Quellcode durchsuchen

feat(data-platform): 完成 1.1.1 租户工厂数据集管理并更新进度

YY968XX vor 2 Tagen
Ursprung
Commit
10216cf8d8

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.424",
+	"version": "2.4.425",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 55 - 0
Web/src/views/aidop/data-platform/api/ingestDatasets.ts

@@ -0,0 +1,55 @@
+import service from '/@/utils/request';
+
+const endpoint = '/api/DataPlatform/ingest-datasets';
+
+export interface IngestSource {
+	id: string;
+	sourceCode: string;
+	sourceName: string;
+	enabled: boolean;
+}
+
+export interface IngestDataset {
+	id: string;
+	datasetKey: string;
+	name: string;
+	enabled: boolean;
+	activeSchemaVersion: string | null;
+	revision: number;
+	versions: string[];
+	bindings: { sourceId: string; sourceName: string | null; sourceEnabled: boolean }[];
+}
+
+interface IngestWorkspace {
+	factoryId: string;
+	factoryName: string;
+	sources: IngestSource[];
+	list: IngestDataset[];
+}
+
+export async function fetchIngestDatasets(factoryId?: string): Promise<IngestWorkspace> {
+	return (await service.get<IngestWorkspace>(endpoint, { params: { factoryId } })).data;
+}
+
+export function createIngestDataset(datasetKey: string, name: string, factoryId?: string) {
+	return service.post(endpoint, { datasetKey, name }, { params: { factoryId } });
+}
+
+export function setIngestDatasetSource(dataset: IngestDataset, sourceId: string, enabled: boolean, factoryId?: string) {
+	return service.put(`${endpoint}/${dataset.id}/sources/${sourceId}`, { revision: dataset.revision, enabled }, { params: { factoryId } });
+}
+
+export interface DatasetFactory {
+	id: string;
+	name: string;
+	isDefault: boolean;
+}
+export async function fetchDatasetFactories(): Promise<DatasetFactory[]> {
+	return (await service.get<DatasetFactory[]>(endpoint + '/factories')).data;
+}
+export async function availableFactoryOrganizations(): Promise<{ id: string; name: string }[]> {
+	return (await service.get(endpoint + '/factories/available')).data;
+}
+export function registerFactory(id: string) {
+	return service.post(endpoint + '/factories/' + id);
+}

+ 217 - 0
Web/src/views/aidop/data-platform/components/MdpIngestDatasetDrawer.vue

