@ithinkdt/cloud
Version:
iThinkDT Cloud
556 lines (555 loc) • 17.6 kB
JavaScript
import { merge as B, qsParse as x, HttpError as A } from "@ithinkdt/common";
import { useCoreCtx as H, $fetch as N, registerDict as W, useDict as G } from "@ithinkdt/core";
import { shallowReactive as Y, ref as I, isRef as q, watch as z, reactive as P, unref as V, readonly as v, h as L } from "vue";
const p = {};
let b;
function J(n) {
b = n;
}
function ae({
appCode: n,
immediate: s = !0,
includeApp: c = !0,
includeEmptyApp: l = !0,
includeAction: o = !0
} = {}) {
const { saveIcon: r } = H(), i = Y(/* @__PURE__ */ new Map());
let t;
const e = I([]), h = I(!1), d = (a) => Promise.all([N.get(`${p.SYS}cer/module/list/all`), N.get(`${p.SYS}pub/app/all`)]).then(
([g, u]) => {
t = u, i.clear();
const f = new Map(g.map((y) => [y.id, y]));
a?.trim() ? u = u.filter((y) => y.appCode === a) : l || (u = u.filter((y) => f.get(y.id)?.children?.length));
const O = P(
C(
u.map((y) => ({
id: "app-" + y.id,
asMenu: !0,
isApp: !0,
appId: y.id,
appCode: y.appCode,
icon: y.logo,
moduleName: y.appName,
children: f.get(y.id)?.children ?? []
})),
void 0,
i,
[],
o
)
);
return c ? O : O[0]?.children ?? [];
}
);
q(n) ? z(
n,
async (a) => {
e.value = a ? await d(a) : [];
},
{ immediate: s }
) : d(n).then((a) => {
e.value = a;
});
const m = (a) => {
const g = i.get(a) ?? [];
let u = e.value;
for (let f = c ? 0 : 1; f < g.length - 1; f++)
u = u[g[f]]?.children ?? [];
return u[g.at(-1)] ?? void 0;
}, _ = (a) => {
const g = m(a)?.parentKey;
return g && m(g) || void 0;
}, $ = () => d(V(n)).then((a) => {
e.value = a;
});
function S(a) {
if (a?.length) {
a.sort((g, u) => g.sort - u.sort);
for (const [g, u] of a.entries()) {
const f = i.get(u.id);
f[f.length - 1] = g;
}
}
}
const w = async (a, g = a.key ? _(a.key) : a.parentKey ? m(a.parentKey) : void 0) => {
const u = {
id: a.key,
parentId: a.parentKey,
appId: g?.appId || t.find((f) => f.appCode === a.appCode)?.id,
moduleType: M[a.type],
visiable: a.hidden !== !0,
sortField: a.sort,
moduleUrl: (a.type === "federate" ? a.remote + T : a.type === "lowcode" ? a.lcKey + (a.remote ? R + a.remote : "") + T : "") + a.path,
icon: a.icon,
moduleLevel: a.level,
moduleName: a.label,
moduleNameEn: a.labelEn,
resources: a.resources?.filter((f) => !!f).join(";"),
asMenu: a.type !== "action"
};
if (u.children = a.children?.length ? await Promise.all(
a.children?.map((f) => (f.parentKey ||= "", w(f, u)))
) : void 0, u.icon && typeof u.icon != "string") {
const { id: f } = await r({
...u.icon,
type: "module"
});
u.icon = f;
}
return (u.parentId === void 0 || u.parentId?.startsWith("app-")) && (u.parentId = "0"), u;
}, F = (a, g, u) => {
const f = m(g.parentKey);
let O;
if (u.id) {
const y = m(u.id);
Object.assign(y, g);
} else {
O = U(a, -1, f, i, i.get(g.parentKey), o);
const y = f.children || [];
y.push(O), f.children = y;
}
return S(f?.children), O;
};
return {
tree: e,
loading: h,
getByKey: m,
getParentByKey: _,
refresh: $,
save: async (a) => {
const g = Array.isArray(a), u = await (g ? Promise.all(a.map((f) => w(f))) : w(a));
return N.post(g ? `${p.SYS}cer/module/batch/save` : `${p.SYS}cer/module/save`, u).then((f) => g ? ($(), u.map((O, y) => F(f[y], a[y], O))) : F(f, a, u));
},
del: (a) => {
const g = a.key ?? a;
return N.post(`${p.SYS}cer/module/delete`, { id: g }, { reqType: "urlencoded" }).then(() => {
const u = _(g), f = u.children.findIndex((O) => O.id === g);
f > -1 && u.children.splice(f, 1), S(u.children);
});
}
};
}
const M = {
group: "00",
module: "01",
lowcode: "02",
federate: "03",
external: "04",
other: "99"
}, k = Object.fromEntries(Object.entries(M).map(([n, s]) => [s, n])), T = " | ", R = " @ ", U = (n, s, c, l, o, r) => {
if (!r && !n.isApp && !n.asMenu)
return;
const i = n.resources?.trim();
o = [...o, s], l?.set(n.id, o);
let t = n.asMenu && n.children?.length ? C(n.children, n, l, o, r) : n.isApp ? [] : void 0;
r || (t = t?.filter((_) => !!_), t?.length || (t = void 0));
let e = k[n.moduleType ?? M.module];
e === "group" && (e = "module");
const [h, d] = n.moduleUrl?.split(T) ?? [];
return {
id: n.id,
key: n.id,
parentKey: c?.id,
parent: c,
label: n.moduleName,
labelEn: n.moduleNameEn,
resources: i ? i.split(";") : [],
type: n.isApp ? "other" : n.asMenu ? e : "action",
level: n.moduleLevel,
icon: n.icon,
path: e === "federate" || e === "lowcode" ? d : n.moduleUrl,
remote: e === "federate" ? h : e === "lowcode" ? h.split(R)[1] : void 0,
lcKey: e === "lowcode" ? h.split(R)[0] : void 0,
hidden: n.visiable === !1,
sort: n.sortField,
appId: n.appId,
appCode: n.appCode || c?.appCode,
children: t
};
}, C = (n, s, c, l = [], o) => {
let r = 0;
return n.map((i) => {
const t = U(i, r, s, c, l, o);
return t && r++, t;
});
};
let D;
function K(n, s) {
return fetch(`${n}logout`, {
method: "post",
redirect: "error",
credentials: "omit",
headers: new Headers({
Authorization: `Bearer ${s}`
})
}).catch((c) => {
console.debug("调用登出接口错误", c);
});
}
function Q(n) {
return {
async fetchDicts(s) {
const c = s.length > 1 ? "Types" : "Type", l = await N.get(`${n}cli/dict/value/getBy${c}`, {
[`dict${c}`]: s.join(",")
});
return c === "Types" ? l : { [s[0]]: l };
},
labelGetter: (s, c) => (c === "zh-CN" ? s.dictValue : s.dictValueEn) ?? s.dictValue,
valueGetter: (s) => s.dictKey
};
}
let E;
function Z(n, { _BASE: s, SYS: c, YIDA: l }, o) {
return Promise.all([
o?.length ? Promise.resolve({ data: o }) : fetch(`${s}${c}pub/app/all`, { credentials: "omit" }).then((r) => r.json()).catch((r) => (console.log(`未能获取到前端应用信息 (${r.message}),使用默认配置。`), {
data: []
})),
fetch(`${s}${c}pub/busConfig/getFrontConfig`, { credentials: "omit" }).then((r) => r.json()).catch((r) => (console.log(`未能获取到前端配置 (${r.message}),使用默认配置。`), {
data: []
})),
l ? fetch(`${s}${l}/pub/yida/app/personalize/${n}`).then((r) => r.json()).catch((r) => (console.log(`未能获取到前端配置 (${r.message}),使用默认配置。`), {
data: {}
})) : Promise.resolve({})
]).then(async ([{ data: r }, { data: i }, { data: t = {} }]) => {
const e = {};
for (const d of i)
e[d.configKey] = d.configValue;
E = {};
for (let { appCode: d, url: m = "" } of r)
m.endsWith("/") || (m = m + "/"), E[d] = m, E[d.replaceAll("-", "_").toUpperCase()] = m;
const h = await fetch(
`${s}${c}pub/logo/${r.find((d) => d.appCode === n)?.logo || e.FRONT_LOGO_ID}`
).then((d) => d.text());
return {
...e,
context: E,
apps: r,
appName(d, m) {
const _ = r.find(($) => $.appCode === d);
return _?.[m.startsWith("zh") ? "appName" : "appNameEn"] ?? _?.appName ?? _?.appNameEn ?? "系统";
},
logo: h,
multiTab: t.multiTab ?? e.FRONT_MULTI_TAB === "true",
i18n: e.FRONT_I18N === "true",
accordionMenu: t.accordionMenu ?? e.FRONT_ACCORDION_MENU === "true",
collpaseBtnPlacement: t.collpaseBtnPlacement ?? (e.FRONT_COLLPASE_BTN_PLACEMENT || "default"),
menuPlacement: t.menuPlacement ?? (e.FRONT_MENU_PLACEMENT || "sidebar"),
appearence: t.showAppearence ?? e.FRONT_APPEARENCE === "true",
theme: {
light: JSON.parse(e.FRONT_THEME_LIGHT ?? "{}"),
dark: B({}, JSON.parse(e.FRONT_THEME_LIGHT ?? "{}"), JSON.parse(e.FRONT_THEME_DARK ?? "{}"))
},
locale: e.FRONT_LOCALE || void 0,
watermark: t.watermark ?? e.FRONT_WATERMARK === "true",
renderWatermark: new Function("user", `return (${e.FRONT_WATERMARK_RENDER})`),
footer: e.FRONT_FOOTER.trim() || void 0,
timeout: Number.parseFloat(e.FRONT_REQUEST_TIMEOUT) || void 0,
domain: e.FRONT_COOKIE_DOMAIN || void 0,
sso: e.FRONT_SSO_ENABLED === "false" ? !1 : {
selfLogin: e.FRONT_LOCAL_LOGIN === "true",
login: (d) => new Function("redirect", `return \`${e.FRONT_SSO_LOGIN_URL}\``)(
encodeURIComponent(d)
),
logout: async (d, { appCode: m, username: _, token: $ }) => (await K(s + c, $), new Function(
"redirect",
"appCode",
"username",
`return \`${e.FRONT_SSO_LOGOUT_URL}\``
)(encodeURIComponent(d), encodeURIComponent(m), encodeURIComponent(_))),
parseToken: (d) => {
const m = new URL(d);
return new Function("url", "query", e.FRONT_SSO_PARSE_URL)(
d,
x(m.search || "?" + (m.hash.split("?")[1] || ""))
);
}
}
};
});
}
function j(n, s, c) {
return (n ?? []).map((l) => {
const o = j(l.children, s, c);
let r = l.asMenu ? o.some((h) => h.type !== "action" && h.hidden !== !0) ? "group" : l.moduleType && k[l.moduleType] || "module" : "action", i = l.moduleUrl;
r === "module" && s !== b && (r = "federate", i = s + T + i);
let t, e;
if (r === "federate")
e = i?.split(T)[0], !e || e === b ? (r = "module", e = void 0, i = i?.split(T)[1]) : e = E[e] + "routes.js?_t=" + Date.now();
else if (r === "lowcode") {
const [h] = i?.split(T) ?? [];
t = h?.split(R)[0], e = h?.split(R)[1];
}
return {
key: l.id,
type: r,
label: (c === "zh-CN" ? l.moduleName : l.moduleNameEn) ?? l.moduleName ?? l.text,
hidden: l.visiable === !1,
path: ["federate", "lowcode"].includes(r) ? i.split(T)[1] : i,
remote: e,
lcKey: t,
level: l.moduleLevel,
icon: l.icon,
children: o,
parentKey: l.parentId,
actions: r === "action" ? i?.split(",").filter((h) => !!h) : o.map((h) => h.actions).flat(Number.POSITIVE_INFINITY)
};
});
}
function X(n, s, c) {
return {
login(l) {
return N.post(`${s}login`, l, { alert: !1, redirect: "error" });
},
logout({ token: l }) {
return K(c + s, l);
},
async loadAuthInfo(l, o) {
D = l;
const [r, i] = await Promise.allSettled([
N.get(`${s}cli/userinfo`, void 0, { alert: !1 }),
N.get(`${s}cli/modules`, n ? { appCode: n } : void 0, { alert: !1 })
]);
if (r?.reason instanceof A)
throw r?.reason.code === 403 ? new Error("forbidden") : r?.reason.code === 408 ? new Error("timeout") : r?.reason;
const t = n ? i.value[0]?.children : i.value;
if (t)
for (const e of t)
e.asMenu = !0;
return {
user: {
...r.value,
nickname: r.value.personName
},
modules: j(t, n, o)
};
},
changePwd({ old: l, new: o }) {
return N.post(
`${s}cli/user/password/change`,
{ curPassword: l, newPassword: o },
{ reqType: "urlencoded" }
);
},
jwt: {
headerField: "Authorization",
cookieField: "access_token",
tokenFormatter: (l) => `Bearer ${l}`,
tokenParser: (l) => l?.slice(7),
unauthCodes: [401, 604, 606]
}
};
}
function ee(n, s) {
return {
fileUploader: async (c, { access: l = "INTERNAL", name: o, action: r, field: i = "file", data: t = {}, onUploadProgress: e }) => {
let h = r;
r || (h = `${n.FILE}cer/file/transfer/upload`);
const d = new FormData();
d.append("filename", o || c.name), d.append("accessRight", l);
for (const m of Object.keys(t))
m === "filename" ? d.set(m, t[m]) : d.append(m, t[m]);
return d.append(i, c), await N.post(h, d, {
onUploadProgress: e
}).then((m) => ({
...m[0],
fileId: m[0].id
}));
},
filePreview: (c, l = !0) => `${n._BASE + n.FILE}${l ? "cli/" : "pub/"}file/transfer/preview?id=${c}` + (l ? `&access_token=${encodeURIComponent(`Bearer ${s()}`)}` : ""),
fileDownload: (c, l = !0) => `${n._BASE + n.FILE}${l ? "cli/" : "pub/"}file/transfer/download?id=${c}` + (l ? `&access_token=${encodeURIComponent(`Bearer ${s()}`)}` : ""),
fileInfo: (c) => N.get(`${n.FILE}cli/file/transfer/fileinfo`, {
ids: c
}).then(
(l) => c.map((o) => {
const r = l[o] || {};
return r.id = o, r.fileId = o, r;
})
),
fileRemove: (c) => Promise.resolve(c)
};
}
function te(n) {
const s = /* @__PURE__ */ new Map();
let c;
function l() {
c === void 0 && (setTimeout(() => {
requestIdleCallback(() => {
for (const t of s.keys())
s.get(t).value !== void 0 && s.delete(t);
c = void 0;
});
}, 6e4), c = !0);
}
function o(t) {
return fetch(`${n._BASE + n.SYS}pub/logo/${t}`, {
method: "get",
credentials: "omit"
}).then((e) => e.blob()).then((e) => e.text()).then((e) => {
try {
const h = JSON.parse(e);
return console.debug(`获取图标失败,id: ${t}`, h), "";
} catch {
return e;
} finally {
l();
}
});
}
const r = "data:image/svg+xml;base64,";
function i(t) {
if (s.has(t))
return s.get(t);
const e = I(), h = v(e);
return s.set(t, h), o(t).then((d) => {
e.value = d;
}), h;
}
return {
async saveIcon(t) {
if (t = { type: "other", ...t }, t.body instanceof File) {
const e = t.body;
t.name || (t.name = e.name), t.body = await new Promise((h) => {
const d = new FileReader();
d.addEventListener("load", () => {
h(d.result);
}), d.readAsDataURL(e);
});
}
return N.post(`${n.SYS}cer/logo/save`, {
id: t.id,
name: t.name,
logo: t.body,
type: t.type,
remark: t.remark
}).then((e) => (t.id = e.id, t));
},
getIconUri: i,
getIcon(t) {
const e = i(t);
return v(
P({
id: t,
body: e
})
);
},
getIconRender(t) {
return () => {
let e = i(t).value;
if (e)
return e.startsWith(r) ? (e = window.atob(e.slice(r.length)), L("span", {
innerHTML: e,
style: {
lineHeight: "0"
}
})) : L("img", {
src: e,
style: {
height: "1em"
}
});
};
}
};
}
function le(n, s, c, l = n) {
Object.assign(p, c), J(l), p._BASE = s;
for (const o of Object.keys(p))
p[o].endsWith("/") || (p[o] = p[o] + "/"), p[o].startsWith("/") && (p[o] = p[o].slice(1));
return /^http(s?):\/\//.test(p._BASE) || (p._BASE = "/" + p._BASE), {
loadConfig: (o) => Z(n, p, o),
auth: {
...X(n, p.SYS, p._BASE),
loadMessages({ status: o, pageSize: r, currentPage: i }) {
return N.post(`${p.MC}cli/mc/msgInternal/page`, {
status: o === "read" ? 1 : o === "unread" ? 0 : void 0,
pageSize: r,
pageNumber: i
}).then((t) => {
for (const e of t.records)
e.time = e.createDate, e.status = e.status === 1 ? "read" : "unread", e.action = e.link;
return t;
});
},
readMessages(o) {
return N.post(`${p.MC}cli/mc/msgInternal/read`, o);
},
deleteMessages(o) {
return N.post(`${p.MC}cli/mc/msgInternal/deletes`, o);
}
},
dict: Q(p.DICT),
lang: {
headerField: "Lang",
localeFormatter: (o) => o.replace("-", "_")
},
page: {
...ee(p, () => D),
transformListParams(o, r, i) {
return {
...o,
sortName: r?.name,
sortOrder: r?.order,
...i ? {
pageNumber: i.currentPage,
pageSize: i.pageSize
} : {}
};
},
getUsers(o) {
return N.get(`${p.UC}cli/user/name`, { usernames: o.join(",") }).then((r) => Object.entries(r).map(([i, t]) => ({ username: i, nickname: t })));
},
getDepts(o) {
return N.get(`${p.UC}cli/org/name`, { codes: o.join(",") }).then((r) => Object.entries(r).map(([i, t]) => ({ code: i, name: t })));
}
},
icon: te(p),
msgi: (o, r) => r(o).catch((i) => {
if (i instanceof A && i.code === 501) {
const t = i?.resp?.data?.[0];
i.message = `${i.message}:${t?.fieldLabel || ""} ${t?.msg}`;
}
throw i;
})
};
}
function se() {
return N.get(`${p.BPM}cli/bpm/task/timestamp`, {}, { alert: !1 }).catch(() => Date.now());
}
function ie() {
return N.get(`${p.SYS}cli/login/refresh`);
}
const ce = {
SYSTEM: "SYSTEM",
NORMAL: "NORMAL"
};
function de(n) {
const { dictType: s } = W(
"__roles",
() => N.post(`${p.UC}cer/role/list`, {
pageSize: Math.pow(2, 31) - 1,
pageNumber: 1
}).then((c) => c.records),
{
autoClean: !0,
label: "roleName",
value: "id"
}
);
return G(s, {
onGet: n
});
}
export {
R as MODULE_APP_SPLIT,
T as MODULE_PATH_SPLIT,
ce as RoleType,
le as cloud,
se as getServerDate,
te as icon,
k as moduleTypeMap,
ie as refreshAuthrization,
ae as useModuleTree,
de as useRoleDicts
};
//# sourceMappingURL=index.js.map