20260722173146

This commit is contained in:
oneao committed 2026-07-22 17:31:48 +08:00
1 parent e9f099f044
commit d04fad24ed
24 files changed
+1309 -422

No files matched your search

@@ -0,0 +1,264 @@
<script setup>
import { h, ref } from "vue";
import { message } from "antdv-next";
import { Input, InputNumber, Select } from "antdv-next";
import FmsTable from "@/components/fms-table/FmsTable.vue";
const COLUMN_COUNT = 20;
const ROW_COUNT = 4000;
const STATUS_OPTIONS = [
{ label: "启用", value: 1 },
{ label: "禁用", value: 0 },
];
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randText(len) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let s = "";
for (let i = 0; i < len; i++) s += chars[randInt(0, chars.length - 1)];
return s;
}
function generateValue(c, i) {
switch (c % 5) {
case 0:
return randText(randInt(4, 10));
case 1:
return randInt(0, 99999);
case 2:
return STATUS_OPTIONS[randInt(0, 1)].value;
case 3:
return `名称-${i}-${c}`;
default:
return `${randInt(1000, 9999)}-${randText(4)}`;
}
}
function buildData() {
const rows = [];
for (let i = 0; i < ROW_COUNT; i++) {
const row = { id: `R${i}` };
for (let c = 1; c <= COLUMN_COUNT; c++) row[`col${c}`] = generateValue(c, i);
rows.push(row);
}
return rows;
}
const dataSource = ref(buildData());
// 当前编辑行 key;进入编辑时留存快照,取消可还原
const editingKey = ref(null);
const editSnapshot = ref(null);
function editConfigFor(c) {
switch (c % 5) {
case 1:
return { type: "number" };
case 2:
return { type: "select", options: STATUS_OPTIONS };
default:
return { type: "text", maxlength: 64 };
}
}
// 单元格渲染:编辑行显示控件,其他行显示纯文本
function makeCellEditor(dataIndex, edit) {
return (props) => {
const { row, cellValue } = props;
if (row.id !== editingKey.value) {
if (edit.type === "select") {
const opt = (edit.options || []).find((o) => o.value === cellValue);
return h("span", { class: "cell-display" }, opt ? opt.label : cellValue ?? "");
}
return h("span", { class: "cell-display" }, cellValue ?? "");
}
const update = (v) => {
row[dataIndex] = v;
};
const common = {
size: "small",
style: { width: "100%" },
onClick: (e) => e.stopPropagation(),
};
if (edit.type === "number") {
return h(InputNumber, {
...common,
value: cellValue,
min: edit.min,
max: edit.max,
precision: edit.precision,
"onUpdate:value": update,
});
}
if (edit.type === "select") {
return h(Select, {
...common,
value: cellValue,
options: edit.options || [],
"onUpdate:value": update,
});
}
return h(Input, {
...common,
value: cellValue,
maxlength: edit.maxlength,
"onUpdate:value": update,
});
};
}
function buildColumns() {
const cols = [
{
dataIndex: "id",
title: "编码",
width: 120,
fixed: "left",
customCell: makeCellEditor("id", { type: "text", maxlength: 32 }),
},
];
for (let c = 1; c <= COLUMN_COUNT; c++) {
const edit = editConfigFor(c);
cols.push({
dataIndex: `col${c}`,
title: `列 ${c}`,
width: 140,
sorter: edit.type === "number" ? true : undefined,
customCell: makeCellEditor(`col${c}`, edit),
});
}
return cols;
}
const columns = ref(buildColumns());
function onRowClick(ev, row) {
if (row.id === editingKey.value) return;
editingKey.value = row.id;
editSnapshot.value = JSON.parse(JSON.stringify(row));
}
function saveEdit() {
if (editingKey.value == null) return;
editingKey.value = null;
editSnapshot.value = null;
message.success("已保存当前行修改");
}
function cancelEdit() {
if (editingKey.value != null && editSnapshot.value) {
const idx = dataSource.value.findIndex((r) => r.id === editingKey.value);
if (idx >= 0) dataSource.value[idx] = editSnapshot.value;
}
editingKey.value = null;
editSnapshot.value = null;
message.info("已取消编辑");
}
function regenerate() {
editingKey.value = null;
editSnapshot.value = null;
dataSource.value = buildData();
message.success("已重新生成随机数据");
}
function rowClassName(row) {
return row.id === editingKey.value ? "fms-row-editing" : "";
}
</script>
<template>
<main class="table-demo">
<header class="table-demo__toolbar">
<div class="table-demo__title">
<strong>大数据表格 Demo</strong>
<span class="table-demo__meta">
共 {{ dataSource.length }} 行 · {{ columns.length }} 列 ·
<template v-if="editingKey">正在编辑:{{ editingKey }}</template>
<template v-else>点击任意行进入编辑</template>
</span>
</div>
<div class="table-demo__actions">
<a-button :disabled="editingKey == null" type="primary" @click="saveEdit">保存</a-button>
<a-button :disabled="editingKey == null" @click="cancelEdit">取消</a-button>
<a-button @click="regenerate">重新生成</a-button>
</div>
</header>
<section class="table-demo__body">
<FmsTable
v-model:columns="columns"
:data-source="dataSource"
row-key="id"
:row-class-name="rowClassName"
@row-click="onRowClick"
/>
</section>
</main>
</template>
<style scoped>
.table-demo {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 0;
color: var(--fms-text);
background: var(--fms-surface);
}
.table-demo__toolbar {
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 12px 16px;
border-bottom: 1px solid var(--fms-border);
}
.table-demo__title {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.table-demo__title strong {
font-size: 15px;
font-weight: 600;
}
.table-demo__meta {
color: var(--fms-text-secondary);
font-size: 12px;
}
.table-demo__actions {
display: flex;
flex: none;
gap: 8px;
}
.table-demo__body {
flex: 1;
min-height: 0;
padding: 12px 16px 16px;
}
:deep(.fms-row-editing) {
background: rgba(22, 119, 255, 0.08) !important;
}
:deep(.cell-display) {
display: block;
min-height: 22px;
padding: 0 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
@@ -3,7 +3,7 @@ import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { App } from "antdv-next";
import { Languages, Plus, RefreshCw, RotateCcw, Save, Trash2 } from "@lucide/vue";
import FmsTable from "@/components/FmsTable.vue";
import FmsTable from "@/components/fms-table/FmsTable.vue";
import { loadDataApi, nextIdApi, saveObjectApi } from "@/services/api";
import { useAuthStore } from "@/stores/auth";
import { usePermissionStore } from "@/stores/permissions";
@@ -40,6 +40,7 @@ function updateRoute(value) {
<ModuleTranslationEditor
v-model:translations="translations"
:i18n-key="module.b_i18n"
:default-name="module.b_name"
:disabled="!module.b_i18n?.trim()"
/>
</div>
@@ -80,6 +81,7 @@ function updateRoute(value) {
<ModuleTranslationEditor
v-model:translations="translations"
:i18n-key="module.b_i18n"
:default-name="module.b_name"
:disabled="!module.b_i18n?.trim()"
/>
</div>
@@ -1,57 +1,83 @@
<script setup>
import { computed, ref, watch } from "vue";
import { ref } from "vue";
import { App } from "antdv-next";
import { Plus, Trash2 } from "@lucide/vue";
import FmsTable from "@/components/FmsTable.vue";
import { nextIdApi } from "@/services/api";
import { RefreshCw } from "@lucide/vue";
import FmsTable from "@/components/fms-table/FmsTable.vue";
import { describeApi } from "@/services/api";
import { createTempId } from "@/utils/tempId";
import { createI18nCellRenderer } from "./createI18nCellRenderer";
import ModuleTranslationEditor from "./ModuleTranslationEditor.vue";
const props = defineProps({
moduleId: { type: [String, Number], default: "" },
moduleCode: { type: String, default: "" },
// 字段来源:模块配置的查询表或视图,为空时无法同步。
viewTable: { type: String, default: "" },
});
const fields = defineModel("fields", { type: Array, default: () => [] });
const translations = defineModel("translations", { type: Object, default: () => ({}) });
const { message } = App.useApp();
const adding = ref(false);
const selectedRowKeys = ref([]);
// 当前编辑行 key;点击某行进入单行编辑,再次点击退出。
const activeRowKey = ref(null);
const syncing = ref(false);
const translationEditorRef = ref(null);
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys;
},
}));
const renderI18nCell = createI18nCellRenderer({
activeRowKey,
translationEditorRef,
});
watch(
() => fields.value.map((item) => String(item.b_id)),
(keys) => {
const available = new Set(keys);
selectedRowKeys.value = selectedRowKeys.value.filter((key) => available.has(String(key)));
},
);
function nextFieldCode() {
const existing = new Set(fields.value.map((item) => item.b_field));
let index = 1;
while (existing.has(`b_new_${index}`)) index += 1;
return `b_new_${index}`;
function onRowClick(_ev, row) {
const key = String(row.b_id);
activeRowKey.value = activeRowKey.value === key ? null : key;
}
async function onAdd() {
if (!props.moduleId || adding.value) return;
adding.value = true;
function mapType(type) {
const t = String(type || "").toLowerCase();
if (t.includes("bit")) return "boolean";
if (/(tinyint|smallint|int|bigint|decimal|numeric|float|real|money|smallmoney)/.test(t)) {
return "number";
}
if (/(datetime|smalldatetime|date|time)/.test(t)) return "date";
if (/(text|ntext)/.test(t)) return "text";
return "string";
}
// 从视图同步字段:保留已有配置,追加视图新增列,移除视图已不存在的列。
async function syncFields() {
const source = props.viewTable;
if (!source) {
message.warning("请先在基本信息中配置查询表或视图");
return;
}
syncing.value = true;
try {
const code = nextFieldCode();
const id = String((await nextIdApi()).data);
fields.value = [
...fields.value,
{
b_id: id,
const columns = (await describeApi(source)).data || [];
if (!columns.length) {
message.warning("该视图没有可识别的列");
return;
}
const existingByField = new Map(fields.value.map((item) => [item.b_field, item]));
const merged = [];
let maxXh = 0;
fields.value.forEach((item) => {
if (columns.some((col) => col.name === item.b_field)) {
merged.push(item);
maxXh = Math.max(maxXh, Number(item.b_xh) || 0);
}
});
for (const col of columns) {
if (existingByField.has(col.name)) continue;
maxXh += 10;
merged.push({
b_id: createTempId(),
b_module_id: props.moduleId,
b_field: code,
b_name: "新字段",
b_i18n: props.moduleCode ? `field.${props.moduleCode}.${code}` : null,
b_type: "string",
b_field: col.name,
b_name: col.name,
b_i18n: props.moduleCode ? `field.${props.moduleCode}.${col.name}` : null,
b_type: mapType(col.type),
b_canlist: 1,
b_canform: 1,
b_must: 0,
@@ -59,27 +85,28 @@ async function onAdd() {
b_readonly: 0,
b_width: 120,
b_value: null,
b_xh: (fields.value.length + 1) * 10,
b_xh: maxXh,
b_canuse: 1,
},
];
});
}
fields.value = merged;
message.success(`已同步 ${columns.length} 个字段`);
} catch (error) {
message.error(error.message || "字段创建失败");
message.error(error.message || "字段同步失败");
} finally {
adding.value = false;
syncing.value = false;
}
}
function onBatchDelete() {
const selected = new Set(selectedRowKeys.value.map(String));
fields.value = fields.value.filter((item) => !selected.has(String(item.b_id)));
selectedRowKeys.value = [];
}
const columns = ref([
{
dataIndex: "b_i18n",
title: "多语言键",
width: 250,
customCell: renderI18nCell,
},
{ dataIndex: "b_field", title: "字段", width: 150, editor: { maxlength: 50 } },
{ dataIndex: "b_name", title: "名称", width: 150, editor: { maxlength: 100 } },
{ dataIndex: "b_i18n", title: "多语言键", width: 230, editor: { maxlength: 150 } },
{
dataIndex: "b_type",
title: "类型",
@@ -145,13 +172,9 @@ const columns = ref([
<template>
<section class="table-pane">
<div class="toolbar">
<a-button type="primary" :loading="adding" @click="onAdd">
<template #icon><Plus /></template>
新增
</a-button>
<a-button danger :disabled="!selectedRowKeys.length" @click="onBatchDelete">
<template #icon><Trash2 /></template>
批量删除
<a-button type="primary" :loading="syncing" @click="syncFields">
<template #icon><RefreshCw /></template>
同步字段
</a-button>
</div>
<FmsTable
@@ -159,8 +182,10 @@ const columns = ref([
row-key="b_id"
v-model:columns="columns"
:data-source="fields"
:row-selection="rowSelection"
:active-row-key="activeRowKey"
@row-click="onRowClick"
/>
<ModuleTranslationEditor ref="translationEditorRef" v-model:translations="translations" />
</section>
</template>
@@ -178,6 +203,7 @@ const columns = ref([
gap: 8px;
flex: none;
padding: 10px 0;
align-items: center;
}
.sub-table {
@@ -1,9 +1,10 @@
<script setup>
import { computed, ref, watch } from "vue";
import { App } from "antdv-next";
import { Plus, Trash2 } from "@lucide/vue";
import FmsTable from "@/components/FmsTable.vue";
import { nextIdApi } from "@/services/api";
import FmsTable from "@/components/fms-table/FmsTable.vue";
import { createTempId } from "@/utils/tempId";
import { createI18nCellRenderer } from "./createI18nCellRenderer";
import ModuleTranslationEditor from "./ModuleTranslationEditor.vue";
const props = defineProps({
moduleId: { type: [String, Number], default: "" },
@@ -11,9 +12,21 @@ const props = defineProps({
});
const powers = defineModel("powers", { type: Array, default: () => [] });
const { message } = App.useApp();
const adding = ref(false);
const translations = defineModel("translations", { type: Object, default: () => ({}) });
const selectedRowKeys = ref([]);
// 当前编辑行 key;点击某行进入单行编辑,再次点击退出。
const activeRowKey = ref(null);
const translationEditorRef = ref(null);
const renderI18nCell = createI18nCellRenderer({
activeRowKey,
translationEditorRef,
});
function onRowClick(_ev, row) {
const key = String(row.b_id);
activeRowKey.value = activeRowKey.value === key ? null : key;
}
const rowSelection = computed(() => ({
selectedRowKeys: selectedRowKeys.value,
@@ -37,41 +50,42 @@ function nextPowerCode() {
return `new_${index}`;
}
async function onAdd() {
if (!props.moduleId || adding.value) return;
adding.value = true;
try {
const code = nextPowerCode();
const id = String((await nextIdApi()).data);
powers.value = [
...powers.value,
{
b_id: id,
b_module_id: props.moduleId,
b_code: code,
b_name: "新权限",
b_i18n: props.moduleCode ? `power.${props.moduleCode}.${code}` : null,
b_canuse: 1,
b_xh: (powers.value.length + 1) * 10,
},
];
} catch (error) {
message.error(error.message || "权限创建失败");
} finally {
adding.value = false;
}
function onAdd() {
if (!props.moduleId) return;
const code = nextPowerCode();
powers.value = [
...powers.value,
{
b_id: createTempId(),
b_module_id: props.moduleId,
b_code: code,
b_name: "新权限",
b_i18n: props.moduleCode ? `power.${props.moduleCode}.${code}` : null,
b_canuse: 1,
b_xh: (powers.value.length + 1) * 10,
},
];
activeRowKey.value = powers.value[powers.value.length - 1].b_id;
}
function onBatchDelete() {
const selected = new Set(selectedRowKeys.value.map(String));
powers.value = powers.value.filter((item) => !selected.has(String(item.b_id)));
selectedRowKeys.value = [];
if (activeRowKey.value && selected.has(String(activeRowKey.value))) {
activeRowKey.value = null;
}
}
const columns = ref([
{
dataIndex: "b_i18n",
title: "多语言键",
width: 250,
customCell: renderI18nCell,
},
{ dataIndex: "b_code", title: "权限代码", width: 180, editor: { maxlength: 50 } },
{ dataIndex: "b_name", title: "名称", width: 180, editor: { maxlength: 100 } },
{ dataIndex: "b_i18n", title: "多语言键", width: 240, editor: { maxlength: 150 } },
{
dataIndex: "b_canuse",
title: "启用",
@@ -87,7 +101,7 @@ const columns = ref([
<template>
<section class="table-pane">
<div class="toolbar">
<a-button type="primary" :loading="adding" @click="onAdd">
<a-button type="primary" @click="onAdd">
<template #icon><Plus /></template>
新增
</a-button>
@@ -102,7 +116,10 @@ const columns = ref([
v-model:columns="columns"
:data-source="powers"
:row-selection="rowSelection"
:active-row-key="activeRowKey"
@row-click="onRowClick"
/>
<ModuleTranslationEditor ref="translationEditorRef" v-model:translations="translations" />
</section>
</template>
@@ -1,5 +1,5 @@
<script setup>
import { reactive } from "vue";
import { computed, reactive } from "vue";
import { App } from "antdv-next";
import { Languages } from "@lucide/vue";
import { I18N_LOCALES, isValidI18nKey } from "@/utils/i18n";
@@ -7,25 +7,50 @@ import { I18N_LOCALES, isValidI18nKey } from "@/utils/i18n";
const props = defineProps({
i18nKey: { type: String, default: "" },
disabled: { type: Boolean, default: false },
// 默认语言(由 b_name 承载),不在此编辑器中维护,避免两份中文名互相脱节。
defaultLocale: { type: String, default: "zh-CN" },
// 默认语言对应的名称(如 b_name 的中文名),仅展示用,帮助辨识所属对象。
defaultName: { type: String, default: "" },
});
const translations = defineModel("translations", { type: Object, default: () => ({}) });
const { message } = App.useApp();
const dialog = reactive({ open: false, key: "", values: {} });
const dialog = reactive({ open: false, key: "", name: "", values: {} });
function openEditor() {
const key = props.i18nKey.trim();
// 仅维护非默认语言;默认语言(zh-CN)由对应实体的 b_name 字段承载。
const editableLocales = computed(() =>
I18N_LOCALES.filter((locale) => locale.value !== props.defaultLocale),
);
const defaultLocaleLabel = computed(
() =>
I18N_LOCALES.find((locale) => locale.value === props.defaultLocale)?.label ||
props.defaultLocale,
);
// 支持两种打开方式:
// 1) 自带按钮点击:使用 props.i18nKey / props.defaultName
// 2) 表格内按行打开:传入 key / name(如字段、权限的某行)
function openEditor(forceKey, forceName) {
const key = String(forceKey ?? props.i18nKey).trim();
const name = forceName ?? props.defaultName;
if (!isValidI18nKey(key)) {
message.warning("请先填写正确的多语言键");
return;
}
dialog.key = key;
dialog.name = name || "";
dialog.values = Object.fromEntries(
I18N_LOCALES.map((locale) => [locale.value, translations.value[key]?.[locale.value] || ""]),
editableLocales.value.map((locale) => [
locale.value,
translations.value[key]?.[locale.value] || "",
]),
);
dialog.open = true;
}
defineExpose({ open: openEditor });
function saveTranslations() {
// 整条 key 只写非默认语言,顺带清掉历史残留的默认语言翻译,杜绝覆盖 b_name。
translations.value = {
...translations.value,
[dialog.key]: { ...dialog.values },
@@ -35,7 +60,7 @@ function saveTranslations() {
</script>
<template>
<a-button :disabled="disabled" @click="openEditor">
<a-button v-if="i18nKey" :disabled="disabled" @click="openEditor">
<template #icon><Languages /></template>
多语言
</a-button>
@@ -49,9 +74,12 @@ function saveTranslations() {
>
<a-form layout="vertical">
<a-form-item label="多语言键">
<a-input :value="dialog.key" disabled />
<a-input :value="dialog.key" readonly />
</a-form-item>
<a-form-item v-for="locale in I18N_LOCALES" :key="locale.value" :label="locale.label">
<a-form-item :label="`${defaultLocaleLabel}(默认语言)`">
<a-input :value="dialog.name" readonly />
</a-form-item>
<a-form-item v-for="locale in editableLocales" :key="locale.value" :label="locale.label">
<a-input v-model:value="dialog.values[locale.value]" :maxlength="500" />
</a-form-item>
</a-form>
@@ -0,0 +1,64 @@
import { h } from "vue";
import { Input } from "antdv-next";
import { Languages } from "@lucide/vue";
const cellStyle = {
display: "flex",
alignItems: "center",
gap: "4px",
width: "100%",
};
const inputStyle = { flex: "1 1 auto", minWidth: 0 };
const textStyle = {
flex: "1 1 auto",
minWidth: 0,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
};
const iconStyle = {
display: "inline-flex",
flex: "none",
alignItems: "center",
justifyContent: "center",
width: "24px",
height: "24px",
cursor: "pointer",
color: "var(--ant-color-primary, #1677ff)",
};
export function createI18nCellRenderer({ activeRowKey, translationEditorRef }) {
return function renderI18nCell({ row }) {
const editing = activeRowKey.value != null && String(row.b_id) === String(activeRowKey.value);
return h("div", { style: cellStyle }, [
editing
? h("div", { style: inputStyle }, [
h(Input, {
value: row.b_i18n,
size: "small",
maxlength: 150,
allowClear: true,
style: { width: "100%" },
onClick: (event) => event.stopPropagation(),
"onUpdate:value": (value) => {
row.b_i18n = value;
},
}),
])
: h("span", { style: textStyle }, row.b_i18n ?? ""),
h(
"span",
{
style: iconStyle,
title: "编辑翻译",
onClick: (event) => {
event.stopPropagation();
translationEditorRef.value?.open(row.b_i18n, row.b_name);
},
},
[h(Languages, { size: 16 })],
),
]);
};
}
@@ -3,15 +3,20 @@ import { computed, onMounted, reactive, ref } from "vue";
import { App } from "antdv-next";
import { Database, FileText, RotateCcw, Save, ShieldCheck, Trash2 } from "@lucide/vue";
import { loadDataApi, nextIdApi, saveObjectApi } from "@/services/api";
import { createTempId } from "@/utils/tempId";
import { useAuthStore } from "@/stores/auth";
import { usePermissionStore } from "@/stores/permissions";
import { I18N_LOCALE_CODES } from "@/utils/i18n";
// 默认语言:由实体的 b_name 字段承载,不写入 b_i18n 翻译表(方案 A)。
const I18N_DEFAULT_LOCALE = "zh-CN";
import ModuleBasicInfoPanel from "./components/ModuleBasicInfoPanel.vue";
import ModuleFieldDefinitionPanel from "./components/ModuleFieldDefinitionPanel.vue";
import ModulePowerPanel from "./components/ModulePowerPanel.vue";
import ModuleTreePanel from "./components/ModuleTreePanel.vue";
const PROTECTED_MODULE_CODES = ["m_module", "m_i18n", "m_biz"];
// 受保护的模块(禁止删除)。当前放开为可删除,留空即不做保护。
const PROTECTED_MODULE_CODES = [];
const { message } = App.useApp();
const authStore = useAuthStore();
const permissionStore = usePermissionStore();
@@ -22,8 +27,8 @@ const activeTab = ref("basic");
const isNew = ref(false);
const deleteConfirmOpen = ref(false);
const pendingDeleteKey = ref("");
const original = ref("");
const originalTranslationKeys = ref([]);
let originalDraft = null;
const data = reactive({
modules: [],
fields: [],
@@ -38,7 +43,6 @@ const canCreate = computed(() => permissionStore.canPower("m_module", "create"))
const canUpdate = computed(() => permissionStore.canPower("m_module", "update"));
const canDelete = computed(() => permissionStore.canPower("m_module", "delete"));
const canSave = computed(() => (isNew.value ? canCreate.value : canUpdate.value));
const dirty = computed(() => Boolean(draft.module) && serializeDraft() !== original.value);
const parentOptions = computed(() =>
data.modules
.filter((item) => item.b_id !== draft.module?.b_id && item.b_type !== "data")
@@ -61,15 +65,6 @@ function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function serializeDraft() {
return JSON.stringify({
module: draft.module,
fields: draft.fields,
powers: draft.powers,
translations: draft.translations,
});
}
function rowKeys() {
return [
draft.module?.b_i18n,
@@ -85,7 +80,7 @@ function clearDraft() {
draft.fields = [];
draft.powers = [];
draft.translations = {};
original.value = "";
originalDraft = null;
originalTranslationKeys.value = [];
activeTab.value = "basic";
}
@@ -108,12 +103,18 @@ function selectModule(moduleCode) {
data.translations
.filter((item) => keys.has(item.b_key))
.forEach((item) => {
if (item.b_locale === I18N_DEFAULT_LOCALE) return;
draft.translations[item.b_key] ||= {};
draft.translations[item.b_key][item.b_locale] = item.b_value;
});
originalTranslationKeys.value = Array.from(keys);
original.value = serializeDraft();
originalDraft = clone({
module: draft.module,
fields: draft.fields,
powers: draft.powers,
translations: draft.translations,
});
if (module.b_type === "directory") activeTab.value = "basic";
}
@@ -189,12 +190,10 @@ async function addModule(kind, contextKey) {
draft.fields = [];
draft.powers = [];
originalTranslationKeys.value = [];
draft.translations = {
["module." + code]: { "zh-CN": draft.module.b_name },
};
draft.translations = {};
originalDraft = { module: null, fields: [], powers: [], translations: {} };
selectedKey.value = code;
isNew.value = true;
original.value = "";
activeTab.value = "basic";
}
@@ -278,6 +277,10 @@ function diffRows(current, previous) {
};
}
function sameRecord(current, previous) {
return JSON.stringify(current) === JSON.stringify(previous);
}
async function translationChanges(previousKeys) {
const currentKeys = new Set([...rowKeys(), ...Object.keys(draft.translations)]);
const relevantKeys = new Set([...previousKeys, ...currentKeys]);
@@ -285,8 +288,9 @@ async function translationChanges(previousKeys) {
const desired = [];
const missing = [];
const editableLocales = I18N_LOCALE_CODES.filter((locale) => locale !== I18N_DEFAULT_LOCALE);
for (const key of currentKeys) {
for (const locale of I18N_LOCALE_CODES) {
for (const locale of editableLocales) {
const value = draft.translations[key]?.[locale]?.trim();
if (!value) continue;
const old = oldRows.find((item) => item.b_key === key && item.b_locale === locale);
@@ -301,15 +305,10 @@ async function translationChanges(previousKeys) {
.filter((item) => !I18N_LOCALE_CODES.includes(item.b_locale))
.forEach((item) => desired.push(item));
const ids = [];
for (let index = 0; index < missing.length; index += 1) {
const response = await nextIdApi();
ids.push(String(response.data));
}
const now = new Date().toISOString().slice(0, 19).replace("T", " ");
missing.forEach((item, index) => {
missing.forEach((item) => {
desired.push({
b_id: ids[index],
b_id: createTempId(),
b_key: item.key,
b_locale: item.locale,
b_value: item.value,
@@ -339,15 +338,9 @@ async function saveModule() {
saving.value = true;
try {
const oldModule = isNew.value
? null
: data.modules.find((item) => item.b_code === selectedKey.value);
const oldFields = oldModule
? data.fields.filter((item) => item.b_module_id === oldModule.b_id)
: [];
const oldPowers = oldModule
? data.powers.filter((item) => item.b_module_id === oldModule.b_id)
: [];
const oldModule = originalDraft?.module ?? null;
const oldFields = originalDraft?.fields ?? [];
const oldPowers = originalDraft?.powers ?? [];
const previousKeys = new Set(
[
...originalTranslationKeys.value,
@@ -380,18 +373,21 @@ async function saveModule() {
table: "b_module",
key_field: "b_id",
inserts: isNew.value ? [draft.module] : [],
updates: isNew.value ? [] : [draft.module],
updates: !isNew.value && !sameRecord(draft.module, oldModule) ? [draft.module] : [],
deletes: [],
},
{ table: "b_module_field", key_field: "b_id", ...fieldChanges },
{ table: "b_module_power", key_field: "b_id", ...powerChanges },
{ table: "b_i18n", key_field: "b_id", ...i18nChanges },
);
await saveObjectApi(
requests.filter(
(request) => request.inserts.length || request.updates.length || request.deletes.length,
),
const pendingRequests = requests.filter(
(request) => request.inserts.length || request.updates.length || request.deletes.length,
);
if (!pendingRequests.length) {
message.info("没有需要保存的修改");
return;
}
await saveObjectApi(pendingRequests);
const savedKey = draft.module.b_code;
message.success("模块配置已保存");
@@ -553,9 +549,7 @@ onMounted(async () => {
</div>
<div class="header-actions">
<a-button :disabled="!dirty" @click="resetDraft">
<RotateCcw :size="15" />取消
</a-button>
<a-button @click="resetDraft"> <RotateCcw :size="15" />取消 </a-button>
<a-popconfirm
title="确定删除当前模块吗?"
:disabled="
@@ -572,12 +566,7 @@ onMounted(async () => {
<Trash2 :size="15" />删除
</a-button>
</a-popconfirm>
<a-button
type="primary"
:loading="saving"
:disabled="!dirty || !canSave"
@click="saveModule"
>
<a-button type="primary" :loading="saving" :disabled="!canSave" @click="saveModule">
<Save :size="15" />保存
</a-button>
</div>
@@ -604,8 +593,10 @@ onMounted(async () => {
</template>
<ModuleFieldDefinitionPanel
v-model:fields="draft.fields"
v-model:translations="draft.translations"
:module-id="draft.module.b_id"
:module-code="draft.module.b_code"
:view-table="draft.module.b_viewtable || draft.module.b_savetable"
/>
</a-tab-pane>
<a-tab-pane v-if="draft.module.b_type !== 'directory'" key="powers">
@@ -616,6 +607,7 @@ onMounted(async () => {
</template>
<ModulePowerPanel
v-model:powers="draft.powers"
v-model:translations="draft.translations"
:module-id="draft.module.b_id"
:module-code="draft.module.b_code"
/>