@@ -0,0 +1,217 @@
+<script setup lang="ts">
+import { computed, reactive, shallowRef, watch } from 'vue';
+import { ElMessage } from 'element-plus';
+import {
+	createIngestDataset,
+	fetchIngestDatasets,
+	setIngestDatasetSource,
+	fetchDatasetFactories,
+	availableFactoryOrganizations,
+	registerFactory,
+	type DatasetFactory,
+	type IngestDataset,
+} from '../api/ingestDatasets';
+
+type Action = 'create' | 'bind';
+
+const open = defineModel<boolean>({ required: true });
+const workspace = shallowRef<Awaited<ReturnType<typeof fetchIngestDatasets>>>();
+const factories = shallowRef<DatasetFactory[]>([]);
+const factoryId = shallowRef('');
+const eligible = shallowRef<{ id: string; name: string }[]>([]);
+const registration = shallowRef('');
+let sequence = 0;
+const loading = shallowRef(false);
+const saving = shallowRef(false);
+const loadError = shallowRef('');
+const action = shallowRef<Action | null>(null);
+const selected = shallowRef<IngestDataset>();
+const form = reactive({ datasetKey: '', name: '', sourceId: '' });
+
+const availableSources = computed(() => (workspace.value?.sources ?? []).filter((source) => source.enabled && !selected.value?.bindings.some((binding) => binding.sourceId === source.id)));
+const dialogTitle = computed(
+	() =>
+		({
+			create: '新建数据集',
+			bind: '绑定来源',
+		})[action.value ?? 'create']
+);
+
+watch(
+	open,
+	(visible) => {
+		if (visible) void load();
+	},
+	{ immediate: true }
+);
+
+async function load() {
+	const request = ++sequence;
+	loading.value = true;
+	loadError.value = '';
+	workspace.value = undefined;
+	try {
+		const [choices, options] = await Promise.all([fetchDatasetFactories(), availableFactoryOrganizations()]);
+		if (request !== sequence) return;
+		factories.value = choices;
+		eligible.value = options;
+		if (!choices.some((f) => f.id === factoryId.value)) {
+			factoryId.value = choices.find((f) => f.isDefault)?.id ?? (choices.length === 1 ? choices[0].id : '');
+		}
+		if (!factoryId.value) {
+			loadError.value = choices.length ? '请选择要管理的工厂' : '当前账号没有已授权的有效工厂';
+			return;
+		}
+		const data = await fetchIngestDatasets(factoryId.value);
+		if (request === sequence) workspace.value = data;
+	} catch {
+		if (request === sequence) loadError.value = '无法读取工厂或数据集,请核对权限与服务状态。';
+	} finally {
+		if (request === sequence) loading.value = false;
+	}
+}
+
+function edit(next: Action, dataset?: IngestDataset) {
+	selected.value = dataset;
+	Object.assign(form, {
+		datasetKey: '',
+		name: '',
+		sourceId: '',
+	});
+	action.value = next;
+}
+
+async function save() {
+	if (action.value === 'create') {
+		const key = form.datasetKey.trim();
+		const name = form.name.trim();
+		if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(key) || !name) {
+			ElMessage.warning('请输入有效的数据集编码和名称');
+			return;
+		}
+		await apply(() => createIngestDataset(key, name, factoryId.value));
+	} else if (selected.value && action.value === 'bind' && form.sourceId) {
+		const dataset = selected.value;
+		await apply(() => setIngestDatasetSource(dataset, form.sourceId, true, factoryId.value));
+	}
+}
+
+async function apply(write: () => Promise<unknown>) {
+	if (saving.value) return;
+	saving.value = true;
+	try {
+		await write();
+		action.value = null;
+		ElMessage.success('已保存');
+		await load();
+	} catch {
+		// 请求拦截器展示后台返回的原因。刷新列表后可按当前版本重试。
+		action.value = null;
+		await load();
+	} finally {
+		saving.value = false;
+	}
+}
+</script>
+
+<template>
+	<el-drawer v-model="open" title="接收数据集" size="min(100%, 940px)" destroy-on-close>
+		<el-alert v-if="loadError" :title="loadError" type="error" :closable="false" show-icon />
+		<div v-if="eligible.length" class="dataset-toolbar">
+			<el-select v-model="registration" filterable placeholder="选择需登记为工厂的机构"><el-option v-for="org in eligible" :key="org.id" :label="org.name" :value="org.id" /></el-select>
+			<el-button
+				:disabled="saving || !registration"
+				@click="
+					apply(async () => {
+						await registerFactory(registration);
+						factoryId = registration;
+						registration = '';
+					})
+				"
+				>登记为工厂</el-button
+			>
+		</div>
+		<div class="dataset-toolbar">
+			<el-select v-model="factoryId" aria-label="当前工厂" placeholder="请选择工厂" :disabled="saving || !!action" style="width: 230px" @change="load">
+				<el-option v-for="f in factories" :key="f.id" :value="f.id" :label="f.name" />
+			</el-select>
+			<div class="dataset-actions">
+				<el-button :loading="loading" :disabled="saving" @click="load">刷新</el-button>
+				<el-button type="primary" :disabled="!workspace || loading || saving" @click="edit('create')">新建数据集</el-button>
+			</div>
+		</div>
+
+		<el-table v-loading="loading" :data="workspace?.list ?? []" row-key="id" border>
+			<el-table-column prop="datasetKey" label="数据集编码" min-width="145" show-overflow-tooltip />
+			<el-table-column prop="name" label="名称" min-width="130" show-overflow-tooltip />
+			<el-table-column label="接收状态" min-width="145">
+				<template #default="{ row }">
+					<el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '未启用' }}</el-tag>
+					<div v-if="row.activeSchemaVersion" class="dataset-version">{{ row.activeSchemaVersion }}</div>
+				</template>
+			</el-table-column>
+			<el-table-column label="已绑定来源" min-width="210">
+				<template #default="{ row }">
+					<span v-if="!row.bindings.length">待绑定</span>
+					<el-tag
+						v-for="binding in row.bindings"
+						:key="binding.sourceId"
+						class="dataset-binding"
+						:type="binding.sourceEnabled ? 'info' : 'warning'"
+						:closable="!saving && !loading"
+						@close="apply(() => setIngestDatasetSource(row, binding.sourceId, false, factoryId))"
+					>
+						{{ binding.sourceName ?? '已移除来源' }}{{ binding.sourceEnabled ? '' : '(停用)' }}
+					</el-tag>
+				</template>
+			</el-table-column>
+			<el-table-column label="操作" width="195">
+				<template #default="{ row }">
+					<el-button link type="primary" :disabled="saving || loading" @click="edit('bind', row)">绑定来源</el-button>
+				</template>
+			</el-table-column>
+		</el-table>
+
+		<el-dialog :model-value="action !== null" :title="dialogTitle" width="min(92vw, 480px)" append-to-body :close-on-click-modal="false" :show-close="!saving" @update:model-value="action = null">
+			<el-form label-width="100px" :disabled="saving" @submit.prevent="save">
+				<template v-if="action === 'create'">
+					<el-form-item label="数据集编码">
+						<el-input v-model="form.datasetKey" maxlength="80" placeholder="例如 erp.purchase-receipt" />
+					</el-form-item>
+					<el-form-item label="名称">
+						<el-input v-model="form.name" maxlength="120" />
+					</el-form-item>
+				</template>
+				<el-form-item v-else-if="action === 'bind'" label="来源">
+					<el-select v-model="form.sourceId" filterable placeholder="请选择当前租户的可用来源">
+						<el-option v-for="source in availableSources" :key="source.id" :label="`${source.sourceName}(${source.sourceCode})`" :value="source.id" />
+					</el-select>
+				</el-form-item>
+			</el-form>
+			<template #footer>
+				<el-button :disabled="saving" @click="action = null">取消</el-button>
+				<el-button type="primary" :loading="saving" :disabled="action === 'bind' && !form.sourceId" @click="save">保存</el-button>
+			</template>
+		</el-dialog>
+	</el-drawer>
+</template>
+
+<style scoped>
+.dataset-toolbar {
+	display: flex;
+	align-items: center;
+	justify-content: space-between;
+	gap: 12px;
+	margin: 12px 0;
+}
+.dataset-actions {
+	margin-left: auto;
+}
+.dataset-version {
+	overflow-wrap: anywhere;
+	margin-top: 4px;
+}
+.dataset-binding {
+	margin: 2px 4px 2px 0;
+}
+</style>

