refactor(docs): 简化README结构,更新技术栈和项目结构描述
This commit is contained in:
85
scripts/database/check_remote_table_structure.js
Normal file
85
scripts/database/check_remote_table_structure.js
Normal file
@@ -0,0 +1,85 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function checkRemoteTableStructure() {
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('正在检查远程suppliers表结构...');
|
||||
|
||||
// 检查suppliers表结构
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'suppliers'
|
||||
ORDER BY ORDINAL_POSITION
|
||||
`);
|
||||
|
||||
console.log('\nsuppliers表当前字段:');
|
||||
console.table(columns.map(col => ({
|
||||
字段名: col.COLUMN_NAME,
|
||||
数据类型: col.DATA_TYPE,
|
||||
允许空值: col.IS_NULLABLE,
|
||||
默认值: col.COLUMN_DEFAULT,
|
||||
注释: col.COLUMN_COMMENT
|
||||
})));
|
||||
|
||||
// 检查是否缺少必要字段
|
||||
const requiredFields = ['bank_account', 'bank_name', 'tax_number', 'notes'];
|
||||
const existingFields = columns.map(col => col.COLUMN_NAME);
|
||||
const missingFields = requiredFields.filter(field => !existingFields.includes(field));
|
||||
|
||||
console.log(`\n字段检查结果:`);
|
||||
console.log(`总字段数: ${columns.length}`);
|
||||
console.log(`缺失字段: ${missingFields.length > 0 ? missingFields.join(', ') : '无'}`);
|
||||
|
||||
if (missingFields.length > 0) {
|
||||
console.log('\n需要添加的字段:');
|
||||
missingFields.forEach(field => {
|
||||
let fieldDef = '';
|
||||
switch(field) {
|
||||
case 'bank_account':
|
||||
fieldDef = 'varchar(50) DEFAULT NULL COMMENT \'银行账号\'';
|
||||
break;
|
||||
case 'bank_name':
|
||||
fieldDef = 'varchar(100) DEFAULT NULL COMMENT \'开户银行\'';
|
||||
break;
|
||||
case 'tax_number':
|
||||
fieldDef = 'varchar(30) DEFAULT NULL COMMENT \'税务登记号\'';
|
||||
break;
|
||||
case 'notes':
|
||||
fieldDef = 'text DEFAULT NULL COMMENT \'备注信息\'';
|
||||
break;
|
||||
}
|
||||
console.log(`- ${field}: ${fieldDef}`);
|
||||
});
|
||||
}
|
||||
|
||||
// 检查数据量
|
||||
const [countResult] = await connection.execute('SELECT COUNT(*) as count FROM suppliers');
|
||||
console.log(`\nsuppliers表数据量: ${countResult[0].count} 条记录`);
|
||||
|
||||
await connection.end();
|
||||
return { missingFields, totalRecords: countResult[0].count };
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 检查表结构失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行检查
|
||||
checkRemoteTableStructure().then(result => {
|
||||
console.log('\n✅ 表结构检查完成');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
39
scripts/database/check_table_structure.js
Normal file
39
scripts/database/check_table_structure.js
Normal file
@@ -0,0 +1,39 @@
|
||||
const { Sequelize } = require('../../backend/node_modules/sequelize');
|
||||
|
||||
async function checkTableStructure() {
|
||||
const sequelize = new Sequelize('niumall', 'root', '123456', {
|
||||
host: 'localhost',
|
||||
dialect: 'mysql',
|
||||
logging: false
|
||||
});
|
||||
|
||||
try {
|
||||
console.log('正在检查suppliers表结构...');
|
||||
|
||||
const [results] = await sequelize.query(`
|
||||
DESCRIBE suppliers
|
||||
`);
|
||||
|
||||
console.log('suppliers表字段列表:');
|
||||
console.table(results);
|
||||
|
||||
// 检查是否有bank_account字段
|
||||
const hasBank = results.some(field => field.Field === 'bank_account');
|
||||
console.log(`\nbank_account字段存在: ${hasBank ? '是' : '否'}`);
|
||||
|
||||
if (!hasBank) {
|
||||
console.log('\n需要添加的字段:');
|
||||
console.log('- bank_account');
|
||||
console.log('- bank_name');
|
||||
console.log('- tax_number');
|
||||
console.log('- notes');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 检查失败:', error.message);
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
|
||||
checkTableStructure().catch(console.error);
|
||||
72
scripts/database/check_users_table.js
Normal file
72
scripts/database/check_users_table.js
Normal file
@@ -0,0 +1,72 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function checkUsersTable() {
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('正在检查users表...');
|
||||
|
||||
// 检查users表是否存在
|
||||
const [tables] = await connection.execute(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'users'
|
||||
`);
|
||||
|
||||
if (tables.length === 0) {
|
||||
console.log('❌ users表不存在');
|
||||
await connection.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('✅ users表存在');
|
||||
|
||||
// 检查用户数据
|
||||
const [users] = await connection.execute(`
|
||||
SELECT id, uuid, username, display_name, real_name, phone, email, role, status
|
||||
FROM users
|
||||
ORDER BY id
|
||||
`);
|
||||
|
||||
console.log(`\nusers表数据 (${users.length}条记录):`);
|
||||
console.table(users);
|
||||
|
||||
// 检查是否有管理员用户
|
||||
const [adminUsers] = await connection.execute(`
|
||||
SELECT username, role, status
|
||||
FROM users
|
||||
WHERE role = 'admin' AND status = 'active'
|
||||
`);
|
||||
|
||||
console.log(`\n管理员用户 (${adminUsers.length}个):`);
|
||||
if (adminUsers.length > 0) {
|
||||
console.table(adminUsers);
|
||||
} else {
|
||||
console.log('❌ 没有找到活跃的管理员用户');
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 检查users表失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行检查
|
||||
checkUsersTable().then(() => {
|
||||
console.log('\n✅ users表检查完成');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
75
scripts/database/check_users_table_simple.js
Normal file
75
scripts/database/check_users_table_simple.js
Normal file
@@ -0,0 +1,75 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function checkUsersTableSimple() {
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('正在检查users表结构...');
|
||||
|
||||
// 先检查表结构
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'users'
|
||||
ORDER BY ORDINAL_POSITION
|
||||
`);
|
||||
|
||||
console.log('\nusers表字段结构:');
|
||||
console.table(columns.map(col => ({
|
||||
字段名: col.COLUMN_NAME,
|
||||
数据类型: col.DATA_TYPE,
|
||||
允许空值: col.IS_NULLABLE,
|
||||
默认值: col.COLUMN_DEFAULT,
|
||||
注释: col.COLUMN_COMMENT
|
||||
})));
|
||||
|
||||
// 检查用户数据(使用实际存在的字段)
|
||||
const [users] = await connection.execute(`SELECT * FROM users LIMIT 10`);
|
||||
|
||||
console.log(`\nusers表数据 (前10条记录):`);
|
||||
console.table(users);
|
||||
|
||||
// 检查管理员用户
|
||||
const [adminCheck] = await connection.execute(`
|
||||
SELECT COUNT(*) as admin_count
|
||||
FROM users
|
||||
WHERE role = 'admin'
|
||||
`);
|
||||
|
||||
console.log(`\n管理员用户数量: ${adminCheck[0].admin_count}`);
|
||||
|
||||
if (adminCheck[0].admin_count > 0) {
|
||||
const [adminUsers] = await connection.execute(`
|
||||
SELECT username, role, status
|
||||
FROM users
|
||||
WHERE role = 'admin'
|
||||
`);
|
||||
console.log('\n管理员用户列表:');
|
||||
console.table(adminUsers);
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 检查users表失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行检查
|
||||
checkUsersTableSimple().then(() => {
|
||||
console.log('\n✅ users表检查完成');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
62
scripts/database/fix_suppliers_table.js
Normal file
62
scripts/database/fix_suppliers_table.js
Normal file
@@ -0,0 +1,62 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function fixSuppliersTable() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: 'localhost',
|
||||
user: 'root',
|
||||
password: '123456',
|
||||
database: 'niumall'
|
||||
});
|
||||
|
||||
try {
|
||||
console.log('正在修复suppliers表结构...');
|
||||
|
||||
// 检查字段是否已存在
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'suppliers'
|
||||
AND COLUMN_NAME IN ('bank_account', 'bank_name', 'tax_number', 'notes')
|
||||
`);
|
||||
|
||||
const existingColumns = columns.map(col => col.COLUMN_NAME);
|
||||
console.log('已存在的字段:', existingColumns);
|
||||
|
||||
// 添加缺失的字段
|
||||
const fieldsToAdd = [
|
||||
{ name: 'bank_account', sql: 'ADD COLUMN bank_account varchar(50) DEFAULT NULL COMMENT \'银行账号\'' },
|
||||
{ name: 'bank_name', sql: 'ADD COLUMN bank_name varchar(100) DEFAULT NULL COMMENT \'开户银行\'' },
|
||||
{ name: 'tax_number', sql: 'ADD COLUMN tax_number varchar(30) DEFAULT NULL COMMENT \'税务登记号\'' },
|
||||
{ name: 'notes', sql: 'ADD COLUMN notes text DEFAULT NULL COMMENT \'备注信息\'' }
|
||||
];
|
||||
|
||||
for (const field of fieldsToAdd) {
|
||||
if (!existingColumns.includes(field.name)) {
|
||||
console.log(`添加字段: ${field.name}`);
|
||||
await connection.execute(`ALTER TABLE suppliers ${field.sql}`);
|
||||
} else {
|
||||
console.log(`字段 ${field.name} 已存在,跳过`);
|
||||
}
|
||||
}
|
||||
|
||||
// 修改status字段的枚举值
|
||||
console.log('更新status字段枚举值...');
|
||||
await connection.execute(`
|
||||
ALTER TABLE suppliers
|
||||
MODIFY COLUMN status enum('active','inactive','suspended','blacklisted')
|
||||
NOT NULL DEFAULT 'active' COMMENT '状态'
|
||||
`);
|
||||
|
||||
console.log('✅ suppliers表结构修复完成!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 修复失败:', error.message);
|
||||
throw error;
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
// 执行修复
|
||||
fixSuppliersTable().catch(console.error);
|
||||
67
scripts/database/fix_test_data.js
Normal file
67
scripts/database/fix_test_data.js
Normal file
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const fs = require('fs').promises;
|
||||
|
||||
async function fixTestData() {
|
||||
console.log('开始修复测试数据的时间戳字段...');
|
||||
|
||||
try {
|
||||
// 读取原始文件
|
||||
const content = await fs.readFile('./init_test_data.sql', 'utf8');
|
||||
|
||||
// 需要添加时间戳字段的表和对应的INSERT语句模式
|
||||
const tableFields = {
|
||||
'suppliers': ', `created_at`, `updated_at`',
|
||||
'drivers': ', `created_at`, `updated_at`',
|
||||
'vehicles': ', `created_at`, `updated_at`',
|
||||
'orders': ', `created_at`, `updated_at`',
|
||||
'payments': ', `created_at`, `updated_at`',
|
||||
'transports': ', `created_at`, `updated_at`',
|
||||
'transport_tracking': ', `created_at`, `updated_at`',
|
||||
'quality_inspections': ', `created_at`, `updated_at`',
|
||||
'settlements': ', `created_at`, `updated_at`'
|
||||
};
|
||||
|
||||
let fixedContent = content;
|
||||
|
||||
// 为每个表修复INSERT语句
|
||||
for (const [tableName, timeFields] of Object.entries(tableFields)) {
|
||||
// 查找INSERT语句的模式
|
||||
const insertPattern = new RegExp(
|
||||
`(INSERT INTO \`${tableName}\` \\([^)]+\\)) VALUES\\s*\\n([\\s\\S]*?);`,
|
||||
'g'
|
||||
);
|
||||
|
||||
fixedContent = fixedContent.replace(insertPattern, (match, insertPart, valuesPart) => {
|
||||
// 在字段列表中添加时间戳字段
|
||||
const newInsertPart = insertPart + timeFields;
|
||||
|
||||
// 在每个VALUES行的末尾添加时间戳值
|
||||
const fixedValuesPart = valuesPart.replace(/\),?\s*$/gm, (valueMatch) => {
|
||||
if (valueMatch.includes('),')) {
|
||||
return ', NOW(), NOW()),';
|
||||
} else {
|
||||
return ', NOW(), NOW())';
|
||||
}
|
||||
});
|
||||
|
||||
return `${newInsertPart} VALUES\n${fixedValuesPart};`;
|
||||
});
|
||||
}
|
||||
|
||||
// 写入修复后的文件
|
||||
await fs.writeFile('./init_test_data_fixed.sql', fixedContent);
|
||||
console.log('✅ 测试数据修复完成,已保存为 init_test_data_fixed.sql');
|
||||
|
||||
// 显示修复的统计信息
|
||||
const originalInserts = (content.match(/INSERT INTO/g) || []).length;
|
||||
const fixedInserts = (fixedContent.match(/INSERT INTO/g) || []).length;
|
||||
console.log(`原始INSERT语句数量: ${originalInserts}`);
|
||||
console.log(`修复后INSERT语句数量: ${fixedInserts}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('修复失败:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
fixTestData().catch(console.error);
|
||||
@@ -70,7 +70,11 @@ CREATE TABLE `suppliers` (
|
||||
`capacity` int(11) DEFAULT NULL COMMENT '供应能力(头/月)',
|
||||
`rating` decimal(3,2) DEFAULT '0.00' COMMENT '供应商评级(0-5分)',
|
||||
`cooperation_start_date` date DEFAULT NULL COMMENT '合作开始日期',
|
||||
`status` enum('active','inactive','suspended') NOT NULL DEFAULT 'active' COMMENT '状态',
|
||||
`status` enum('active','inactive','suspended','blacklisted') NOT NULL DEFAULT 'active' COMMENT '状态',
|
||||
`bank_account` varchar(50) DEFAULT NULL COMMENT '银行账号',
|
||||
`bank_name` varchar(100) DEFAULT NULL COMMENT '开户银行',
|
||||
`tax_number` varchar(30) DEFAULT NULL COMMENT '税务登记号',
|
||||
`notes` text DEFAULT NULL COMMENT '备注信息',
|
||||
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
@@ -337,40 +341,9 @@ CREATE TABLE `settlements` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='结算表';
|
||||
|
||||
-- =====================================================
|
||||
-- 外键约束
|
||||
-- 注意:为了避免权限问题和简化数据库结构,此脚本不使用外键约束
|
||||
-- 数据完整性将通过应用层逻辑来保证
|
||||
-- =====================================================
|
||||
-- 订单表外键
|
||||
ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_buyer` FOREIGN KEY (`buyerId`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_supplier` FOREIGN KEY (`supplierId`) REFERENCES `suppliers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_trader` FOREIGN KEY (`traderId`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- 支付表外键
|
||||
ALTER TABLE `payments` ADD CONSTRAINT `fk_payments_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `payments` ADD CONSTRAINT `fk_payments_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 车辆表外键
|
||||
ALTER TABLE `vehicles` ADD CONSTRAINT `fk_vehicles_driver` FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 司机表外键
|
||||
ALTER TABLE `drivers` ADD CONSTRAINT `fk_drivers_vehicle` FOREIGN KEY (`current_vehicle_id`) REFERENCES `vehicles` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- 运输表外键
|
||||
ALTER TABLE `transports` ADD CONSTRAINT `fk_transports_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `transports` ADD CONSTRAINT `fk_transports_driver` FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
ALTER TABLE `transports` ADD CONSTRAINT `fk_transports_vehicle` FOREIGN KEY (`vehicle_id`) REFERENCES `vehicles` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 运输跟踪表外键
|
||||
ALTER TABLE `transport_tracks` ADD CONSTRAINT `fk_transport_tracks_transport` FOREIGN KEY (`transport_id`) REFERENCES `transports` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `transport_tracks` ADD CONSTRAINT `fk_transport_tracks_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `transport_tracks` ADD CONSTRAINT `fk_transport_tracks_driver` FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 质检记录表外键
|
||||
ALTER TABLE `quality_records` ADD CONSTRAINT `fk_quality_records_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `quality_records` ADD CONSTRAINT `fk_quality_records_inspector` FOREIGN KEY (`inspector_id`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 结算表外键
|
||||
ALTER TABLE `settlements` ADD CONSTRAINT `fk_settlements_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE `settlements` ADD CONSTRAINT `fk_settlements_approver` FOREIGN KEY (`approver_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- 恢复外键检查
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
@@ -11,13 +11,13 @@ SET FOREIGN_KEY_CHECKS = 0;
|
||||
-- =====================================================
|
||||
-- 1. 用户测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `users` (`id`, `uuid`, `username`, `password_hash`, `nickname`, `real_name`, `phone`, `email`, `user_type`, `company_name`, `status`, `registration_source`) VALUES
|
||||
(1, 'admin-uuid-001', 'admin', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '系统管理员', '张三', '13800138001', 'admin@niumall.com', 'admin', '牛牛商城', 'active', 'admin_create'),
|
||||
(2, 'buyer-uuid-001', 'buyer001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商李四', '李四', '13800138002', 'buyer001@example.com', 'buyer', '大华肉业有限公司', 'active', 'web'),
|
||||
(3, 'buyer-uuid-002', 'buyer002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商王五', '王五', '13800138003', 'buyer002@example.com', 'buyer', '鑫源食品集团', 'active', 'web'),
|
||||
(4, 'trader-uuid-001', 'trader001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '贸易商赵六', '赵六', '13800138004', 'trader001@example.com', 'trader', '中原贸易公司', 'active', 'web'),
|
||||
(5, 'staff-uuid-001', 'staff001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小明', '陈明', '13800138005', 'staff001@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create'),
|
||||
(6, 'staff-uuid-002', 'staff002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小红', '李红', '13800138006', 'staff002@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create');
|
||||
INSERT INTO `users` (`id`, `uuid`, `username`, `password_hash`, `nickname`, `real_name`, `phone`, `email`, `user_type`, `company_name`, `status`, `registration_source`, `created_at`, `updated_at`) VALUES
|
||||
(1, 'admin-uuid-001', 'admin', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '系统管理员', '张三', '13800138001', 'admin@niumall.com', 'admin', '牛牛商城', 'active', 'admin_create', NOW(), NOW()),
|
||||
(2, 'buyer-uuid-001', 'buyer001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商李四', '李四', '13800138002', 'buyer001@example.com', 'buyer', '大华肉业有限公司', 'active', 'web', NOW(), NOW()),
|
||||
(3, 'buyer-uuid-002', 'buyer002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商王五', '王五', '13800138003', 'buyer002@example.com', 'buyer', '鑫源食品集团', 'active', 'web', NOW(), NOW()),
|
||||
(4, 'trader-uuid-001', 'trader001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '贸易商赵六', '赵六', '13800138004', 'trader001@example.com', 'trader', '中原贸易公司', 'active', 'web', NOW(), NOW()),
|
||||
(5, 'staff-uuid-001', 'staff001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小明', '陈明', '13800138005', 'staff001@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create', NOW(), NOW()),
|
||||
(6, 'staff-uuid-002', 'staff002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小红', '李红', '13800138006', 'staff002@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 2. 供应商测试数据
|
||||
|
||||
128
scripts/database/init_test_data_fixed.sql
Normal file
128
scripts/database/init_test_data_fixed.sql
Normal file
@@ -0,0 +1,128 @@
|
||||
-- =====================================================
|
||||
-- 牛牛商城测试数据初始化脚本
|
||||
-- 创建时间: 2024-01-21
|
||||
-- 描述: 插入测试数据,用于开发和测试环境
|
||||
-- =====================================================
|
||||
|
||||
-- 设置字符集
|
||||
SET NAMES utf8mb4;
|
||||
SET FOREIGN_KEY_CHECKS = 0;
|
||||
|
||||
-- =====================================================
|
||||
-- 1. 用户测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `users` (`id`, `uuid`, `username`, `password_hash`, `nickname`, `real_name`, `phone`, `email`, `user_type`, `company_name`, `status`, `registration_source`, `created_at`, `updated_at`) VALUES
|
||||
(1, 'admin-uuid-001', 'admin', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '系统管理员', '张三', '13800138001', 'admin@niumall.com', 'admin', '牛牛商城', 'active', 'admin_create', NOW(), NOW()),
|
||||
(2, 'buyer-uuid-001', 'buyer001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商李四', '李四', '13800138002', 'buyer001@example.com', 'buyer', '大华肉业有限公司', 'active', 'web', NOW(), NOW()),
|
||||
(3, 'buyer-uuid-002', 'buyer002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '采购商王五', '王五', '13800138003', 'buyer002@example.com', 'buyer', '鑫源食品集团', 'active', 'web', NOW(), NOW()),
|
||||
(4, 'trader-uuid-001', 'trader001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '贸易商赵六', '赵六', '13800138004', 'trader001@example.com', 'trader', '中原贸易公司', 'active', 'web', NOW(), NOW()),
|
||||
(5, 'staff-uuid-001', 'staff001', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小明', '陈明', '13800138005', 'staff001@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create', NOW(), NOW()),
|
||||
(6, 'staff-uuid-002', 'staff002', '$2b$10$N9qo8uLOickgx2ZMRZoMye.IjPeGGvse/rXhd0.UpFrF6wcE.iy/i', '质检员小红', '李红', '13800138006', 'staff002@niumall.com', 'staff', '牛牛商城', 'active', 'admin_create', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 2. 供应商测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `suppliers` (`id`, `name`, `code`, `contact`, `phone`, `email`, `address`, `region`, `qualification_level`, `cattle_types`, `capacity`, `rating`, `cooperation_start_date`, `status`), `created_at`, `updated_at` VALUES
|
||||
(1, '内蒙古草原牧业有限公司', 'SUP001', '张牧民', '13900139001', 'contact@nmgcy.com', '内蒙古呼和浩特市赛罕区草原路123号', '内蒙古', 'A', '["西门塔尔牛", "安格斯牛", "夏洛莱牛"]', 500, 4.8, '2023-01-15', 'active', NOW(), NOW()),
|
||||
(2, '山东鲁西黄牛养殖场', 'SUP002', '李养牛', '13900139002', 'contact@sdlx.com', '山东济宁市嘉祥县畜牧路456号', '山东', 'A', '["鲁西黄牛", "利木赞牛"]', 300, 4.6, '2023-03-20', 'active', NOW(), NOW()),
|
||||
(3, '河南豫南肉牛合作社', 'SUP003', '王合作', '13900139003', 'contact@hnyn.com', '河南南阳市宛城区牧业大道789号', '河南', 'B', '["西门塔尔牛", "夏洛莱牛"]', 200, 4.2, '2023-05-10', 'active', NOW(), NOW()),
|
||||
(4, '新疆天山牧业集团', 'SUP004', '马天山', '13900139004', 'contact@xjts.com', '新疆乌鲁木齐市天山区牧场路321号', '新疆', 'A', '["安格斯牛", "海福特牛"]', 400, 4.7, '2023-02-28', 'active', NOW(), NOW()),
|
||||
(5, '黑龙江北大荒牧业', 'SUP005', '刘北方', '13900139005', 'contact@hlbdh.com', '黑龙江哈尔滨市道里区牧业街654号', '黑龙江', 'B', '["西门塔尔牛", "利木赞牛"]', 250, 4.3, '2023-04-15', 'active', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 3. 司机测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `drivers` (`id`, `name`, `phone`, `id_card`, `driver_license`, `license_type`, `license_expiry_date`, `emergency_contact`, `emergency_phone`, `employment_type`, `hire_date`, `salary`, `performance_rating`, `status`), `created_at`, `updated_at` VALUES
|
||||
(1, '张运输', '13700137001', '110101198001011234', 'A2001234567890', 'A2', '2025-12-31', '张妻子', '13700137101', 'full_time', '2023-01-10', 8000.00, 4.5, 'active', NOW(), NOW()),
|
||||
(2, '李司机', '13700137002', '110101198002022345', 'A2001234567891', 'A2', '2026-06-30', '李父亲', '13700137102', 'full_time', '2023-02-15', 7500.00, 4.3, 'active', NOW(), NOW()),
|
||||
(3, '王师傅', '13700137003', '110101198003033456', 'A2001234567892', 'A2', '2025-09-30', '王儿子', '13700137103', 'full_time', '2023-03-20', 7800.00, 4.6, 'active', NOW(), NOW()),
|
||||
(4, '赵老板', '13700137004', '110101198004044567', 'A2001234567893', 'A2', '2026-03-31', '赵妻子', '13700137104', 'contract', '2023-04-10', 9000.00, 4.8, 'active', NOW(), NOW()),
|
||||
(5, '陈快递', '13700137005', '110101198005055678', 'A2001234567894', 'A2', '2025-11-30', '陈母亲', '13700137105', 'part_time', '2023-05-05', 6500.00, 4.1, 'active', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 4. 车辆测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `vehicles` (`id`, `license_plate`, `vehicle_type`, `capacity`, `driver_id`, `status`, `last_maintenance_date`, `next_maintenance_date`, `insurance_expiry_date`, `registration_expiry_date`), `created_at`, `updated_at` VALUES
|
||||
(1, '京A12345', '大型货车', 15000, 1, 'available', '2024-01-15', '2024-04-15', '2024-12-31', '2025-01-10', NOW(), NOW()),
|
||||
(2, '京B23456', '中型货车', 10000, 2, 'available', '2024-01-20', '2024-04-20', '2024-11-30', '2025-02-15', NOW(), NOW()),
|
||||
(3, '京C34567', '大型货车', 18000, 3, 'in_use', '2024-01-10', '2024-04-10', '2024-10-31', '2025-03-20', NOW(), NOW()),
|
||||
(4, '京D45678', '特大型货车', 25000, 4, 'available', '2024-01-25', '2024-04-25', '2025-01-31', '2025-04-10', NOW(), NOW()),
|
||||
(5, '京E56789', '中型货车', 12000, 5, 'maintenance', '2024-01-05', '2024-04-05', '2024-09-30', '2025-05-05', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 5. 订单测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `orders` (`id`, `orderNo`, `buyerId`, `buyerName`, `supplierId`, `supplierName`, `traderId`, `traderName`, `cattleBreed`, `cattleCount`, `expectedWeight`, `actualWeight`, `unitPrice`, `totalAmount`, `deliveryAddress`, `deliveryDate`, `paymentMethod`, `paymentStatus`, `orderStatus`), `created_at`, `updated_at` VALUES
|
||||
(1, 'ORD202401001', 2, '大华肉业有限公司', 1, '内蒙古草原牧业有限公司', 4, '中原贸易公司', '西门塔尔牛', 50, 25000.00, 24800.00, 28.50, 706800.00, '北京市朝阳区肉联厂路100号', '2024-02-15', 'bank_transfer', 'partial_paid', 'shipped', NOW(), NOW()),
|
||||
(2, 'ORD202401002', 3, '鑫源食品集团', 2, '山东鲁西黄牛养殖场', NULL, NULL, '鲁西黄牛', 30, 18000.00, NULL, 26.80, 482400.00, '上海市浦东新区食品工业园区200号', '2024-02-20', 'bank_transfer', 'unpaid', 'confirmed', NOW(), NOW()),
|
||||
(3, 'ORD202401003', 2, '大华肉业有限公司', 3, '河南豫南肉牛合作社', NULL, NULL, '夏洛莱牛', 40, 22000.00, NULL, 29.20, 642400.00, '北京市朝阳区肉联厂路100号', '2024-02-25', 'online_payment', 'unpaid', 'pending', NOW(), NOW()),
|
||||
(4, 'ORD202401004', 3, '鑫源食品集团', 4, '新疆天山牧业集团', 4, '中原贸易公司', '安格斯牛', 60, 32000.00, NULL, 32.00, 1024000.00, '上海市浦东新区食品工业园区200号', '2024-03-01', 'bank_transfer', 'unpaid', 'pending', NOW(), NOW()),
|
||||
(5, 'ORD202401005', 2, '大华肉业有限公司', 5, '黑龙江北大荒牧业', NULL, NULL, '西门塔尔牛', 35, 19500.00, NULL, 27.50, 536250.00, '北京市朝阳区肉联厂路100号', '2024-03-05', 'bank_transfer', 'unpaid', 'pending', NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 6. 支付测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `payments` (`id`, `order_id`, `user_id`, `amount`, `paid_amount`, `payment_type`, `payment_method`, `payment_no`, `third_party_id`, `status`, `paid_time`), `created_at`, `updated_at` VALUES
|
||||
(1, 1, 2, 353400.00, 353400.00, 'bank', 'web', 'PAY202401001001', 'BANK20240115001', 'paid', '2024-01-15 14:30:00', NOW(), NOW()),
|
||||
(2, 1, 2, 353400.00, NULL, 'bank', 'web', 'PAY202401001002', NULL, 'pending', NULL, NOW(), NOW()),
|
||||
(3, 2, 3, 241200.00, NULL, 'bank', 'web', 'PAY202401002001', NULL, 'pending', NULL, NOW(), NOW()),
|
||||
(4, 2, 3, 241200.00, NULL, 'bank', 'web', 'PAY202401002002', NULL, 'pending', NULL, NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 7. 运输测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `transports` (`id`, `order_id`, `driver_id`, `vehicle_id`, `start_location`, `end_location`, `scheduled_start_time`, `actual_start_time`, `scheduled_end_time`, `actual_end_time`, `status`, `estimated_arrival_time`, `distance`, `fuel_cost`, `toll_cost`, `other_cost`, `total_cost`), `created_at`, `updated_at` VALUES
|
||||
(1, 1, 3, 3, '内蒙古呼和浩特市赛罕区草原路123号', '北京市朝阳区肉联厂路100号', '2024-02-10 08:00:00', '2024-02-10 08:30:00', '2024-02-12 18:00:00', NULL, 'in_transit', '2024-02-12 16:00:00', 450.5, 1800.00, 200.00, 100.00, 2100.00, NOW(), NOW()),
|
||||
(2, 2, 2, 2, '山东济宁市嘉祥县畜牧路456号', '上海市浦东新区食品工业园区200号', '2024-02-18 06:00:00', NULL, '2024-02-20 20:00:00', NULL, 'scheduled', '2024-02-20 18:00:00', 680.2, 2400.00, 350.00, 150.00, 2900.00, NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 8. 运输跟踪测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `transport_tracks` (`id`, `transport_id`, `order_id`, `driver_id`, `latitude`, `longitude`, `speed`, `direction`, `cattle_status`, `temperature`, `humidity`, `created_at`) VALUES
|
||||
(1, 1, 1, 3, 40.8518, 111.7519, 65.5, 135.2, '正常', 2.5, 45.0, '2024-02-10 10:00:00'),
|
||||
(2, 1, 1, 3, 40.9234, 111.6789, 68.2, 140.8, '正常', 3.2, 42.0, '2024-02-10 12:00:00'),
|
||||
(3, 1, 1, 3, 41.0567, 111.5432, 62.8, 138.5, '正常', 4.1, 38.0, '2024-02-10 14:00:00'),
|
||||
(4, 1, 1, 3, 41.2345, 111.3456, 70.1, 142.3, '正常', 5.8, 35.0, '2024-02-10 16:00:00'),
|
||||
(5, 1, 1, 3, 41.4567, 111.1234, 66.7, 139.7, '正常', 6.5, 32.0, '2024-02-10 18:00:00');
|
||||
|
||||
-- =====================================================
|
||||
-- 9. 质检记录测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `quality_records` (`id`, `order_id`, `inspector_id`, `inspection_type`, `inspection_date`, `location`, `cattle_count_expected`, `cattle_count_actual`, `weight_expected`, `weight_actual`, `health_status`, `breed_verification`, `age_range_verification`, `overall_rating`, `pass_status`, `inspector_notes`, `buyer_confirmation`) VALUES
|
||||
(1, 1, 5, 'pre_loading', '2024-02-10 07:00:00', '内蒙古呼和浩特市赛罕区草原路123号', 50, 50, 25000.00, 24800.00, 'excellent', 1, 1, 4.8, 'passed', '牛只健康状况良好,品种纯正,符合订单要求', 0),
|
||||
(2, 1, 6, 'arrival', '2024-02-12 15:30:00', '北京市朝阳区肉联厂路100号', 50, 50, 24800.00, 24800.00, 'good', 1, 1, 4.5, 'passed', '运输过程中牛只状态稳定,无明显损失', 1);
|
||||
|
||||
-- =====================================================
|
||||
-- 10. 结算测试数据
|
||||
-- =====================================================
|
||||
INSERT INTO `settlements` (`id`, `order_id`, `settlement_no`, `settlement_type`, `cattle_count`, `unit_price`, `total_weight`, `gross_amount`, `deduction_amount`, `deduction_reason`, `net_amount`, `payment_method`, `payment_status`, `payment_date`, `invoice_required`, `invoice_type`, `invoice_status`, `approver_id`, `approval_status`, `approval_time`), `created_at`, `updated_at` VALUES
|
||||
(1, 1, 'SET202401001', 'advance', 50, 28.50, 24800.00, 706800.00, 0.00, NULL, 353400.00, 'bank_transfer', 'paid', '2024-01-15', 1, 'special', 'issued', 1, 'approved', '2024-01-14 16:00:00', NOW(), NOW()),
|
||||
(2, 1, 'SET202401002', 'final', 50, 28.50, 24800.00, 706800.00, 0.00, NULL, 353400.00, 'bank_transfer', 'pending', NULL, 1, 'special', 'not_issued', 1, 'pending', NULL, NOW(), NOW());
|
||||
|
||||
-- =====================================================
|
||||
-- 更新司机当前车辆关联
|
||||
-- =====================================================
|
||||
UPDATE `drivers` SET `current_vehicle_id` = 1 WHERE `id` = 1;
|
||||
UPDATE `drivers` SET `current_vehicle_id` = 2 WHERE `id` = 2;
|
||||
UPDATE `drivers` SET `current_vehicle_id` = 3 WHERE `id` = 3;
|
||||
UPDATE `drivers` SET `current_vehicle_id` = 4 WHERE `id` = 4;
|
||||
UPDATE `drivers` SET `current_vehicle_id` = 5 WHERE `id` = 5;
|
||||
|
||||
-- 恢复外键检查
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
-- =====================================================
|
||||
-- 完成测试数据插入
|
||||
-- =====================================================
|
||||
SELECT '测试数据插入完成!' as message;
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM users) as users_count,
|
||||
(SELECT COUNT(*) FROM suppliers) as suppliers_count,
|
||||
(SELECT COUNT(*) FROM drivers) as drivers_count,
|
||||
(SELECT COUNT(*) FROM vehicles) as vehicles_count,
|
||||
(SELECT COUNT(*) FROM orders) as orders_count,
|
||||
(SELECT COUNT(*) FROM payments) as payments_count,
|
||||
(SELECT COUNT(*) FROM transports) as transports_count,
|
||||
(SELECT COUNT(*) FROM transport_tracks) as transport_tracks_count,
|
||||
(SELECT COUNT(*) FROM quality_records) as quality_records_count,
|
||||
(SELECT COUNT(*) FROM settlements) as settlements_count;
|
||||
@@ -24,7 +24,10 @@ const defaultConfig = {
|
||||
port: 3306,
|
||||
user: 'root',
|
||||
password: '',
|
||||
database: 'niumall'
|
||||
database: 'niumall',
|
||||
skipStructure: false,
|
||||
skipData: false,
|
||||
dataFile: 'init_test_data.sql'
|
||||
};
|
||||
|
||||
// 显示帮助信息
|
||||
@@ -41,11 +44,13 @@ function showHelp() {
|
||||
console.log(' --database DB 数据库名称 (默认: niumall)');
|
||||
console.log(' --skip-structure 跳过表结构创建');
|
||||
console.log(' --skip-data 跳过测试数据插入');
|
||||
console.log(' --data-file FILE 指定测试数据文件 (默认: init_test_data.sql)');
|
||||
console.log(' --help 显示此帮助信息');
|
||||
console.log('');
|
||||
console.log('示例:');
|
||||
console.log(' node init_with_node.js --user root --password secret');
|
||||
console.log(' node init_with_node.js --host 192.168.1.100 --database test');
|
||||
console.log(' node init_with_node.js --data-file init_test_data_fixed.sql');
|
||||
}
|
||||
|
||||
// 解析命令行参数
|
||||
@@ -78,6 +83,9 @@ function parseArgs() {
|
||||
case '--skip-data':
|
||||
skipData = true;
|
||||
break;
|
||||
case '--data-file':
|
||||
config.dataFile = args[++i];
|
||||
break;
|
||||
case '--help':
|
||||
showHelp();
|
||||
process.exit(0);
|
||||
@@ -261,7 +269,7 @@ async function main() {
|
||||
|
||||
// 4. 插入测试数据
|
||||
if (!skipData && success) {
|
||||
const dataFile = path.join(__dirname, 'init_test_data.sql');
|
||||
const dataFile = path.join(__dirname, config.dataFile);
|
||||
if (!await executeSqlFile(config, dataFile, '测试数据插入')) {
|
||||
success = false;
|
||||
}
|
||||
|
||||
179
scripts/database/insert_suppliers_test_data.js
Normal file
179
scripts/database/insert_suppliers_test_data.js
Normal file
@@ -0,0 +1,179 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function insertSuppliersTestData() {
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('正在插入suppliers测试数据...');
|
||||
|
||||
// 先清空现有数据(可选)
|
||||
console.log('清空现有suppliers数据...');
|
||||
await connection.execute('DELETE FROM suppliers');
|
||||
await connection.execute('ALTER TABLE suppliers AUTO_INCREMENT = 1');
|
||||
|
||||
// 插入测试数据,包含新增字段
|
||||
const testData = [
|
||||
{
|
||||
id: 1,
|
||||
name: '内蒙古草原牧业有限公司',
|
||||
code: 'SUP001',
|
||||
contact: '张牧民',
|
||||
phone: '13900139001',
|
||||
email: 'contact@nmgcy.com',
|
||||
address: '内蒙古呼和浩特市赛罕区草原路123号',
|
||||
region: '内蒙古',
|
||||
qualification_level: 'A',
|
||||
cattle_types: JSON.stringify(['西门塔尔牛', '安格斯牛', '夏洛莱牛']),
|
||||
capacity: 500,
|
||||
rating: 4.8,
|
||||
cooperation_start_date: '2023-01-15',
|
||||
status: 'active',
|
||||
bank_account: '6228480012345678901',
|
||||
bank_name: '中国农业银行呼和浩特分行',
|
||||
tax_number: '91150100123456789X',
|
||||
notes: '优质供应商,合作稳定,产品质量优秀'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '山东鲁西黄牛养殖场',
|
||||
code: 'SUP002',
|
||||
contact: '李养牛',
|
||||
phone: '13900139002',
|
||||
email: 'contact@sdlx.com',
|
||||
address: '山东济宁市嘉祥县畜牧路456号',
|
||||
region: '山东',
|
||||
qualification_level: 'A',
|
||||
cattle_types: JSON.stringify(['鲁西黄牛', '利木赞牛']),
|
||||
capacity: 300,
|
||||
rating: 4.6,
|
||||
cooperation_start_date: '2023-03-20',
|
||||
status: 'active',
|
||||
bank_account: '6228480023456789012',
|
||||
bank_name: '中国工商银行济宁分行',
|
||||
tax_number: '91370829234567890A',
|
||||
notes: '专业黄牛养殖,品种纯正'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: '河南豫南肉牛合作社',
|
||||
code: 'SUP003',
|
||||
contact: '王合作',
|
||||
phone: '13900139003',
|
||||
email: 'contact@hnyn.com',
|
||||
address: '河南南阳市宛城区牧业大道789号',
|
||||
region: '河南',
|
||||
qualification_level: 'B',
|
||||
cattle_types: JSON.stringify(['西门塔尔牛', '夏洛莱牛']),
|
||||
capacity: 200,
|
||||
rating: 4.2,
|
||||
cooperation_start_date: '2023-05-10',
|
||||
status: 'active',
|
||||
bank_account: '6228480034567890123',
|
||||
bank_name: '中国建设银行南阳分行',
|
||||
tax_number: '91411303345678901B',
|
||||
notes: '合作社模式,农户联合经营'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: '新疆天山牧业集团',
|
||||
code: 'SUP004',
|
||||
contact: '马天山',
|
||||
phone: '13900139004',
|
||||
email: 'contact@xjts.com',
|
||||
address: '新疆乌鲁木齐市天山区牧场路321号',
|
||||
region: '新疆',
|
||||
qualification_level: 'A',
|
||||
cattle_types: JSON.stringify(['安格斯牛', '海福特牛']),
|
||||
capacity: 400,
|
||||
rating: 4.7,
|
||||
cooperation_start_date: '2023-02-28',
|
||||
status: 'active',
|
||||
bank_account: '6228480045678901234',
|
||||
bank_name: '中国银行乌鲁木齐分行',
|
||||
tax_number: '91650100456789012C',
|
||||
notes: '大型牧业集团,规模化经营'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
name: '黑龙江北大荒牧业',
|
||||
code: 'SUP005',
|
||||
contact: '刘北方',
|
||||
phone: '13900139005',
|
||||
email: 'contact@hlbdh.com',
|
||||
address: '黑龙江哈尔滨市道里区牧业街654号',
|
||||
region: '黑龙江',
|
||||
qualification_level: 'B',
|
||||
cattle_types: JSON.stringify(['西门塔尔牛', '利木赞牛']),
|
||||
capacity: 250,
|
||||
rating: 4.3,
|
||||
cooperation_start_date: '2023-04-15',
|
||||
status: 'active',
|
||||
bank_account: '6228480056789012345',
|
||||
bank_name: '中国邮政储蓄银行哈尔滨分行',
|
||||
tax_number: '91230102567890123D',
|
||||
notes: '北大荒品牌,信誉良好'
|
||||
}
|
||||
];
|
||||
|
||||
// 批量插入数据
|
||||
const insertSql = `
|
||||
INSERT INTO suppliers (
|
||||
id, name, code, contact, phone, email, address, region,
|
||||
qualification_level, cattle_types, capacity, rating,
|
||||
cooperation_start_date, status, bank_account, bank_name,
|
||||
tax_number, notes, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
`;
|
||||
|
||||
for (const supplier of testData) {
|
||||
const values = [
|
||||
supplier.id, supplier.name, supplier.code, supplier.contact,
|
||||
supplier.phone, supplier.email, supplier.address, supplier.region,
|
||||
supplier.qualification_level, supplier.cattle_types, supplier.capacity,
|
||||
supplier.rating, supplier.cooperation_start_date, supplier.status,
|
||||
supplier.bank_account, supplier.bank_name, supplier.tax_number, supplier.notes
|
||||
];
|
||||
|
||||
await connection.execute(insertSql, values);
|
||||
console.log(`✅ 插入供应商: ${supplier.name}`);
|
||||
}
|
||||
|
||||
// 验证插入结果
|
||||
const [result] = await connection.execute('SELECT COUNT(*) as count FROM suppliers');
|
||||
console.log(`\n插入完成,suppliers表共有 ${result[0].count} 条记录`);
|
||||
|
||||
// 显示插入的数据
|
||||
const [suppliers] = await connection.execute(`
|
||||
SELECT id, name, code, contact, phone, bank_account, bank_name, tax_number, status
|
||||
FROM suppliers
|
||||
ORDER BY id
|
||||
`);
|
||||
|
||||
console.log('\n插入的供应商数据:');
|
||||
console.table(suppliers);
|
||||
|
||||
await connection.end();
|
||||
console.log('\n✅ suppliers测试数据插入完成!');
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 插入测试数据失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行插入
|
||||
insertSuppliersTestData().then(() => {
|
||||
console.log('测试数据插入成功');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
238
scripts/database/mysql_operations.js
Normal file
238
scripts/database/mysql_operations.js
Normal file
@@ -0,0 +1,238 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
|
||||
// 数据库连接配置
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
class MySQLOperations {
|
||||
constructor() {
|
||||
this.connection = null;
|
||||
}
|
||||
|
||||
async connect() {
|
||||
try {
|
||||
this.connection = await mysql.createConnection(config);
|
||||
console.log('✅ 成功连接到远程MySQL数据库');
|
||||
console.log(`主机: ${config.host}:${config.port}`);
|
||||
console.log(`数据库: ${config.database}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('❌ 连接数据库失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
if (this.connection) {
|
||||
await this.connection.end();
|
||||
console.log('数据库连接已关闭');
|
||||
}
|
||||
}
|
||||
|
||||
async showTables() {
|
||||
try {
|
||||
const [tables] = await this.connection.execute('SHOW TABLES');
|
||||
console.log('\n📋 数据库中的表:');
|
||||
tables.forEach((table, index) => {
|
||||
console.log(`${index + 1}. ${Object.values(table)[0]}`);
|
||||
});
|
||||
return tables;
|
||||
} catch (error) {
|
||||
console.error('❌ 获取表列表失败:', error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async describeTable(tableName) {
|
||||
try {
|
||||
const [columns] = await this.connection.execute(`DESCRIBE ${tableName}`);
|
||||
console.log(`\n📊 表 ${tableName} 的结构:`);
|
||||
console.table(columns);
|
||||
return columns;
|
||||
} catch (error) {
|
||||
console.error(`❌ 获取表 ${tableName} 结构失败:`, error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async executeSQL(sql) {
|
||||
try {
|
||||
const [result] = await this.connection.execute(sql);
|
||||
console.log('✅ SQL执行成功');
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('❌ SQL执行失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async executeSQLFile(filePath) {
|
||||
try {
|
||||
const sqlContent = await fs.readFile(filePath, 'utf8');
|
||||
|
||||
// 分割SQL语句(简单处理,按分号分割)
|
||||
const statements = sqlContent
|
||||
.split(';')
|
||||
.map(stmt => stmt.trim())
|
||||
.filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
|
||||
|
||||
console.log(`\n📄 执行SQL文件: ${filePath}`);
|
||||
console.log(`包含 ${statements.length} 条SQL语句`);
|
||||
|
||||
for (let i = 0; i < statements.length; i++) {
|
||||
const stmt = statements[i];
|
||||
if (stmt.toLowerCase().startsWith('select') ||
|
||||
stmt.toLowerCase().startsWith('show') ||
|
||||
stmt.toLowerCase().startsWith('describe')) {
|
||||
// 查询语句
|
||||
const [result] = await this.connection.execute(stmt);
|
||||
console.log(`语句 ${i + 1}: ${stmt.substring(0, 50)}...`);
|
||||
if (result.length > 0) {
|
||||
console.log(`返回 ${result.length} 行数据`);
|
||||
}
|
||||
} else {
|
||||
// 其他语句(INSERT, UPDATE, DELETE等)
|
||||
const [result] = await this.connection.execute(stmt);
|
||||
console.log(`语句 ${i + 1}: ${stmt.substring(0, 50)}...`);
|
||||
if (result.affectedRows !== undefined) {
|
||||
console.log(`影响 ${result.affectedRows} 行`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✅ SQL文件执行完成');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('❌ 执行SQL文件失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async checkTableData(tableName, limit = 5) {
|
||||
try {
|
||||
const [rows] = await this.connection.execute(`SELECT * FROM ${tableName} LIMIT ${limit}`);
|
||||
const [count] = await this.connection.execute(`SELECT COUNT(*) as total FROM ${tableName}`);
|
||||
|
||||
console.log(`\n📊 表 ${tableName} 数据概览:`);
|
||||
console.log(`总记录数: ${count[0].total}`);
|
||||
|
||||
if (rows.length > 0) {
|
||||
console.log(`前 ${rows.length} 条记录:`);
|
||||
console.table(rows);
|
||||
} else {
|
||||
console.log('表中暂无数据');
|
||||
}
|
||||
|
||||
return { total: count[0].total, rows };
|
||||
} catch (error) {
|
||||
console.error(`❌ 检查表 ${tableName} 数据失败:`, error.message);
|
||||
return { total: 0, rows: [] };
|
||||
}
|
||||
}
|
||||
|
||||
async interactiveMode() {
|
||||
console.log('\n🔧 进入交互模式 (输入 "exit" 退出)');
|
||||
console.log('可用命令:');
|
||||
console.log(' tables - 显示所有表');
|
||||
console.log(' desc <表名> - 显示表结构');
|
||||
console.log(' data <表名> - 显示表数据');
|
||||
console.log(' sql <SQL语句> - 执行SQL');
|
||||
console.log(' file <文件路径> - 执行SQL文件');
|
||||
console.log(' exit - 退出');
|
||||
|
||||
const readline = require('readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
const askQuestion = () => {
|
||||
rl.question('\nmysql> ', async (input) => {
|
||||
const command = input.trim();
|
||||
|
||||
if (command === 'exit') {
|
||||
rl.close();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (command === 'tables') {
|
||||
await this.showTables();
|
||||
} else if (command.startsWith('desc ')) {
|
||||
const tableName = command.substring(5).trim();
|
||||
await this.describeTable(tableName);
|
||||
} else if (command.startsWith('data ')) {
|
||||
const tableName = command.substring(5).trim();
|
||||
await this.checkTableData(tableName);
|
||||
} else if (command.startsWith('sql ')) {
|
||||
const sql = command.substring(4).trim();
|
||||
await this.executeSQL(sql);
|
||||
} else if (command.startsWith('file ')) {
|
||||
const filePath = command.substring(5).trim();
|
||||
await this.executeSQLFile(filePath);
|
||||
} else if (command === '') {
|
||||
// 空命令,继续
|
||||
} else {
|
||||
console.log('未知命令,请输入 "exit" 退出或使用可用命令');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('执行命令时出错:', error.message);
|
||||
}
|
||||
|
||||
askQuestion();
|
||||
});
|
||||
};
|
||||
|
||||
askQuestion();
|
||||
}
|
||||
}
|
||||
|
||||
// 主函数
|
||||
async function main() {
|
||||
const db = new MySQLOperations();
|
||||
|
||||
// 连接数据库
|
||||
const connected = await db.connect();
|
||||
if (!connected) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
// 显示数据库信息
|
||||
await db.showTables();
|
||||
|
||||
// 检查关键表的结构和数据
|
||||
const keyTables = ['users', 'suppliers', 'orders', 'drivers', 'vehicles'];
|
||||
|
||||
for (const table of keyTables) {
|
||||
console.log(`\n${'='.repeat(50)}`);
|
||||
await db.describeTable(table);
|
||||
await db.checkTableData(table, 3);
|
||||
}
|
||||
|
||||
// 进入交互模式
|
||||
await db.interactiveMode();
|
||||
|
||||
} catch (error) {
|
||||
console.error('操作过程中出错:', error.message);
|
||||
} finally {
|
||||
await db.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// 如果直接运行此脚本
|
||||
if (require.main === module) {
|
||||
main().catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = MySQLOperations;
|
||||
115
scripts/database/test_insert.js
Normal file
115
scripts/database/test_insert.js
Normal file
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
const fs = require('fs').promises;
|
||||
|
||||
async function testInsert() {
|
||||
console.log('开始测试数据插入...');
|
||||
|
||||
const connection = await mysql.createConnection({
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall',
|
||||
multipleStatements: true
|
||||
});
|
||||
|
||||
try {
|
||||
// 读取修复后的测试数据文件
|
||||
const sqlContent = await fs.readFile('./init_test_data_fixed.sql', 'utf8');
|
||||
console.log('SQL文件读取成功,长度:', sqlContent.length);
|
||||
|
||||
// 更智能的SQL语句分割 - 处理多行INSERT
|
||||
const statements = [];
|
||||
let currentStatement = '';
|
||||
let inInsert = false;
|
||||
|
||||
const lines = sqlContent.split('\n');
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim();
|
||||
|
||||
// 跳过注释和空行
|
||||
if (trimmedLine.startsWith('--') || trimmedLine === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 检测INSERT语句开始
|
||||
if (trimmedLine.toUpperCase().startsWith('INSERT')) {
|
||||
if (currentStatement) {
|
||||
statements.push(currentStatement.trim());
|
||||
}
|
||||
currentStatement = line;
|
||||
inInsert = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果在INSERT语句中
|
||||
if (inInsert) {
|
||||
currentStatement += '\n' + line;
|
||||
// 检测INSERT语句结束(以分号结尾)
|
||||
if (trimmedLine.endsWith(';')) {
|
||||
statements.push(currentStatement.trim());
|
||||
currentStatement = '';
|
||||
inInsert = false;
|
||||
}
|
||||
} else {
|
||||
// 处理其他语句
|
||||
if (currentStatement) {
|
||||
currentStatement += '\n' + line;
|
||||
} else {
|
||||
currentStatement = line;
|
||||
}
|
||||
|
||||
if (trimmedLine.endsWith(';')) {
|
||||
statements.push(currentStatement.trim());
|
||||
currentStatement = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加最后一个语句(如果有)
|
||||
if (currentStatement.trim()) {
|
||||
statements.push(currentStatement.trim());
|
||||
}
|
||||
|
||||
console.log('总共解析出', statements.length, '条SQL语句');
|
||||
|
||||
// 查找INSERT语句
|
||||
const insertStatements = statements.filter(stmt => stmt.toUpperCase().includes('INSERT'));
|
||||
console.log('其中INSERT语句', insertStatements.length, '条');
|
||||
|
||||
// 执行第一条INSERT语句
|
||||
if (insertStatements.length > 0) {
|
||||
const firstInsert = insertStatements[0];
|
||||
console.log('执行第一条INSERT语句:');
|
||||
console.log(firstInsert.substring(0, 200) + '...');
|
||||
|
||||
try {
|
||||
const [result] = await connection.execute(firstInsert);
|
||||
console.log('✅ 插入成功,影响行数:', result.affectedRows);
|
||||
} catch (error) {
|
||||
console.error('❌ 插入失败:', error.message);
|
||||
console.error('错误代码:', error.code);
|
||||
}
|
||||
}
|
||||
|
||||
// 检查users表数据
|
||||
const [users] = await connection.execute('SELECT COUNT(*) as count FROM users');
|
||||
console.log('users表当前记录数:', users[0].count);
|
||||
|
||||
// 如果有数据,显示前几条
|
||||
if (users[0].count > 0) {
|
||||
const [userList] = await connection.execute('SELECT id, username, user_type FROM users LIMIT 3');
|
||||
console.log('用户数据示例:');
|
||||
userList.forEach(user => console.log(user));
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('测试失败:', error.message);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
testInsert().catch(console.error);
|
||||
57
scripts/database/test_remote_connection.js
Normal file
57
scripts/database/test_remote_connection.js
Normal file
@@ -0,0 +1,57 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function testRemoteConnection() {
|
||||
// 从.env文件读取配置
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
console.log('正在测试远程数据库连接...');
|
||||
console.log(`主机: ${config.host}:${config.port}`);
|
||||
console.log(`数据库: ${config.database}`);
|
||||
console.log(`用户: ${config.user}`);
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('✅ 远程数据库连接成功!');
|
||||
|
||||
// 测试查询
|
||||
const [rows] = await connection.execute('SELECT VERSION() as version');
|
||||
console.log(`MySQL版本: ${rows[0].version}`);
|
||||
|
||||
// 检查数据库是否存在
|
||||
const [databases] = await connection.execute('SHOW DATABASES');
|
||||
const dbExists = databases.some(db => db.Database === config.database);
|
||||
console.log(`数据库 ${config.database} 存在: ${dbExists ? '是' : '否'}`);
|
||||
|
||||
if (dbExists) {
|
||||
// 检查表列表
|
||||
const [tables] = await connection.execute('SHOW TABLES');
|
||||
console.log(`\n数据库中的表 (${tables.length}个):`);
|
||||
tables.forEach(table => {
|
||||
console.log(`- ${Object.values(table)[0]}`);
|
||||
});
|
||||
}
|
||||
|
||||
await connection.end();
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 远程数据库连接失败:');
|
||||
console.error(`错误信息: ${error.message}`);
|
||||
console.error(`错误代码: ${error.code}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行测试
|
||||
testRemoteConnection().then(success => {
|
||||
process.exit(success ? 0 : 1);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
76
scripts/database/test_suppliers_api.js
Normal file
76
scripts/database/test_suppliers_api.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const http = require('http');
|
||||
|
||||
function testSuppliersAPI() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const options = {
|
||||
hostname: 'localhost',
|
||||
port: 3000,
|
||||
path: '/api/suppliers',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
timeout: 5000
|
||||
};
|
||||
|
||||
console.log('正在测试suppliers API接口...');
|
||||
console.log(`请求: GET http://localhost:3000/api/suppliers`);
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
let data = '';
|
||||
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
console.log(`\n响应状态码: ${res.statusCode}`);
|
||||
console.log(`响应头: ${JSON.stringify(res.headers, null, 2)}`);
|
||||
|
||||
try {
|
||||
const jsonData = JSON.parse(data);
|
||||
console.log('\n响应数据:');
|
||||
console.log(JSON.stringify(jsonData, null, 2));
|
||||
|
||||
if (res.statusCode === 200 && jsonData.code === 200) {
|
||||
console.log('\n✅ suppliers API接口测试成功!');
|
||||
console.log(`返回数据条数: ${jsonData.data?.list?.length || 0}`);
|
||||
resolve(true);
|
||||
} else {
|
||||
console.log('\n❌ suppliers API接口返回错误');
|
||||
resolve(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('\n❌ 解析响应数据失败:', error.message);
|
||||
console.log('原始响应:', data);
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error) => {
|
||||
console.error('\n❌ 请求失败:', error.message);
|
||||
if (error.code === 'ECONNREFUSED') {
|
||||
console.log('提示: 请确保后端服务正在运行 (npm start)');
|
||||
}
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
console.error('\n❌ 请求超时');
|
||||
req.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// 执行测试
|
||||
testSuppliersAPI().then(success => {
|
||||
console.log(`\n测试结果: ${success ? '成功' : '失败'}`);
|
||||
process.exit(success ? 0 : 1);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
104
scripts/database/update_suppliers_table.js
Normal file
104
scripts/database/update_suppliers_table.js
Normal file
@@ -0,0 +1,104 @@
|
||||
const mysql = require('../../backend/node_modules/mysql2/promise');
|
||||
|
||||
async function updateSuppliersTable() {
|
||||
const config = {
|
||||
host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
|
||||
port: 20784,
|
||||
user: 'jiebanke',
|
||||
password: 'aiot741$12346',
|
||||
database: 'niumall'
|
||||
};
|
||||
|
||||
try {
|
||||
const connection = await mysql.createConnection(config);
|
||||
console.log('正在更新suppliers表结构...');
|
||||
|
||||
// 需要添加的字段
|
||||
const fieldsToAdd = [
|
||||
{
|
||||
name: 'bank_account',
|
||||
definition: 'varchar(50) DEFAULT NULL COMMENT \'银行账号\'',
|
||||
after: 'phone'
|
||||
},
|
||||
{
|
||||
name: 'bank_name',
|
||||
definition: 'varchar(100) DEFAULT NULL COMMENT \'开户银行\'',
|
||||
after: 'bank_account'
|
||||
},
|
||||
{
|
||||
name: 'tax_number',
|
||||
definition: 'varchar(30) DEFAULT NULL COMMENT \'税务登记号\'',
|
||||
after: 'bank_name'
|
||||
},
|
||||
{
|
||||
name: 'notes',
|
||||
definition: 'text DEFAULT NULL COMMENT \'备注信息\'',
|
||||
after: 'tax_number'
|
||||
}
|
||||
];
|
||||
|
||||
// 逐个添加字段
|
||||
for (const field of fieldsToAdd) {
|
||||
try {
|
||||
const sql = `ALTER TABLE suppliers ADD COLUMN ${field.name} ${field.definition} AFTER ${field.after}`;
|
||||
console.log(`添加字段 ${field.name}...`);
|
||||
await connection.execute(sql);
|
||||
console.log(`✅ 字段 ${field.name} 添加成功`);
|
||||
} catch (error) {
|
||||
if (error.code === 'ER_DUP_FIELDNAME') {
|
||||
console.log(`⚠️ 字段 ${field.name} 已存在,跳过`);
|
||||
} else {
|
||||
console.error(`❌ 添加字段 ${field.name} 失败:`, error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 验证字段是否添加成功
|
||||
console.log('\n验证表结构更新...');
|
||||
const [columns] = await connection.execute(`
|
||||
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'suppliers'
|
||||
AND COLUMN_NAME IN ('bank_account', 'bank_name', 'tax_number', 'notes')
|
||||
ORDER BY ORDINAL_POSITION
|
||||
`);
|
||||
|
||||
console.log('\n新添加的字段:');
|
||||
console.table(columns.map(col => ({
|
||||
字段名: col.COLUMN_NAME,
|
||||
数据类型: col.DATA_TYPE,
|
||||
允许空值: col.IS_NULLABLE,
|
||||
默认值: col.COLUMN_DEFAULT,
|
||||
注释: col.COLUMN_COMMENT
|
||||
})));
|
||||
|
||||
// 检查总字段数
|
||||
const [allColumns] = await connection.execute(`
|
||||
SELECT COUNT(*) as count
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = 'niumall'
|
||||
AND TABLE_NAME = 'suppliers'
|
||||
`);
|
||||
|
||||
console.log(`\nsuppliers表总字段数: ${allColumns[0].count}`);
|
||||
|
||||
await connection.end();
|
||||
console.log('\n✅ suppliers表结构更新完成!');
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 更新表结构失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行更新
|
||||
updateSuppliersTable().then(() => {
|
||||
console.log('表结构更新成功');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('脚本执行失败:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user