From eb8c94eacf550d38a0fbaec277c8ea9e265a1f6a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 5 Nov 2026 15:44:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(shop):=20=E6=96=B0=E5=A2=9E=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E5=BA=97=E9=93=BA=E7=B1=BB=E5=9E=8B=E4=B8=8E?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5/=E9=80=89=E8=A1=A8/=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 迁移 shop_database_configs:一店一条,存数据库类型/IP/端口/库名/账号/密码、 商品表/订单表/订单明细表名、三份字段映射与最近校验结果 - 新增 shopDatabase 控制器与 lib:服务端用 mysql2 连接客户库(8s 超时、utf8mb4), 提供配置读取/保存、测试连通、连接拉表、拉表列表与表字段;表名走白名单校验 - 保存时连得上则校验表与列真实存在(不存在拒绝保存),连不上则保存并提示未校验 - 店铺新增支持 type=3 数据库店铺;删除店铺时一并清理数据库配置 - 前端:新增店铺可选「数据库店铺」,创建后自动打开配置弹窗;列表对数据库店铺 显示「配置」,弹窗内填写连接信息、测试连通、连接拉表、选三张表并逐个字段映射 - 契约与路由:补数据库店铺配置相关接口定义 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/contract/index.js | 99 ++++ backend/app/controller/shop.js | 28 +- backend/app/controller/shopDatabase.js | 493 ++++++++++++++++++ backend/app/lib/shopDatabaseClient.js | 146 ++++++ backend/app/lib/shopDatabaseFields.js | 88 ++++ backend/app/model/shopDatabaseConfig.js | 47 ++ backend/app/router.js | 7 + ...1105074000-create-shop-database-configs.js | 49 ++ frontend/src/api/shop.ts | 4 +- frontend/src/api/shopDatabase.ts | 125 +++++ frontend/src/views/Shop/Index.vue | 439 +++++++++++++++- 11 files changed, 1515 insertions(+), 10 deletions(-) create mode 100644 backend/app/controller/shopDatabase.js create mode 100644 backend/app/lib/shopDatabaseClient.js create mode 100644 backend/app/lib/shopDatabaseFields.js create mode 100644 backend/app/model/shopDatabaseConfig.js create mode 100644 backend/database/migrations/20261105074000-create-shop-database-configs.js create mode 100644 frontend/src/api/shopDatabase.ts diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index dbf38fd..8738ded 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -1162,6 +1162,7 @@ module.exports = { code: { type: 'string', description: '店铺编码,留空则自动生成 OMS 前缀编码;传入时同一主体下唯一' }, name: { type: 'string', required: true, description: '店铺名称' }, platform: { type: 'string', description: '平台标识:taobao/pdd/douyin/jd/other' }, + type: { type: 'integer', description: '店铺类型:1 平台店铺(默认)/ 3 数据库店铺' }, contact_name: { type: 'string', description: '联系人' }, contact_phone: { type: 'string', description: '联系电话' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, @@ -1186,6 +1187,104 @@ module.exports = { remark: { type: 'string', description: '备注' }, }, + // ---------- 数据库店铺配置 shop_database_configs ---------- + /** 数据库店铺字段映射:OMS 字段 key → 源表列名 */ + shopDatabaseFieldMapping: { + // 商品表 + item_code: { type: 'string', description: '商品表:商品编码 对应的源列名(必填)' }, + item_name: { type: 'string', description: '商品表:商品名称 对应的源列名(必填)' }, + sku_property: { type: 'string', description: '商品表:SKU规格 对应的源列名' }, + barcode: { type: 'string', description: '商品表:条码 对应的源列名' }, + stock_unit: { type: 'string', description: '商品表:库存单位 对应的源列名' }, + price: { type: 'string', description: '商品表/明细表:单价 对应的源列名' }, + // 订单表 / 明细表 + order_no: { type: 'string', description: '订单表/明细表:订单号 对应的源列名(必填)' }, + place_order_time: { type: 'string', description: '订单表:下单时间 对应的源列名' }, + receiver: { type: 'string', description: '订单表:收件人 对应的源列名(必填)' }, + mobile: { type: 'string', description: '订单表:手机号 对应的源列名' }, + tel: { type: 'string', description: '订单表:电话 对应的源列名' }, + province: { type: 'string', description: '订单表:省 对应的源列名(必填)' }, + city: { type: 'string', description: '订单表:市 对应的源列名(必填)' }, + area: { type: 'string', description: '订单表:区/县 对应的源列名(必填)' }, + town: { type: 'string', description: '订单表:街道/镇 对应的源列名' }, + detail_address: { type: 'string', description: '订单表:详细地址 对应的源列名(必填)' }, + zip_code: { type: 'string', description: '订单表:邮编 对应的源列名' }, + total_amount: { type: 'string', description: '订单表:订单金额 对应的源列名' }, + freight: { type: 'string', description: '订单表:运费 对应的源列名' }, + buyer_message: { type: 'string', description: '订单表:买家留言 对应的源列名' }, + seller_message: { type: 'string', description: '订单表:卖家留言 对应的源列名' }, + quantity: { type: 'string', description: '订单明细表:数量 对应的源列名(必填)' }, + }, + /** 数据库店铺配置(密码不回显) */ + shopDatabaseConfigItem: { + shop_id: { type: 'integer', description: '店铺ID' }, + db_type: { type: 'string', description: '数据库类型,当前仅 mysql' }, + host: { type: 'string', description: '数据库地址(IP 或域名)' }, + port: { type: 'integer', description: '数据库端口,默认 3306' }, + database_name: { type: 'string', description: '数据库名' }, + username: { type: 'string', description: '数据库账号' }, + has_password: { type: 'boolean', description: '是否已保存密码(密码不回显)' }, + product_table: { type: 'string', description: '商品表名' }, + order_table: { type: 'string', description: '订单表名' }, + order_item_table: { type: 'string', description: '订单明细表名' }, + product_fields: { type: 'shopDatabaseFieldMapping', description: '商品表字段映射' }, + order_fields: { type: 'shopDatabaseFieldMapping', description: '订单表字段映射' }, + order_item_fields: { type: 'shopDatabaseFieldMapping', description: '订单明细表字段映射' }, + last_test_at: { type: 'string', description: '最近一次校验时间' }, + last_test_success: { type: 'integer', description: '最近一次校验结果:1成功 0失败' }, + last_test_message: { type: 'string', description: '最近一次校验说明' }, + }, + shopDatabaseConfigData: { + config: { type: 'shopDatabaseConfigItem', description: '数据库连接与映射配置' }, + db_types: { type: 'array', itemType: 'shopDatabaseOption', description: '可选数据库类型' }, + datasets: { type: 'array', itemType: 'shopDatabaseDataset', description: '可映射字段定义' }, + }, + shopDatabaseConfigResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'shopDatabaseConfigData', description: '数据库店铺配置与字段定义' }, + }, + shopDatabaseOption: { + value: { type: 'string', description: '类型值' }, + label: { type: 'string', description: '类型名称' }, + }, + shopDatabaseDataset: { + key: { type: 'string', description: '数据集标识:product / order / order_item' }, + label: { type: 'string', description: '数据集名称(商品表 / 订单表 / 订单明细表)' }, + table_column: { type: 'string', description: '保存表名的配置列' }, + field_column: { type: 'string', description: '保存字段映射的配置列' }, + fields: { type: 'array', itemType: 'shopDatabaseDatasetField', description: 'OMS 侧字段定义' }, + }, + shopDatabaseDatasetField: { + key: { type: 'string', description: 'OMS 字段标识' }, + label: { type: 'string', description: 'OMS 字段名称' }, + required: { type: 'boolean', description: '是否必填' }, + }, + /** 数据库店铺连接参数(保存 / 测试 / 连接共用) */ + shopDatabaseConnectionRequest: { + db_type: { type: 'string', description: '数据库类型,当前仅 mysql' }, + host: { type: 'string', description: '数据库地址(IP 或域名)' }, + port: { type: 'integer', description: '数据库端口,默认 3306' }, + database_name: { type: 'string', description: '数据库名' }, + username: { type: 'string', description: '数据库账号' }, + password: { type: 'string', description: '数据库密码;留空表示沿用已保存的密码' }, + product_table: { type: 'string', description: '商品表名(保存时必填)' }, + order_table: { type: 'string', description: '订单表名(保存时必填)' }, + order_item_table: { type: 'string', description: '订单明细表名(保存时必填)' }, + product_fields: { type: 'shopDatabaseFieldMapping', description: '商品表字段映射' }, + order_fields: { type: 'shopDatabaseFieldMapping', description: '订单表字段映射' }, + order_item_fields: { type: 'shopDatabaseFieldMapping', description: '订单明细表字段映射' }, + }, + shopDatabaseTableItem: { + name: { type: 'string', description: '表名' }, + comment: { type: 'string', description: '表注释' }, + }, + shopDatabaseColumnItem: { + name: { type: 'string', description: '列名' }, + type: { type: 'string', description: '列类型' }, + comment: { type: 'string', description: '列注释' }, + }, + // ---------- 外部打单平台 external_print_platforms ---------- externalPrintPlatformItem: { id: { type: 'integer', description: '主键' }, diff --git a/backend/app/controller/shop.js b/backend/app/controller/shop.js index bd82cb5..fb64634 100644 --- a/backend/app/controller/shop.js +++ b/backend/app/controller/shop.js @@ -12,6 +12,12 @@ const SHOP_TYPE_PLATFORM = 1; /** 店铺类型:外部打单平台导入的商家店铺(货主权限只读) */ const SHOP_TYPE_EXTERNAL = 2; +/** 店铺类型:数据库店铺(自建 MySQL 库拉取明文订单,需单独配置连接与字段映射) */ +const SHOP_TYPE_DATABASE = 3; + +/** 手工新增时允许选择的店铺类型:平台店铺 / 数据库店铺 */ +const CREATABLE_TYPES = [ SHOP_TYPE_PLATFORM, SHOP_TYPE_DATABASE ]; + /** 自动拉取订单的最小间隔(分钟) */ const MIN_AUTO_FETCH_INTERVAL = 3; @@ -193,7 +199,7 @@ class ShopController extends Controller { /** * @summary 新增店铺 * @description name 必填;code 留空时自动生成 OMS 前缀编码(表示该店铺由 OMS 创建), - * 传入 code 时校验同一主体下唯一 + * 传入 code 时校验同一主体下唯一;type 可选 1 平台店铺(默认)/ 3 数据库店铺 * @router post /api/shops * @apikey * @request body createShopRequest *body @@ -250,9 +256,8 @@ class ShopController extends Controller { } } - // 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通新增固定为「平台店铺」 + // 外部平台导入相关字段由对应接入逻辑维护;手工新增只允许「平台店铺 / 数据库店铺」 const body = { ...ctx.request.body }; - delete body.type; delete body.external_print_account_id; delete body.external_data; delete body.db_host; @@ -261,9 +266,22 @@ class ShopController extends Controller { delete body.db_username; delete body.db_password; + // 店铺类型:不传默认平台店铺;数据库店铺的连接信息在「配置」弹窗单独维护 + let shopType = SHOP_TYPE_PLATFORM; + if (body.type !== undefined && body.type !== null && body.type !== '') { + const incoming = Number(body.type); + if (!CREATABLE_TYPES.includes(incoming)) { + ctx.status = 400; + ctx.body = { code: 400, message: '店铺类型仅支持:1 平台店铺 / 3 数据库店铺' }; + return; + } + shopType = incoming; + } + delete body.type; + const shop = await ctx.model.Shop.create({ ...body, - type: SHOP_TYPE_PLATFORM, + type: shopType, code: shopCode, subsidiary_id: subsidiary.value, auto_fetch_order: autoFetch.auto_fetch_order == null ? 0 : autoFetch.auto_fetch_order, @@ -494,6 +512,8 @@ class ShopController extends Controller { return; } + // 数据库店铺的连接配置随店铺一起删除(一店一条),避免残留脏配置 + await ctx.model.ShopDatabaseConfig.destroy({ where: { shop_id: shop.id } }); await shop.destroy(); await ctx.service.cache.invalidateShop(ctx.params.id); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; diff --git a/backend/app/controller/shopDatabase.js b/backend/app/controller/shopDatabase.js new file mode 100644 index 0000000..4887f2a --- /dev/null +++ b/backend/app/controller/shopDatabase.js @@ -0,0 +1,493 @@ +'use strict'; + +const { Controller } = require('egg'); +const { + DB_TYPES, + DEFAULT_DB_TYPE, + DATASETS, + datasetDefs, +} = require('../lib/shopDatabaseFields'); +const { + SAFE_IDENTIFIER, + normalizeParams, + validateParams, + openConnection, + closeQuietly, + testConnection, + listTables, + listColumns, +} = require('../lib/shopDatabaseClient'); + +/** 数据库店铺的店铺类型值(shops.type) */ +const SHOP_TYPE_DATABASE = 3; + +/** + * @controller ShopDatabaseController 数据库店铺配置 + * + * 数据库店铺(shops.type=3)直接连客户自有 MySQL 库拉取明文订单, + * 因此需要维护:连接信息(类型/地址/端口/库名/账号/密码)、 + * 三张数据集(商品表 / 订单表 / 订单明细表)的选表结果与字段映射。 + * 所有连接动作都在服务端完成(浏览器不直连客户库)。 + */ +class ShopDatabaseController extends Controller { + /** + * 取店铺并校验可见范围 + * @param {number|string} id 店铺ID + * @return {Promise} 店铺实例;失败时已写入响应 + */ + async loadShop(id) { + const { ctx } = this; + const shop = await ctx.model.Shop.findByPk(id, { + attributes: [ 'id', 'principal_id', 'name', 'type', 'subsidiary_id' ], + }); + if (!shop) { + ctx.status = 404; + ctx.body = { code: 404, message: '店铺不存在' }; + return null; + } + if (Number(shop.type) !== SHOP_TYPE_DATABASE) { + ctx.status = 400; + ctx.body = { code: 400, message: '仅「数据库店铺」需要配置数据库连接' }; + return null; + } + // 所在公司权限:仅可配置自己所属公司(货主)的店铺 + const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); + if (!access.isGroup && !access.ownCompanyIds.map(Number).includes(Number(shop.subsidiary_id))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可配置自己所属公司(货主)的店铺' }; + return null; + } + return shop; + } + + /** + * 取(或初始化)店铺的数据库配置记录 + * @param {Object} shop 店铺实例 + * @return {Promise} 配置 model 实例 + */ + async findConfig(shop) { + const { ctx } = this; + const exist = await ctx.model.ShopDatabaseConfig.findOne({ where: { shop_id: shop.id } }); + if (exist) return exist; + return ctx.model.ShopDatabaseConfig.build({ + principal_id: shop.principal_id, + shop_id: shop.id, + db_type: DEFAULT_DB_TYPE, + }); + } + + /** + * 合并前端入参与已保存配置(密码留空表示沿用已保存的密码) + * @param {Object} body 请求体 + * @param {Object} config 已保存配置(可为空) + * @return {Object} 规范化后的连接参数 + */ + resolveParams(body, config) { + const saved = config + ? { + db_type: config.db_type, + host: config.host, + port: config.port, + database_name: config.database_name, + username: config.username, + password: config.password, + } + : {}; + const input = body || {}; + const password = input.password === undefined || input.password === null || input.password === '' + ? (saved.password || '') + : input.password; + return normalizeParams({ ...saved, ...input, password }); + } + + /** + * 输出用的配置视图(密码不回显,只给 has_password) + * @param {Object} config 配置实例 + * @param {Object} [shop] 店铺实例 + * @return {Object} 配置视图 + */ + toView(config, shop) { + const plain = config && config.get ? config.get({ plain: true }) : (config || {}); + return { + shop_id: plain.shop_id, + shop_name: shop ? shop.name : undefined, + db_type: plain.db_type || DEFAULT_DB_TYPE, + host: plain.host || '', + port: plain.port == null ? null : Number(plain.port), + database_name: plain.database_name || '', + username: plain.username || '', + has_password: !!plain.password, + product_table: plain.product_table || '', + order_table: plain.order_table || '', + order_item_table: plain.order_item_table || '', + product_fields: plain.product_fields || {}, + order_fields: plain.order_fields || {}, + order_item_fields: plain.order_item_fields || {}, + last_test_at: plain.last_test_at || null, + last_test_success: plain.last_test_success == null ? null : Number(plain.last_test_success), + last_test_message: plain.last_test_message || '', + }; + } + + /** + * @summary 数据库店铺配置详情 + * @description 返回连接信息(密码不回显)、三张数据集的选表与字段映射、以及可映射字段定义 + * @router get /api/shops/{id}/database-config + * @apikey + * @request path integer *id 店铺主键ID + * @response 200 shopDatabaseConfigResponse success + */ + async show() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const config = await this.findConfig(shop); + + ctx.body = { + code: 0, + message: 'success', + data: { + config: this.toView(config, shop), + db_types: DB_TYPES, + datasets: datasetDefs(), + }, + }; + } + + /** + * 校验字段映射:键必须在字段定义内,值必须是非空安全标识符,必填字段不能缺 + * @param {Object} mapping 前端提交的映射 + * @param {Object} dataset DATASETS 中的定义 + * @return {string|null} 错误提示,通过返回 null + */ + validateMapping(mapping, dataset) { + const raw = mapping && typeof mapping === 'object' ? mapping : {}; + const allowed = new Set(dataset.fields.map(field => field.key)); + for (const [ key, value ] of Object.entries(raw)) { + if (!allowed.has(key)) return `${dataset.label}:不支持的字段 ${key}`; + if (value === null || value === undefined || String(value).trim() === '') continue; + if (!SAFE_IDENTIFIER.test(String(value).trim())) return `${dataset.label}:字段「${key}」的源列名不合法`; + } + const missing = dataset.fields + .filter(field => field.required) + .filter(field => { + const value = raw[field.key]; + return value === null || value === undefined || String(value).trim() === ''; + }) + .map(field => field.label); + if (missing.length) return `${dataset.label}:请完成必填字段映射(${missing.join('、')})`; + return null; + } + + /** + * 整理要落库的映射(去掉空值,统一 trim) + * @param {Object} mapping 前端提交的映射 + * @return {Object} 清洗后的映射 + */ + cleanMapping(mapping) { + const result = {}; + for (const [ key, value ] of Object.entries(mapping && typeof mapping === 'object' ? mapping : {})) { + const text = value === null || value === undefined ? '' : String(value).trim(); + if (text) result[key] = text; + } + return result; + } + + /** + * 连库校验:表是否存在、映射列是否存在于对应表 + * @param {Object} params 连接参数 + * @param {Object} tables 三张数据集选表结果 { product_table: 表名 ... } + * @param {Object} mappings 三张数据集映射 { product_fields: {...} ... } + * @return {Promise<{ok: boolean, connected: boolean, message?: string}>} 校验结果(connected 表示是否连上了库) + */ + async verifyAgainstDatabase(params, tables, mappings) { + let conn = null; + try { + conn = await openConnection(params); + const remoteTables = await listTables(conn, params); + const names = new Set(remoteTables.map(row => row.name)); + for (const dataset of Object.values(DATASETS)) { + const table = tables[dataset.tableColumn]; + if (!names.has(table)) { + return { ok: false, connected: true, message: `${dataset.label}:库中不存在表 ${table},请重新连接后选择` }; + } + } + const columnsByTable = new Map(); + for (const dataset of Object.values(DATASETS)) { + const table = tables[dataset.tableColumn]; + if (!columnsByTable.has(table)) { + const rows = await listColumns(conn, params, table); + columnsByTable.set(table, new Set(rows.map(row => row.name))); + } + const columns = columnsByTable.get(table); + const mapping = mappings[dataset.fieldColumn] || {}; + for (const [ key, column ] of Object.entries(mapping)) { + if (!columns.has(column)) { + const field = dataset.fields.find(item => item.key === key); + return { + ok: false, + connected: true, + message: `${dataset.label}:字段「${field ? field.label : key}」映射的列 ${column} 不存在`, + }; + } + } + } + return { ok: true, connected: true }; + } catch (err) { + return { + ok: false, + connected: false, + message: `连接失败:${err && err.message ? err.message : '未知错误'}`, + }; + } finally { + await closeQuietly(conn); + } + } + + /** + * @summary 保存数据库店铺配置 + * @description 保存连接信息(密码留空沿用原值)、三张数据集选表与字段映射; + * 保存时会尝试连库校验表与列是否真实存在(库不可达时仍保存,返回提示) + * @router put /api/shops/{id}/database-config + * @apikey + * @request path integer *id 店铺主键ID + * @request body shopDatabaseConnectionRequest *body + * @response 200 baseResponse success + */ + async save() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const config = await this.findConfig(shop); + const body = ctx.request.body || {}; + + const params = this.resolveParams(body, config); + const paramsError = validateParams(params); + if (paramsError) { + ctx.status = 400; + ctx.body = { code: 400, message: paramsError }; + return; + } + + const tables = {}; + const mappings = {}; + for (const dataset of Object.values(DATASETS)) { + const table = String(body[dataset.tableColumn] || '').trim(); + if (!table) { + ctx.status = 400; + ctx.body = { code: 400, message: `请选择${dataset.label}` }; + return; + } + if (!SAFE_IDENTIFIER.test(table)) { + ctx.status = 400; + ctx.body = { code: 400, message: `${dataset.label}:表名不合法` }; + return; + } + tables[dataset.tableColumn] = table; + + const mappingError = this.validateMapping(body[dataset.fieldColumn], dataset); + if (mappingError) { + ctx.status = 400; + ctx.body = { code: 400, message: mappingError }; + return; + } + mappings[dataset.fieldColumn] = this.cleanMapping(body[dataset.fieldColumn]); + } + + // 能连上就校验表/列是否真实存在:连上但校验不过直接拒绝(避免存下跑不通的映射); + // 连不上时仍保存连接信息,便于先存配置再排查网络 + const verified = await this.verifyAgainstDatabase(params, tables, mappings); + if (verified.connected && !verified.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: verified.message }; + return; + } + config.set({ + principal_id: shop.principal_id, + shop_id: shop.id, + db_type: params.db_type, + host: params.host, + port: params.port, + database_name: params.database_name, + username: params.username, + password: params.password, + ...tables, + ...mappings, + last_test_at: new Date(), + last_test_success: verified.ok ? 1 : 0, + last_test_message: String(verified.ok ? '配置保存成功,表与字段校验通过' : verified.message).slice(0, 500), + }); + const saved = await config.save(); + + ctx.body = { + code: 0, + message: verified.ok ? 'success' : `配置已保存,但未完成连库校验:${verified.message}`, + data: { id: saved.id, verified: verified.ok }, + }; + } + + /** + * @summary 测试数据库连通 + * @description 使用传入参数(密码留空则用已保存密码)在服务端连接客户库,返回版本与耗时 + * @router post /api/shops/{id}/database-config/test + * @apikey + * @request path integer *id 店铺主键ID + * @request body shopDatabaseConnectionRequest *body + * @response 200 baseResponse success + */ + async test() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const config = await this.findConfig(shop); + const params = this.resolveParams(ctx.request.body, config); + const paramsError = validateParams(params); + if (paramsError) { + ctx.status = 400; + ctx.body = { code: 400, message: paramsError }; + return; + } + + const result = await testConnection(params); + ctx.body = { + code: 0, + message: result.message, + data: { success: result.success, server_version: result.server_version || '', message: result.message }, + }; + } + + /** + * @summary 连接数据库并拉取数据表 + * @description 连通后返回库内所有表,供三张数据集选择 + * @router post /api/shops/{id}/database-config/connect + * @apikey + * @request path integer *id 店铺主键ID + * @request body shopDatabaseConnectionRequest *body + * @response 200 baseResponse success + */ + async connect() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const config = await this.findConfig(shop); + const params = this.resolveParams(ctx.request.body, config); + const paramsError = validateParams(params); + if (paramsError) { + ctx.status = 400; + ctx.body = { code: 400, message: paramsError }; + return; + } + + let conn = null; + try { + conn = await openConnection(params); + const tables = await listTables(conn, params); + ctx.body = { + code: 0, + message: `连接成功,共 ${tables.length} 张表`, + data: { success: true, tables }, + }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: `连接失败:${err && err.message ? err.message : '未知错误'}` }; + } finally { + await closeQuietly(conn); + } + } + + /** + * @summary 用已保存配置拉取数据表 + * @description 配置不完整或库不可达时返回 400,前端可提示重新连接 + * @router get /api/shops/{id}/database-config/tables + * @apikey + * @request path integer *id 店铺主键ID + * @response 200 baseResponse success + */ + async tables() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const config = await this.findConfig(shop); + const params = this.resolveParams({}, config); + const paramsError = validateParams(params); + if (paramsError) { + ctx.status = 400; + ctx.body = { code: 400, message: `请先完善数据库连接信息:${paramsError}` }; + return; + } + + const result = await testConnection(params); + if (!result.success) { + ctx.status = 400; + ctx.body = { code: 400, message: result.message }; + return; + } + + let conn = null; + try { + conn = await openConnection(params); + const tables = await listTables(conn, params); + ctx.body = { code: 0, message: 'success', data: { tables } }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: `连接失败:${err && err.message ? err.message : '未知错误'}` }; + } finally { + await closeQuietly(conn); + } + } + + /** + * @summary 拉取指定表的字段 + * @description 字段映射下拉使用;表名必须真实存在于该库,避免任意 SQL 访问 + * @router get /api/shops/{id}/database-config/columns + * @apikey + * @request path integer *id 店铺主键ID + * @request query string *table 表名 + * @response 200 baseResponse success + */ + async columns() { + const { ctx } = this; + const shop = await this.loadShop(ctx.params.id); + if (!shop) return; + const table = String(ctx.query.table || '').trim(); + if (!table) { + ctx.status = 400; + ctx.body = { code: 400, message: 'table 为必填项' }; + return; + } + if (!SAFE_IDENTIFIER.test(table)) { + ctx.status = 400; + ctx.body = { code: 400, message: '表名不合法' }; + return; + } + + const config = await this.findConfig(shop); + const params = this.resolveParams({}, config); + const paramsError = validateParams(params); + if (paramsError) { + ctx.status = 400; + ctx.body = { code: 400, message: `请先完善数据库连接信息:${paramsError}` }; + return; + } + + let conn = null; + try { + conn = await openConnection(params); + const tables = await listTables(conn, params); + if (!tables.some(row => row.name === table)) { + ctx.status = 400; + ctx.body = { code: 400, message: `库中不存在表 ${table}` }; + return; + } + const columns = await listColumns(conn, params, table); + ctx.body = { code: 0, message: 'success', data: { table, columns } }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: `连接失败:${err && err.message ? err.message : '未知错误'}` }; + } finally { + await closeQuietly(conn); + } + } +} + +module.exports = ShopDatabaseController; diff --git a/backend/app/lib/shopDatabaseClient.js b/backend/app/lib/shopDatabaseClient.js new file mode 100644 index 0000000..4c70787 --- /dev/null +++ b/backend/app/lib/shopDatabaseClient.js @@ -0,0 +1,146 @@ +'use strict'; + +const mysql = require('mysql2/promise'); +const { DEFAULT_DB_TYPE, DEFAULT_PORT } = require('./shopDatabaseFields'); + +/** 连接超时(毫秒):客户自建库可能不可达,避免请求被长时间挂住 */ +const CONNECT_TIMEOUT = 8000; + +/** 表名 / 库名允许的字符(拉取到 SHOW TABLES 结果后会再次比对,这里是第一道校验) */ +const SAFE_IDENTIFIER = /^[\w$.-]{1,64}$/; + +/** + * 规范化连接参数:端口缺省 3306,去掉空白 + * @param {Object} params 原始参数 + * @return {Object} 规范化后的连接参数 + */ +function normalizeParams(params = {}) { + const port = Number(params.port); + return { + db_type: String(params.db_type || DEFAULT_DB_TYPE).trim() || DEFAULT_DB_TYPE, + host: String(params.host || '').trim(), + port: Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_PORT, + database_name: String(params.database_name || '').trim(), + username: String(params.username || '').trim(), + password: params.password == null ? '' : String(params.password), + }; +} + +/** + * 校验连接参数是否齐备 + * @param {Object} params normalizeParams 的结果 + * @return {string|null} 错误提示,校验通过返回 null + */ +function validateParams(params) { + if (params.db_type !== 'mysql') return '数据库类型暂只支持 MySQL'; + if (!params.host) return '请填写数据库地址(IP 或域名)'; + if (!/^[\w.-]{1,255}$/.test(params.host)) return '数据库地址格式不正确'; + if (!params.database_name) return '请填写数据库名'; + if (!SAFE_IDENTIFIER.test(params.database_name)) return '数据库名格式不正确'; + if (!params.username) return '请填写数据库账号'; + return null; +} + +/** + * 建立连接(仅用于测试连通 / 拉取表结构,用完必须关闭) + * @param {Object} params normalizeParams 的结果 + * @return {Promise} mysql2 连接 + */ +async function openConnection(params) { + return mysql.createConnection({ + host: params.host, + port: params.port, + user: params.username, + password: params.password, + database: params.database_name, + connectTimeout: CONNECT_TIMEOUT, + multipleStatements: false, + // 客户库字符集不确定,统一按 utf8mb4 读取,避免中文收件人乱码 + charset: 'utf8mb4', + }); +} + +/** + * 关闭连接(忽略关闭异常,避免掩盖原始错误) + * @param {Object} conn mysql2 连接 + * @return {Promise} 无 + */ +async function closeQuietly(conn) { + if (!conn) return; + try { + await conn.end(); + } catch { + // 忽略 + } +} + +/** + * 测试连通:取服务器版本,确认账号可读该库 + * @param {Object} params normalizeParams 的结果 + * @return {Promise<{success: boolean, message: string, server_version?: string}>} 测试结果 + */ +async function testConnection(params) { + let conn = null; + const startedAt = Date.now(); + try { + conn = await openConnection(params); + const [ rows ] = await conn.query('SELECT VERSION() AS version'); + const version = rows && rows[0] ? String(rows[0].version) : ''; + return { + success: true, + message: `连接成功(${Date.now() - startedAt} ms)`, + server_version: version, + }; + } catch (err) { + return { success: false, message: `连接失败:${err && err.message ? err.message : '未知错误'}` }; + } finally { + await closeQuietly(conn); + } +} + +/** + * 列出库内所有表 + * @param {Object} conn mysql2 连接 + * @param {Object} params normalizeParams 的结果(用于限定库名) + * @return {Promise>} 表名与注释列表 + */ +async function listTables(conn, params) { + const [ rows ] = await conn.query( + 'SELECT TABLE_NAME AS name, TABLE_COMMENT AS comment FROM information_schema.TABLES' + + ' WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = ? ORDER BY TABLE_NAME ASC', + [ params.database_name, 'BASE TABLE' ] + ); + return rows.map(row => ({ name: String(row.name), comment: String(row.comment || '') })); +} + +/** + * 列出表字段 + * @param {Object} conn mysql2 连接 + * @param {Object} params normalizeParams 的结果 + * @param {string} table 表名(必须已在 listTables 结果中出现) + * @return {Promise>} 字段列表 + */ +async function listColumns(conn, params, table) { + const [ rows ] = await conn.query( + 'SELECT COLUMN_NAME AS name, COLUMN_TYPE AS type, COLUMN_COMMENT AS comment' + + ' FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION ASC', + [ params.database_name, table ] + ); + return rows.map(row => ({ + name: String(row.name), + type: String(row.type || ''), + comment: String(row.comment || ''), + })); +} + +module.exports = { + CONNECT_TIMEOUT, + SAFE_IDENTIFIER, + normalizeParams, + validateParams, + openConnection, + closeQuietly, + testConnection, + listTables, + listColumns, +}; diff --git a/backend/app/lib/shopDatabaseFields.js b/backend/app/lib/shopDatabaseFields.js new file mode 100644 index 0000000..3066abf --- /dev/null +++ b/backend/app/lib/shopDatabaseFields.js @@ -0,0 +1,88 @@ +'use strict'; + +/** + * 数据库店铺(shops.type=3)可映射的 OMS 字段定义 + * + * 数据库店铺只支持「明文订单」:源库里的收件人、省市区等字段都是直接可读的值, + * 不需要解密/解析,因此每个字段都要求人工指定对应的源表列名。 + * 商品表 / 订单表 / 订单明细表三组字段分别独立映射。 + */ + +/** 支持的数据库类型(当前仅 MySQL) */ +const DB_TYPES = [ + { value: 'mysql', label: 'MySQL' }, +]; +const DEFAULT_DB_TYPE = 'mysql'; +const DEFAULT_PORT = 3306; + +/** + * 三张数据集的定义:key 与表 config 列一一对应 + * - tableColumn:保存表名的列(shop_database_configs 内) + * - fieldColumn:保存字段映射的列(JSON:{ oms字段: 源列名 }) + */ +const DATASETS = { + product: { + label: '商品表', + tableColumn: 'product_table', + fieldColumn: 'product_fields', + fields: [ + { key: 'item_code', label: '商品编码', required: true }, + { key: 'item_name', label: '商品名称', required: true }, + { key: 'sku_property', label: 'SKU规格', required: false }, + { key: 'barcode', label: '条码', required: false }, + { key: 'stock_unit', label: '库存单位', required: false }, + { key: 'price', label: '单价', required: false }, + ], + }, + order: { + label: '订单表', + tableColumn: 'order_table', + fieldColumn: 'order_fields', + fields: [ + { key: 'order_no', label: '订单号', required: true }, + { key: 'place_order_time', label: '下单时间', required: false }, + { key: 'receiver', label: '收件人', required: true }, + { key: 'mobile', label: '手机号', required: false }, + { key: 'tel', label: '电话', required: false }, + { key: 'province', label: '省', required: true }, + { key: 'city', label: '市', required: true }, + { key: 'area', label: '区/县', required: true }, + { key: 'town', label: '街道/镇', required: false }, + { key: 'detail_address', label: '详细地址', required: true }, + { key: 'zip_code', label: '邮编', required: false }, + { key: 'total_amount', label: '订单金额', required: false }, + { key: 'freight', label: '运费', required: false }, + { key: 'buyer_message', label: '买家留言', required: false }, + { key: 'seller_message', label: '卖家留言', required: false }, + ], + }, + order_item: { + label: '订单明细表', + tableColumn: 'order_item_table', + fieldColumn: 'order_item_fields', + fields: [ + { key: 'order_no', label: '订单号(关联订单表)', required: true }, + { key: 'item_code', label: '商品编码', required: true }, + { key: 'item_name', label: '商品名称', required: false }, + { key: 'sku_property', label: 'SKU规格', required: false }, + { key: 'quantity', label: '数量', required: true }, + { key: 'price', label: '单价', required: false }, + ], + }, +}; + +/** + * 供接口返回给前端的字段定义(含必填标记与保存列名,前端据此渲染映射表单) + * @return {Array} 三组字段定义 + */ +function datasetDefs() { + return Object.entries(DATASETS).map(([ key, def ]) => ({ + key, + label: def.label, + table_column: def.tableColumn, + field_column: def.fieldColumn, + fields: def.fields.map(field => ({ key: field.key, label: field.label, required: field.required })), + })); +} + +module.exports = { DB_TYPES, DEFAULT_DB_TYPE, DEFAULT_PORT, DATASETS, datasetDefs }; diff --git a/backend/app/model/shopDatabaseConfig.js b/backend/app/model/shopDatabaseConfig.js new file mode 100644 index 0000000..9a9540d --- /dev/null +++ b/backend/app/model/shopDatabaseConfig.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 数据库店铺(shops.type=3)连接配置与表/字段映射,一店一条 + * + * 密码存储明文(与仓库接口 app_secret 口径一致),查询接口不回显。 + * 字段映射以「OMS 字段 → 源表列名」的形式存放在三个 JSON 列中, + * 具体可选字段见 app/lib/shopDatabaseFields.js。 + * @param {Egg.Application} app egg application + * @return {object} shop_database_config model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, DATE, JSON: JSONTYPE } = app.Sequelize; + + const ShopDatabaseConfig = app.model.define('shop_database_config', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + shop_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '店铺ID(shops.id,type=3 数据库店铺)' }, + db_type: { type: STRING(20), allowNull: false, defaultValue: 'mysql', comment: '数据库类型:mysql' }, + host: { type: STRING(255), comment: '数据库地址(IP 或域名)' }, + port: { type: INTEGER, comment: '数据库端口' }, + database_name: { type: STRING(100), comment: '数据库名' }, + username: { type: STRING(100), comment: '数据库账号' }, + password: { type: STRING(255), comment: '数据库密码(明文,接口不回显)' }, + product_table: { type: STRING(100), comment: '商品表名' }, + order_table: { type: STRING(100), comment: '订单表名' }, + order_item_table: { type: STRING(100), comment: '订单明细表名' }, + product_fields: { type: JSONTYPE, comment: '商品表字段映射:{ oms字段: 源列名 }' }, + order_fields: { type: JSONTYPE, comment: '订单表字段映射:{ oms字段: 源列名 }' }, + order_item_fields: { type: JSONTYPE, comment: '订单明细表字段映射:{ oms字段: 源列名 }' }, + last_test_at: { type: DATE, comment: '最近一次测试连通时间' }, + last_test_success: { type: TINYINT, comment: '最近一次测试结果:1成功 0失败' }, + last_test_message: { type: STRING(500), comment: '最近一次测试结果说明' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }, { + tableName: 'shop_database_configs', + comment: '数据库店铺连接与表/字段映射配置', + }); + + ShopDatabaseConfig.associate = () => { + app.model.ShopDatabaseConfig.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.ShopDatabaseConfig.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' }); + }; + + return ShopDatabaseConfig; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 1000718..0049ebc 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -146,6 +146,13 @@ module.exports = app => { router.post('/api/order-items/:id/parse', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem.parse); router.resources('orderItems', '/api/order-items', jwtAuth, principalCheck({ model: 'OrderItem' }), controller.orderItem); // 店铺与店铺商品(采集的商品可绑定到系统商品或组合商品) + // 数据库店铺(type=3)的连接与表/字段映射配置:需在 resources('shops') 之前注册,避免 /database-config 被当成 :id + router.get('/api/shops/:id/database-config', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.show); + router.put('/api/shops/:id/database-config', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.save); + router.post('/api/shops/:id/database-config/test', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.test); + router.post('/api/shops/:id/database-config/connect', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.connect); + router.get('/api/shops/:id/database-config/tables', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.tables); + router.get('/api/shops/:id/database-config/columns', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.columns); router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop); // 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定; // 同步商品时平台已不存在的商品会自动移除 diff --git a/backend/database/migrations/20261105074000-create-shop-database-configs.js b/backend/database/migrations/20261105074000-create-shop-database-configs.js new file mode 100644 index 0000000..fea16d0 --- /dev/null +++ b/backend/database/migrations/20261105074000-create-shop-database-configs.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * 数据库店铺(shops.type=3)的连接配置与表/字段映射 + * + * 数据库店铺直接连客户自有数据库拉取明文订单:连接信息(host/port/账号/密码) + * 与「商品表 / 订单表 / 订单明细表」的选表结果、字段映射都存放在本表(一店一配置)。 + * 密码按明文存储(与仓库接口 app_secret 口径一致),接口不回显。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('shop_database_configs', { + id: { type: Sequelize.BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + shop_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '店铺ID(shops.id,type=3 数据库店铺)', + references: { model: 'shops', key: 'id' }, + }, + db_type: { type: Sequelize.STRING(20), allowNull: false, defaultValue: 'mysql', comment: '数据库类型:mysql' }, + host: { type: Sequelize.STRING(255), allowNull: true, comment: '数据库地址(IP 或域名)' }, + port: { type: Sequelize.INTEGER, allowNull: true, comment: '数据库端口' }, + database_name: { type: Sequelize.STRING(100), allowNull: true, comment: '数据库名' }, + username: { type: Sequelize.STRING(100), allowNull: true, comment: '数据库账号' }, + password: { type: Sequelize.STRING(255), allowNull: true, comment: '数据库密码(明文,接口不回显)' }, + product_table: { type: Sequelize.STRING(100), allowNull: true, comment: '商品表名' }, + order_table: { type: Sequelize.STRING(100), allowNull: true, comment: '订单表名' }, + order_item_table: { type: Sequelize.STRING(100), allowNull: true, comment: '订单明细表名' }, + product_fields: { type: Sequelize.JSON, allowNull: true, comment: '商品表字段映射:{ oms字段: 源列名 }' }, + order_fields: { type: Sequelize.JSON, allowNull: true, comment: '订单表字段映射:{ oms字段: 源列名 }' }, + order_item_fields: { type: Sequelize.JSON, allowNull: true, comment: '订单明细表字段映射:{ oms字段: 源列名 }' }, + last_test_at: { type: Sequelize.DATE, allowNull: true, comment: '最近一次测试连通时间' }, + last_test_success: { type: Sequelize.TINYINT, allowNull: true, comment: '最近一次测试结果:1成功 0失败' }, + last_test_message: { type: Sequelize.STRING(500), allowNull: true, comment: '最近一次测试结果说明' }, + created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' }, + updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' }, + }); + + await queryInterface.addIndex('shop_database_configs', [ 'principal_id', 'shop_id' ], { + name: 'uk_shop_database_configs_shop', + unique: true, + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('shop_database_configs'); + }, +}; diff --git a/frontend/src/api/shop.ts b/frontend/src/api/shop.ts index 2e7cb84..1c6d7be 100644 --- a/frontend/src/api/shop.ts +++ b/frontend/src/api/shop.ts @@ -13,7 +13,7 @@ export interface ShopItem { contact_name: string | null contact_phone: string | null status: number - /** 店铺类型:1 平台店铺 2 外部打单平台商家 3 数据库模式(预留) */ + /** 店铺类型:1 平台店铺 2 外部打单平台商家 3 数据库店铺 */ type?: number /** 来源外部打单账号ID(type=2 时有值) */ external_print_account_id?: number | null @@ -50,6 +50,8 @@ export interface ShopPayload { subsidiary_id?: number | null name: string platform?: string + /** 店铺类型:1 平台店铺(默认)/ 3 数据库店铺 */ + type?: number contact_name?: string contact_phone?: string status?: number diff --git a/frontend/src/api/shopDatabase.ts b/frontend/src/api/shopDatabase.ts new file mode 100644 index 0000000..0ccdb1e --- /dev/null +++ b/frontend/src/api/shopDatabase.ts @@ -0,0 +1,125 @@ +import { get, post, put } from '@/utils/request' + +/** 数据库店铺可选类型 */ +export interface ShopDatabaseTypeOption { + value: string + label: string +} + +/** 数据库店铺可映射的 OMS 字段 */ +export interface ShopDatabaseDatasetField { + key: string + label: string + required: boolean +} + +/** 一组数据集定义(商品表 / 订单表 / 订单明细表) */ +export interface ShopDatabaseDataset { + /** 数据集标识:product / order / order_item */ + key: string + label: string + /** 保存表名的配置字段名 */ + table_column: string + /** 保存字段映射的配置字段名 */ + field_column: string + fields: ShopDatabaseDatasetField[] +} + +/** OMS 字段 → 源表列名 */ +export type ShopDatabaseFieldMapping = Record + +/** 数据库店铺配置(密码不回显) */ +export interface ShopDatabaseConfig { + shop_id: number + db_type: string + host: string + port: number | null + database_name: string + username: string + /** 是否已保存密码(密码不回显) */ + has_password: boolean + product_table: string + order_table: string + order_item_table: string + product_fields: ShopDatabaseFieldMapping + order_fields: ShopDatabaseFieldMapping + order_item_fields: ShopDatabaseFieldMapping + last_test_at?: string | null + last_test_success?: number | null + last_test_message?: string +} + +/** 连接参数(保存 / 测试 / 连接共用),密码留空表示沿用已保存密码 */ +export interface ShopDatabaseConnectionPayload { + db_type?: string + host?: string + port?: number | null + database_name?: string + username?: string + password?: string +} + +/** 保存配置入参(连接参数 + 三张数据集选表与字段映射) */ +export interface ShopDatabaseSavePayload extends ShopDatabaseConnectionPayload { + product_table?: string + order_table?: string + order_item_table?: string + product_fields?: ShopDatabaseFieldMapping + order_fields?: ShopDatabaseFieldMapping + order_item_fields?: ShopDatabaseFieldMapping +} + +/** 库内数据表 */ +export interface ShopDatabaseTable { + name: string + comment?: string +} + +/** 表字段 */ +export interface ShopDatabaseColumn { + name: string + type: string + comment?: string +} + +/** 配置详情(含可映射字段定义) */ +export function getShopDatabaseConfig(shopId: number) { + return get<{ + config: ShopDatabaseConfig + db_types: ShopDatabaseTypeOption[] + datasets: ShopDatabaseDataset[] + }>(`/shops/${shopId}/database-config`) +} + +/** 保存配置:连接信息 + 选表 + 字段映射 */ +export function saveShopDatabaseConfig(shopId: number, data: ShopDatabaseSavePayload) { + return put<{ id: number; verified: boolean }>(`/shops/${shopId}/database-config`, data) +} + +/** 测试连通(服务端连接,浏览器不直连) */ +export function testShopDatabaseConnection(shopId: number, data: ShopDatabaseConnectionPayload) { + return post<{ success: boolean; message: string; server_version?: string }>( + `/shops/${shopId}/database-config/test`, + data, + ) +} + +/** 连接并拉取库内数据表 */ +export function connectShopDatabase(shopId: number, data: ShopDatabaseConnectionPayload) { + return post<{ success: boolean; tables: ShopDatabaseTable[] }>( + `/shops/${shopId}/database-config/connect`, + data, + ) +} + +/** 用已保存配置拉取数据表 */ +export function getShopDatabaseTables(shopId: number) { + return get<{ tables: ShopDatabaseTable[] }>(`/shops/${shopId}/database-config/tables`) +} + +/** 拉取指定表的字段(字段映射下拉用) */ +export function getShopDatabaseColumns(shopId: number, table: string) { + return get<{ table: string; columns: ShopDatabaseColumn[] }>(`/shops/${shopId}/database-config/columns`, { + table, + }) +} diff --git a/frontend/src/views/Shop/Index.vue b/frontend/src/views/Shop/Index.vue index 38277a9..c0a4144 100644 --- a/frontend/src/views/Shop/Index.vue +++ b/frontend/src/views/Shop/Index.vue @@ -13,6 +13,19 @@ import { import { syncExternalPrintShopProducts, syncExternalPrintShopOrders } from '@/api/externalPrintAccount' import { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary' import { getAccessContext } from '@/api/access' +import { + getShopDatabaseConfig, + saveShopDatabaseConfig, + testShopDatabaseConnection, + connectShopDatabase, + getShopDatabaseTables, + getShopDatabaseColumns, + type ShopDatabaseDataset, + type ShopDatabaseFieldMapping, + type ShopDatabaseTable, + type ShopDatabaseColumn, + type ShopDatabaseTypeOption, +} from '@/api/shopDatabase' import SplitLayout from '@/components/SplitLayout.vue' import ExportButton from '@/components/ExportButton.vue' import DataTable from '@/components/DataTable.vue' @@ -30,8 +43,16 @@ const PLATFORMS = [ const STATUS_LABELS: Record = { 1: '启用', 0: '禁用' } -/** 店铺类型:1 平台店铺 2 外部打单平台商家 3 数据库模式(预留) */ -const TYPE_LABELS: Record = { 1: '平台店铺', 2: '外部打单平台', 3: '数据库模式' } +/** 店铺类型:1 平台店铺 2 外部打单平台商家 3 数据库店铺 */ +const TYPE_LABELS: Record = { 1: '平台店铺', 2: '外部打单平台', 3: '数据库店铺' } + +/** 新建店铺可选类型:平台店铺 / 数据库店铺(外部打单平台店铺由打单平台导入) */ +const SHOP_TYPE_PLATFORM = 1 +const SHOP_TYPE_DATABASE = 3 +const CREATABLE_TYPES = [ + { label: '平台店铺', value: SHOP_TYPE_PLATFORM }, + { label: '数据库店铺', value: SHOP_TYPE_DATABASE }, +] function platformLabel(value?: string | null) { return PLATFORMS.find((p) => p.value === value)?.label || value || '-' @@ -123,6 +144,7 @@ const form = reactive({ code: '', subsidiary_id: null as number | null, name: '', + type: SHOP_TYPE_PLATFORM, platform: '', contact_name: '', contact_phone: '', @@ -158,6 +180,7 @@ function openCreate() { ? subsidiaryOptions.value[0].id : null form.name = '' + form.type = SHOP_TYPE_PLATFORM form.platform = '' form.contact_name = '' form.contact_phone = '' @@ -173,6 +196,7 @@ function openEdit(row: ShopItem) { form.code = row.code form.subsidiary_id = row.subsidiary_id ?? null form.name = row.name + form.type = Number(row.type) || SHOP_TYPE_PLATFORM form.platform = row.platform || '' form.contact_name = row.contact_name || '' form.contact_phone = row.contact_phone || '' @@ -192,10 +216,16 @@ async function submitForm() { const payload = { ...form, subsidiary_id: form.subsidiary_id == null ? null : Number(form.subsidiary_id), + // 店铺类型只在新增时提交,编辑接口不接受改类型 + ...(editId.value == null ? {} : { type: undefined }), } if (editId.value == null) { - const { code } = await createShop(payload) - ElMessage.success(`新增成功,店铺编码:${code}`) + const created = await createShop(payload) + ElMessage.success(`新增成功,店铺编码:${created.code}`) + // 数据库店铺还需要填连接信息,创建后直接打开配置弹窗 + if (payload.type === SHOP_TYPE_DATABASE) { + pendingConfigShop.value = { id: created.id, name: form.name } + } } else { await updateShop(editId.value, payload) ElMessage.success('保存成功') @@ -206,6 +236,12 @@ async function submitForm() { } dialogVisible.value = false await fetchList() + // 新建数据库店铺后直接进入数据库配置弹窗 + if (pendingConfigShop.value) { + const target = pendingConfigShop.value + pendingConfigShop.value = null + await openDatabaseConfig(target) + } } catch { // 拦截器已提示 } finally { @@ -214,6 +250,236 @@ async function submitForm() { }) } +/* -------------------- 数据库店铺配置 -------------------- */ +/** 新建数据库店铺后待打开配置弹窗的店铺 */ +const pendingConfigShop = ref<{ id: number; name: string } | null>(null) + +const dbConfigVisible = ref(false) +const dbConfigLoading = ref(false) +const dbConfigSaving = ref(false) +const dbTesting = ref(false) +const dbConnecting = ref(false) +const dbConfigShop = ref<{ id: number; name: string } | null>(null) +const dbTypes = ref([]) +const dbDatasets = ref([]) +/** 表选项:连接成功后填充,供三张数据集选择 */ +const dbTables = ref([]) +/** 表名 → 字段列表(字段映射下拉用) */ +const dbColumns = ref>({}) +/** 字段映射:数据集 key → { OMS字段: 源列名 } */ +const dbMappings = reactive>({}) +/** 最近一次保存/校验结果 */ +const dbLastResult = ref<{ success: boolean | null; message: string; at: string }>({ + success: null, + message: '', + at: '', +}) + +const dbForm = reactive({ + db_type: 'mysql', + host: '', + port: 3306 as number | null, + database_name: '', + username: '', + password: '', + product_table: '', + order_table: '', + order_item_table: '', +}) + +/** 连接参数(测试 / 连接 / 保存共用;密码留空表示沿用已保存密码) */ +function connectionPayload() { + return { + db_type: dbForm.db_type, + host: dbForm.host.trim(), + port: dbForm.port == null ? null : Number(dbForm.port), + database_name: dbForm.database_name.trim(), + username: dbForm.username.trim(), + password: dbForm.password, + } +} + +/** 打开数据库配置弹窗(读取已保存配置 + 字段定义) */ +async function openDatabaseConfig(row: { id: number; name: string }) { + dbConfigShop.value = { id: row.id, name: row.name } + dbConfigVisible.value = true + dbConfigLoading.value = true + dbTables.value = [] + dbColumns.value = {} + dbLastResult.value = { success: null, message: '', at: '' } + try { + const { config, db_types: types, datasets } = await getShopDatabaseConfig(row.id) + dbTypes.value = types + dbDatasets.value = datasets + dbForm.db_type = config.db_type || 'mysql' + dbForm.host = config.host || '' + dbForm.port = config.port ?? 3306 + dbForm.database_name = config.database_name || '' + dbForm.username = config.username || '' + // 密码不回显:留空即沿用已保存密码 + dbForm.password = '' + dbForm.product_table = config.product_table || '' + dbForm.order_table = config.order_table || '' + dbForm.order_item_table = config.order_item_table || '' + for (const dataset of datasets) { + const saved = (config as unknown as Record)[dataset.field_column] || {} + dbMappings[dataset.key] = { ...saved } + } + if (config.last_test_at) { + dbLastResult.value = { + success: config.last_test_success === 1, + message: config.last_test_message || '', + at: formatDateTime(config.last_test_at), + } + } + // 已保存过连接信息时顺手拉一次表与字段,避免每次都要点「连接」 + if (config.host && config.database_name && config.username) { + await loadSavedTables() + } + } catch { + // 拦截器已提示 + } finally { + dbConfigLoading.value = false + } +} + +/** 用已保存配置拉表(仅拉列表,字段在选表后单独拉) */ +async function loadSavedTables() { + if (!dbConfigShop.value) return + try { + const { tables } = await getShopDatabaseTables(dbConfigShop.value.id) + dbTables.value = tables + await ensureColumns([ dbForm.product_table, dbForm.order_table, dbForm.order_item_table ]) + } catch { + dbTables.value = [] + } +} + +/** 按需拉取多张表的字段(已有缓存则跳过) */ +async function ensureColumns(tables: Array) { + if (!dbConfigShop.value) return + const targets = [ ...new Set(tables.filter((t): t is string => !!t)) ] + await Promise.all(targets.map(async table => { + if (dbColumns.value[table]) return + try { + const { columns } = await getShopDatabaseColumns(dbConfigShop.value!.id, table) + dbColumns.value = { ...dbColumns.value, [table]: columns } + } catch { + // 单表拉取失败不阻断其它表 + } + })) +} + +/** 数据集当前选中的表名 */ +function tableOf(dataset: ShopDatabaseDataset) { + if (dataset.key === 'product') return dbForm.product_table + if (dataset.key === 'order') return dbForm.order_table + return dbForm.order_item_table +} + +/** 选表(v-model 用 getter/setter,避免模板里做动态键赋值) */ +function setTable(dataset: ShopDatabaseDataset, value: string | null) { + const table = value || '' + if (dataset.key === 'product') dbForm.product_table = table + else if (dataset.key === 'order') dbForm.order_table = table + else dbForm.order_item_table = table + onTableChange(dataset) +} + +/** 写入 / 清空单个字段映射 */ +function setMapping(datasetKey: string, fieldKey: string, value: string | null) { + if (!dbMappings[datasetKey]) dbMappings[datasetKey] = {} + if (value) dbMappings[datasetKey][fieldKey] = value + else delete dbMappings[datasetKey][fieldKey] +} + +/** 选表变化:清空该表已映射的列名并拉取字段 */ +async function onTableChange(dataset: ShopDatabaseDataset) { + dbMappings[dataset.key] = {} + await ensureColumns([ tableOf(dataset) ]) +} + +/** 字段映射下拉选项 */ +function columnsOf(dataset: ShopDatabaseDataset): ShopDatabaseColumn[] { + const table = tableOf(dataset) + return table ? (dbColumns.value[table] || []) : [] +} + +/** 测试连通(服务端连接) */ +async function handleTestConnection() { + if (!dbConfigShop.value) return + dbTesting.value = true + try { + const res = await testShopDatabaseConnection(dbConfigShop.value.id, connectionPayload()) + dbLastResult.value = { success: res.success, message: res.message, at: formatDateTime(new Date()) } + if (res.success) ElMessage.success(res.message) + else ElMessage.error(res.message) + } catch { + // 拦截器已提示 + } finally { + dbTesting.value = false + } +} + +/** 连接数据库并拉取数据表 */ +async function handleConnect() { + if (!dbConfigShop.value) return + dbConnecting.value = true + try { + const res = await connectShopDatabase(dbConfigShop.value.id, connectionPayload()) + dbTables.value = res.tables || [] + dbLastResult.value = { success: true, message: `连接成功,共 ${dbTables.value.length} 张表`, at: formatDateTime(new Date()) } + ElMessage.success(`连接成功,共 ${dbTables.value.length} 张表`) + await ensureColumns([ dbForm.product_table, dbForm.order_table, dbForm.order_item_table ]) + } catch { + // 拦截器已提示 + } finally { + dbConnecting.value = false + } +} + +/** 保存配置:连接信息 + 选表 + 字段映射 */ +async function handleSaveDatabaseConfig() { + if (!dbConfigShop.value) return + for (const dataset of dbDatasets.value) { + if (!tableOf(dataset)) { + ElMessage.warning(`请选择${dataset.label}`) + return + } + const missing = dataset.fields + .filter(field => field.required) + .filter(field => !(dbMappings[dataset.key] || {})[field.key]) + .map(field => field.label) + if (missing.length) { + ElMessage.warning(`${dataset.label}:请完成必填字段映射(${missing.join('、')})`) + return + } + } + dbConfigSaving.value = true + try { + const res = await saveShopDatabaseConfig(dbConfigShop.value.id, { + ...connectionPayload(), + product_table: dbForm.product_table, + order_table: dbForm.order_table, + order_item_table: dbForm.order_item_table, + product_fields: dbMappings.product || {}, + order_fields: dbMappings.order || {}, + order_item_fields: dbMappings.order_item || {}, + }) + ElMessage.success(res.verified ? '配置已保存' : '配置已保存(库不可达,未完成连库校验)') + dbLastResult.value = { success: res.verified, message: '配置已保存', at: formatDateTime(new Date()) } + dbConfigVisible.value = false + await fetchList() + if (currentShop.value && currentShop.value.id === dbConfigShop.value.id) { + await fetchDetail(currentShop.value.id) + } + } catch { + // 拦截器已提示 + } finally { + dbConfigSaving.value = false + } +} + /** 正在拉取订单的店铺ID(防止重复点击) */ const fetchingOrderId = ref(null) /** 拉取订单弹窗 */ @@ -428,6 +694,12 @@ onMounted(() => { type="primary" @click.stop="openEdit(row)" >编辑 + 配置 { - + + + + +
+ 数据库店铺保存后需在列表「配置」中填写数据库连接、选表与字段映射 +
+
+ @@ -628,6 +908,124 @@ onMounted(() => { + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 测试连通 + 连接 + 已加载 {{ dbTables.length }} 张表 + + {{ dbLastResult.at }}:{{ dbLastResult.success ? '成功' : '失败' }} {{ dbLastResult.message }} + +
+
+ + 表与字段映射 + +
+
+ {{ dataset.label }} + + + +
+ + + + + + + + +
+
+ +
+ { margin-left: 6px; color: var(--el-text-color-secondary); } +.db-tip { + margin-bottom: 10px; +} +.db-actions { + display: flex; + align-items: center; + gap: 8px; + margin: -4px 0 4px 110px; +} +.db-conn-tip { + color: var(--el-text-color-secondary); + font-size: 12px; +} +.db-dataset { + margin-bottom: 14px; +} +.db-dataset-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 6px; +} +.db-dataset-title { + font-weight: 600; +} +.db-map-table :deep(.el-table__cell) { + padding: 4px 0; +} +.db-required { + margin-left: 6px; +} .search-bar { margin-bottom: 12px; }