+ 4 - 0
Web/src/views/aidop/data-platform/sources.vue

@@ -2,6 +2,7 @@
 	<AidopDemoShell title="数据源管理" subtitle="mdp_source 真实登记:DB / API 源与健康状态">
 		<template #bar-right>
 			<el-button type="primary" @click="openCreate">新建</el-button>
+			<el-button @click="datasetOpen = true">接收数据集</el-button>
 			<el-button @click="fileOpen = true">Excel 导入</el-button>
 			<el-button icon="ele-Refresh" :loading="loading" @click="loadList">刷新</el-button>
 		</template>
@@ -115,6 +116,7 @@
 			:source-type="wizard.sourceType"
 		/>
 		<MdpFileImportDrawer v-model="fileOpen" />
+		<MdpIngestDatasetDrawer v-model="datasetOpen" />
 	</AidopDemoShell>
 </template>
 
@@ -123,6 +125,7 @@ import { onMounted, reactive, ref } from 'vue';
 import { ElMessage, ElMessageBox } from 'element-plus';
 import AidopDemoShell from '../components/AidopDemoShell.vue';
 import MdpFileImportDrawer from './components/MdpFileImportDrawer.vue';
+import MdpIngestDatasetDrawer from './components/MdpIngestDatasetDrawer.vue';
 import SourceOnboardWizard from './components/SourceOnboardWizard.vue';
 import { fetchDbColumns, fetchDbTables, fetchMdpSources } from './api/syncTasks';
 import { fetchFileEntities } from './api/fileImports';
@@ -131,6 +134,7 @@ import { disableMdpSource, saveMdpSource, sourceBindings, testMdpSource } from '
 const loading = ref(false);
 const rows = ref<any[]>([]);
 const fileOpen = ref(false);
+const datasetOpen = ref(false);
 const drawer = ref(false);
 const saving = ref(false);
 const wizardOpen = ref(false);

BIN
doc/plan/系统集成/数据中台/Ai-DOP数据中台一期项目进度管理.xlsx


+ 9 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.602</AssemblyVersion>
-    <FileVersion>1.0.602</FileVersion>
-    <Version>1.0.602</Version>
+    <AssemblyVersion>1.0.603</AssemblyVersion>
+    <FileVersion>1.0.603</FileVersion>
+    <Version>1.0.603</Version>
   </PropertyGroup>
 
   <ItemGroup>
@@ -1042,6 +1042,12 @@
     <None Update="UpdateScripts\1.0.601.verify.sql">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </None>
+    <None Update="UpdateScripts\1.0.603.sql">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </None>
+    <None Update="UpdateScripts\1.0.603.verify.sql">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </None>
     <None Update="UpdateScripts\UAT-PLACEHOLDER-MENU-HIDE.ops.sql">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </None>

+ 58 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.603.sql

@@ -0,0 +1,58 @@
+-- 1.1.1 接收数据集配置表。开发期 WIP 文件,发布时随版本迁移登记。
+CREATE TABLE IF NOT EXISTS mdp_ingest_dataset (
+    id BIGINT NOT NULL AUTO_INCREMENT,
+    tenant_id BIGINT NOT NULL,
+    factory_id BIGINT NOT NULL,
+    dataset_key VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    name VARCHAR(120) NOT NULL,
+    active_schema_version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    enabled TINYINT(1) NOT NULL DEFAULT 0,
+    revision INT NOT NULL DEFAULT 1,
+    created_by BIGINT NOT NULL,
+    created_at DATETIME(6) NOT NULL,
+    updated_by BIGINT NOT NULL,
+    updated_at DATETIME(6) NOT NULL,
+    PRIMARY KEY (id),
+    UNIQUE KEY uk_mdp_ingest_dataset_scope (tenant_id, factory_id, dataset_key)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_dataset_version (
+    id BIGINT NOT NULL AUTO_INCREMENT,
+    tenant_id BIGINT NOT NULL,
+    factory_id BIGINT NOT NULL,
+    dataset_id BIGINT NOT NULL,
+    schema_version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    registered_by BIGINT NOT NULL,
+    registered_at DATETIME(6) NOT NULL,
+    PRIMARY KEY (id),
+    UNIQUE KEY uk_mdp_ingest_version_scope (tenant_id, factory_id, dataset_id, schema_version)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_dataset_source (
+    id BIGINT NOT NULL AUTO_INCREMENT,
+    tenant_id BIGINT NOT NULL,
+    factory_id BIGINT NOT NULL,
+    dataset_id BIGINT NOT NULL,
+    source_id BIGINT NOT NULL,
+    enabled TINYINT(1) NOT NULL DEFAULT 1,
+    updated_by BIGINT NOT NULL,
+    updated_at DATETIME(6) NOT NULL,
+    PRIMARY KEY (id),
+    UNIQUE KEY uk_mdp_ingest_source_scope (tenant_id, factory_id, dataset_id, source_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_factory (
+ tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, registered_by BIGINT NOT NULL,
+ registered_at DATETIME(6) NOT NULL, PRIMARY KEY(tenant_id,factory_id)
+) ENGINE=InnoDB;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_lifecycle (
+ dataset_id BIGINT PRIMARY KEY, state VARCHAR(20) NOT NULL, reason VARCHAR(500) NOT NULL, revision INT NOT NULL,
+ updated_by BIGINT NOT NULL, updated_at DATETIME(6) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE OR REPLACE SQL SECURITY DEFINER VIEW mdp_purchase_active_factory AS
+ SELECT t.Id AS tenant_id,o.Id AS factory_id
+ FROM SysTenant t JOIN SysOrg o ON o.TenantId=t.Id
+ LEFT JOIN mdp_ingest_factory f ON f.tenant_id=t.Id AND f.factory_id=o.Id
+ WHERE t.Status=1 AND o.Status=1 AND (o.Id=t.OrgId OR f.factory_id IS NOT NULL);

+ 7 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.603.verify.sql

@@ -0,0 +1,7 @@
+SELECT
+  (SELECT COUNT(*) FROM information_schema.tables
+   WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
+     AND table_name IN ('mdp_ingest_dataset', 'mdp_ingest_dataset_version',
+       'mdp_ingest_dataset_source', 'mdp_ingest_factory', 'mdp_ingest_lifecycle')) = 5 AS dataset_management_tables_ready,
+  (SELECT COUNT(*) FROM information_schema.views
+   WHERE table_schema = DATABASE() AND table_name = 'mdp_purchase_active_factory') = 1 AS active_factory_view_ready;

+ 256 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.cs

@@ -0,0 +1,256 @@
+using Admin.NET.Core.Service;
+using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
+using MySqlConnector;
+using System.Text.Json.Serialization;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+[ApiController]
+[Authorize]
+[RequirePcMenuPath("/aidop/data-platform/sources")]
+[Route("api/DataPlatform/ingest-datasets")]
+[NonUnify]
+public sealed partial class MdpIngestDatasetController(ISqlSugarClient db, UserManager user, SysOrgService organizations) : ControllerBase
+{
+    [HttpGet]
+    [DisplayName("查询接收数据集")]
+    public Task<IActionResult> List([FromQuery] long? factoryId) => WithScope(factoryId, async scope =>
+    {
+        var datasets = await Datasets(scope).OrderBy(x => x.DatasetKey).ToListAsync();
+        var sources = await db.Queryable<MdpSource>()
+            .Where(x => x.TenantId == scope.TenantId)
+            .OrderBy(x => x.SourceCode).ToListAsync();
+        var sourceById = sources.ToDictionary(x => x.Id);
+        var bindings = (await db.Queryable<MdpIngestDatasetSource>()
+            .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Enabled)
+            .ToListAsync()).ToLookup(x => x.DatasetId);
+        var versions = (await db.Queryable<MdpIngestDatasetVersion>()
+            .Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId)
+            .OrderByDescending(x => x.Id).ToListAsync()).ToLookup(x => x.DatasetId);
+
+        var stopped = (await db.Ado.SqlQueryAsync<long>("""
+            SELECT d.id FROM mdp_ingest_dataset d JOIN mdp_ingest_lifecycle l ON l.dataset_id=d.id
+            WHERE d.tenant_id=@tenant AND d.factory_id=@factory AND l.state IN ('PAUSED','RETIRED')
+            """, new { tenant = scope.TenantId, factory = scope.FactoryId })).ToHashSet();
+        return Ok(new
+        {
+            factoryId = scope.FactoryId.ToString(),
+            factoryName = scope.FactoryName,
+            sources = sources.Select(x => new { id = x.Id.ToString(), x.SourceCode, x.SourceName, enabled = x.Status == 1 }),
+            list = datasets.Select(x => new
+            {
+                id = x.Id.ToString(),
+                x.DatasetKey,
+                x.Name,
+                enabled = x.Enabled && !stopped.Contains(x.Id),
+                x.ActiveSchemaVersion,
+                x.Revision,
+                versions = versions[x.Id].Select(version => version.SchemaVersion),
+                bindings = bindings[x.Id].Select(binding => new
+                {
+                    sourceId = binding.SourceId.ToString(),
+                    sourceName = sourceById.GetValueOrDefault(binding.SourceId)?.SourceName,
+                    sourceEnabled = sourceById.GetValueOrDefault(binding.SourceId)?.Status == 1
+                })
+            })
+        });
+    });
+
+    [HttpPost]
+    [DisplayName("创建接收数据集")]
+    public Task<IActionResult> Create([FromBody] MdpCreateDatasetInput input, [FromQuery] long? factoryId) =>
+        WithScope(factoryId, async scope =>
+        {
+            var key = input.DatasetKey.Trim().ToLowerInvariant();
+            var name = input.Name.Trim();
+            if (name.Length == 0)
+                return BadRequest(new { message = "请输入数据集名称" });
+            var now = DateTime.UtcNow;
+            var dataset = new MdpIngestDataset
+            {
+                TenantId = scope.TenantId,
+                FactoryId = scope.FactoryId,
+                DatasetKey = key,
+                Name = name,
+                CreatedBy = user.UserId,
+                UpdatedBy = user.UserId,
+                CreatedAt = now,
+                UpdatedAt = now
+            };
+
+            try
+            {
+                var id = await db.Insertable(dataset).ExecuteReturnBigIdentityAsync();
+                return StatusCode(201, new { id = id.ToString() });
+            }
+            catch (Exception ex) when (ex is MySqlException { Number: 1062 } || ex.InnerException is MySqlException { Number: 1062 })
+            {
+                return Conflict(new { message = "当前工厂已存在该数据集编码" });
+            }
+        });
+
+    [HttpPut("{id:long}/sources/{sourceId:long}")]
+    [DisplayName("变更接收数据集来源绑定")]
+    public Task<IActionResult> SetSource(long id, long sourceId, [FromBody] MdpDatasetBindingInput input, [FromQuery] long? factoryId) =>
+        WithScope(factoryId, async scope =>
+        {
+            if (!await Datasets(scope).AnyAsync(x => x.Id == id))
+                return NotFound(new { message = "数据集不存在或不可访问" });
+
+            var now = DateTime.UtcNow;
+            var result = await db.Ado.UseTranAsync(async () =>
+            {
+                if (!await AdvanceRevision(scope, id, input.Revision, now))
+                    return ChangeResult.Conflict;
+
+                if (await db.Ado.SqlQuerySingleAsync<string>("SELECT state FROM mdp_ingest_lifecycle WHERE dataset_id=@id", new { id }) == "RETIRED")
+                    throw new DatasetChangeException("数据集已退役");
+                if (input.Enabled && !await db.Queryable<MdpSource>()
+                        .AnyAsync(x => x.Id == sourceId && x.TenantId == scope.TenantId && x.Status == 1))
+                    throw new DatasetChangeException("来源不存在、已停用或不在当前租户范围内");
+
+                var row = await db.Queryable<MdpIngestDatasetSource>()
+                    .FirstAsync(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId
+                        && x.DatasetId == id && x.SourceId == sourceId);
+                if (row == null && input.Enabled)
+                {
+                    await db.Insertable(new MdpIngestDatasetSource
+                    {
+                        TenantId = scope.TenantId,
+                        FactoryId = scope.FactoryId,
+                        DatasetId = id,
+                        SourceId = sourceId,
+                        Enabled = true,
+                        UpdatedBy = user.UserId,
+                        UpdatedAt = now
+                    }).ExecuteCommandAsync();
+                }
+                else if (row != null)
+                {
+                    row.Enabled = input.Enabled;
+                    row.UpdatedBy = user.UserId;
+                    row.UpdatedAt = now;
+                    await db.Updateable(row).ExecuteCommandAsync();
+                }
+
+                return ChangeResult.Saved;
+            });
+            return ChangeResponse(result);
+        });
+
+    private async Task<IActionResult> WithScope(long? requestedFactoryId, Func<DatasetScope, Task<IActionResult>> action)
+    {
+        var tenantId = AidopTenantScope.ResolveOrThrow(user);
+        var factories = await AuthorizedFactories(tenantId);
+        var factory = requestedFactoryId.HasValue
+            ? factories.SingleOrDefault(x => x.Id == requestedFactoryId)
+            : factories.FirstOrDefault(x => x.IsDefault) ?? (factories.Count == 1 ? factories[0] : null);
+        if (factory == null)
+            return StatusCode(requestedFactoryId.HasValue || factories.Count == 0 ? 403 : 400,
+                new { message = "请选择账号已获授权的有效工厂" });
+        return await action(new DatasetScope(tenantId, factory.Id, factory.Name));
+    }
+
+    private sealed class FactoryOption
+    {
+        public long Id { get; set; }
+        public string Name { get; set; } = "";
+        public bool IsDefault { get; set; }
+    }
+
+    private async Task<List<FactoryOption>> AuthorizedFactories(long tenant)
+    {
+        var rows = await db.Ado.SqlQueryAsync<FactoryOption>(
+            """
+            SELECT f.factory_id AS Id,o.Name,(f.factory_id=t.OrgId) AS IsDefault
+            FROM mdp_purchase_active_factory f JOIN SysOrg o ON o.Id=f.factory_id AND o.TenantId=f.tenant_id
+            JOIN SysTenant t ON t.Id=f.tenant_id WHERE f.tenant_id=@tenant ORDER BY o.Name,o.Id
+            """, new { tenant });
+        if (user.SuperAdmin) return rows;
+        var allowed = (await organizations.GetUserOrgIdList()).ToHashSet();
+        return rows.Where(x => allowed.Contains(x.Id)).ToList();
+    }
+
+    [HttpGet("factories")]
+    public async Task<IActionResult> Factories()
+    {
+        var rows = await AuthorizedFactories(AidopTenantScope.ResolveOrThrow(user));
+        return Ok(rows.Select(f => new { id = f.Id.ToString(), name = f.Name, isDefault = f.IsDefault }));
+    }
+
+    [HttpGet("factories/available")]
+    public async Task<IActionResult> AvailableFactoryOrganizations()
+    {
+        if (!user.SysAdmin && !user.SuperAdmin) return Ok(Array.Empty<object>());
+        var tenant = AidopTenantScope.ResolveOrThrow(user);
+        var options = await db.Ado.SqlQueryAsync<FactoryOption>("""
+            SELECT o.Id,o.Name FROM SysOrg o JOIN SysTenant t ON t.Id=o.TenantId AND t.Status=1
+            WHERE t.Id=@tenant AND o.Status=1 AND NOT EXISTS (SELECT 1 FROM mdp_purchase_active_factory f
+                WHERE f.tenant_id=t.Id AND f.factory_id=o.Id) ORDER BY o.Name,o.Id
+            """,new { tenant });
+        var allowed = user.SuperAdmin ? null : (await organizations.GetUserOrgIdList()).ToHashSet();
+        return Ok(options.Where(o => allowed == null || allowed.Contains(o.Id)).Select(o => new { id=o.Id.ToString(),o.Name }));
+    }
+
+    [HttpPost("factories/{id:long}")]
+    public async Task<IActionResult> RegisterFactory(long id)
+    {
+        if (!user.SysAdmin && !user.SuperAdmin) return Forbid();
+        var tenant = AidopTenantScope.ResolveOrThrow(user);
+        if (!user.SuperAdmin && !(await organizations.GetUserOrgIdList()).Contains(id)) return Forbid();
+        var org = await db.Queryable<SysOrg>().FirstAsync(o => o.Id == id && o.TenantId == tenant && o.Status == StatusEnum.Enable);
+        if (org == null) return NotFound();
+        await db.Ado.ExecuteCommandAsync("""
+            INSERT INTO mdp_ingest_factory(tenant_id,factory_id,registered_by,registered_at)
+            VALUES (@tenant,@id,@actor,UTC_TIMESTAMP(6)) ON DUPLICATE KEY UPDATE factory_id=VALUES(factory_id)
+            """, new { tenant, id, actor = user.UserId });
+        return NoContent();
+    }
+
+    private ISugarQueryable<MdpIngestDataset> Datasets(DatasetScope scope) =>
+        db.Queryable<MdpIngestDataset>().Where(x => x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId);
+
+    private async Task<bool> AdvanceRevision(DatasetScope scope, long id, int revision, DateTime now)
+    {
+        var actor = user.UserId;
+        return await db.Updateable<MdpIngestDataset>()
+            .SetColumns(x => x.Revision == x.Revision + 1)
+            .SetColumns(x => x.UpdatedBy == actor)
+            .SetColumns(x => x.UpdatedAt == now)
+            .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId && x.Revision == revision)
+            .ExecuteCommandAsync() == 1;
+    }
+
+    private IActionResult ChangeResponse(DbResult<ChangeResult> result)
+    {
+        if (result.ErrorException is DatasetChangeException validation)
+            return BadRequest(new { message = validation.Message });
+        if (!result.IsSuccess)
+            throw result.ErrorException ?? Oops.Oh("保存接收数据集失败");
+        return result.Data == ChangeResult.Conflict
+            ? Conflict(new { message = "数据集已变更,请刷新后重试" })
+            : NoContent();
+    }
+
+    private sealed record DatasetScope(long TenantId, long FactoryId, string FactoryName);
+    private enum ChangeResult { Saved, Conflict }
+    private sealed class DatasetChangeException(string message) : Exception(message);
+}
+
+public sealed class MdpCreateDatasetInput
+{
+    [Required, StringLength(80), RegularExpression(@"^[A-Za-z0-9][A-Za-z0-9._-]*$")]
+    public string DatasetKey { get; set; } = string.Empty;
+
+    [Required, StringLength(120)]
+    public string Name { get; set; } = string.Empty;
+}
+
+public sealed class MdpDatasetBindingInput
+{
+    [Range(1, int.MaxValue)]
+    public int Revision { get; set; }
+
+    [JsonRequired, Newtonsoft.Json.JsonRequired]
+    public bool Enabled { get; set; }
+}

+ 97 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/Entity/DataPlatform/MdpIngestDataset.cs

@@ -0,0 +1,97 @@
+namespace Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
+
+[SugarTable("mdp_ingest_dataset", "通用接收数据集")]
+[SugarIndex("uk_mdp_ingest_dataset_scope", nameof(TenantId), OrderByType.Asc, nameof(FactoryId), OrderByType.Asc, nameof(DatasetKey), OrderByType.Asc, true)]
+public sealed class MdpIngestDataset
+{
+    [SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
+    public long Id { get; set; }
+
+    [SugarColumn(ColumnName = "tenant_id")]
+    public long TenantId { get; set; }
+
+    [SugarColumn(ColumnName = "factory_id")]
+    public long FactoryId { get; set; }
+
+    [SugarColumn(ColumnName = "dataset_key", Length = 80)]
+    public string DatasetKey { get; set; } = string.Empty;
+
+    [SugarColumn(ColumnName = "name", Length = 120)]
+    public string Name { get; set; } = string.Empty;
+
+    [SugarColumn(ColumnName = "active_schema_version", Length = 64, IsNullable = true)]
+    public string? ActiveSchemaVersion { get; set; }
+
+    [SugarColumn(ColumnName = "enabled")]
+    public bool Enabled { get; set; }
+
+    [SugarColumn(ColumnName = "revision")]
+    public int Revision { get; set; } = 1;
+
+    [SugarColumn(ColumnName = "created_by")]
+    public long CreatedBy { get; set; }
+
+    [SugarColumn(ColumnName = "created_at")]
+    public DateTime CreatedAt { get; set; }
+
+    [SugarColumn(ColumnName = "updated_by")]
+    public long UpdatedBy { get; set; }
+
+    [SugarColumn(ColumnName = "updated_at")]
+    public DateTime UpdatedAt { get; set; }
+}
+
+[SugarTable("mdp_ingest_dataset_version", "通用接收数据集版本")]
+[SugarIndex("uk_mdp_ingest_version_scope", nameof(TenantId), OrderByType.Asc, nameof(FactoryId), OrderByType.Asc, nameof(DatasetId), OrderByType.Asc, nameof(SchemaVersion), OrderByType.Asc, true)]
+public sealed class MdpIngestDatasetVersion
+{
+    [SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
+    public long Id { get; set; }
+
+    [SugarColumn(ColumnName = "tenant_id")]
+    public long TenantId { get; set; }
+
+    [SugarColumn(ColumnName = "factory_id")]
+    public long FactoryId { get; set; }
+
+    [SugarColumn(ColumnName = "dataset_id")]
+    public long DatasetId { get; set; }
+
+    [SugarColumn(ColumnName = "schema_version", Length = 64)]
+    public string SchemaVersion { get; set; } = string.Empty;
+
+    [SugarColumn(ColumnName = "registered_by")]
+    public long RegisteredBy { get; set; }
+
+    [SugarColumn(ColumnName = "registered_at")]
+    public DateTime RegisteredAt { get; set; }
+}
+
+[SugarTable("mdp_ingest_dataset_source", "通用接收数据集来源授权")]
+[SugarIndex("uk_mdp_ingest_source_scope", nameof(TenantId), OrderByType.Asc, nameof(FactoryId), OrderByType.Asc, nameof(DatasetId), OrderByType.Asc, nameof(SourceId), OrderByType.Asc, true)]
+public sealed class MdpIngestDatasetSource
+{
+    [SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
+    public long Id { get; set; }
+
+    [SugarColumn(ColumnName = "tenant_id")]
+    public long TenantId { get; set; }
+
+    [SugarColumn(ColumnName = "factory_id")]
+    public long FactoryId { get; set; }
+
+    [SugarColumn(ColumnName = "dataset_id")]
+    public long DatasetId { get; set; }
+
+    [SugarColumn(ColumnName = "source_id")]
+    public long SourceId { get; set; }
+
+    [SugarColumn(ColumnName = "enabled")]
+    public bool Enabled { get; set; }
+
+    [SugarColumn(ColumnName = "updated_by")]
+    public long UpdatedBy { get; set; }
+
+    [SugarColumn(ColumnName = "updated_at")]
+    public DateTime UpdatedAt { get; set; }
+}