Files
ai-showcase-platform/scripts/insert-real-test-data.js
2025-09-09 18:18:02 +08:00

181 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const mysql = require('mysql2/promise');
async function insertTestData() {
console.log('📊 在資料庫中插入真實測試數據...\n');
let connection;
try {
// 連接資料庫
connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'ai_showcase_platform'
});
console.log('✅ 資料庫連接成功');
// 1. 獲取現有的應用和用戶
const [apps] = await connection.execute('SELECT id FROM apps WHERE is_active = TRUE LIMIT 3');
const [users] = await connection.execute('SELECT id FROM users WHERE status = "active" LIMIT 10');
if (apps.length === 0) {
console.log('❌ 沒有找到現有應用,無法創建測試數據');
return;
}
console.log(`📱 找到 ${apps.length} 個應用`);
console.log(`👥 找到 ${users.length} 個用戶`);
const targetAppId = apps[0].id; // 使用第一個應用作為目標
console.log(`🎯 目標應用 ID: ${targetAppId}`);
// 2. 清空現有的測試數據(如果有的話)
console.log('\n🧹 清空現有測試數據...');
await connection.execute('DELETE FROM user_views WHERE app_id = ?', [targetAppId]);
await connection.execute('DELETE FROM user_likes WHERE app_id = ?', [targetAppId]);
await connection.execute('DELETE FROM user_ratings WHERE app_id = ?', [targetAppId]);
console.log('✅ 現有測試數據已清空');
// 3. 插入用戶瀏覽記錄
console.log('\n👀 插入用戶瀏覽記錄...');
const views = [];
for (let i = 0; i < 25; i++) {
const userId = users[Math.floor(Math.random() * users.length)].id;
const viewedAt = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000); // 過去30天內
const ipAddress = `192.168.1.${Math.floor(Math.random() * 255)}`;
const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
views.push([targetAppId, userId, viewedAt, ipAddress, userAgent]);
}
for (const view of views) {
await connection.execute(`
INSERT INTO user_views (id, app_id, user_id, viewed_at, ip_address, user_agent)
VALUES (UUID(), ?, ?, ?, ?, ?)
`, view);
}
console.log(`✅ 插入了 ${views.length} 個瀏覽記錄`);
// 4. 插入用戶按讚記錄
console.log('\n❤ 插入用戶按讚記錄...');
const likes = [];
for (let i = 0; i < 8; i++) {
const userId = users[Math.floor(Math.random() * users.length)].id;
const likedAt = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000);
likes.push([targetAppId, userId, likedAt]);
}
for (const like of likes) {
await connection.execute(`
INSERT INTO user_likes (id, app_id, user_id, liked_at)
VALUES (UUID(), ?, ?, ?)
`, like);
}
console.log(`✅ 插入了 ${likes.length} 個按讚記錄`);
// 5. 插入用戶評分記錄
console.log('\n⭐ 插入用戶評分記錄...');
const ratings = [
{ rating: 5, review: '這個應用非常實用,界面設計得很棒!' },
{ rating: 4, review: '功能強大,處理速度很快,推薦使用。' },
{ rating: 5, review: '非常好用的工具,節省了很多時間。' },
{ rating: 3, review: '還不錯,但還有改進空間。' },
{ rating: 4, review: '界面簡潔,操作簡單,很滿意。' },
{ rating: 5, review: '功能齊全,使用體驗很好。' },
{ rating: 4, review: '整體不錯,希望能增加更多功能。' },
{ rating: 5, review: '非常推薦,已經推薦給同事了。' },
{ rating: 3, review: '還可以,但界面可以再優化。' },
{ rating: 4, review: '實用性很高,值得使用。' }
];
for (let i = 0; i < ratings.length; i++) {
const userId = users[Math.floor(Math.random() * users.length)].id;
const ratedAt = new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000);
await connection.execute(`
INSERT INTO user_ratings (id, app_id, user_id, rating, rated_at)
VALUES (UUID(), ?, ?, ?, ?)
`, [targetAppId, userId, ratings[i].rating, ratedAt]);
}
console.log(`✅ 插入了 ${ratings.length} 個評分記錄`);
// 6. 更新應用的統計數據
console.log('\n📈 更新應用統計數據...');
const [viewCount] = await connection.execute(
'SELECT COUNT(*) as count FROM user_views WHERE app_id = ?',
[targetAppId]
);
const [likeCount] = await connection.execute(
'SELECT COUNT(*) as count FROM user_likes WHERE app_id = ?',
[targetAppId]
);
await connection.execute(`
UPDATE apps
SET views_count = ?, likes_count = ?, updated_at = NOW()
WHERE id = ?
`, [viewCount[0].count, likeCount[0].count, targetAppId]);
console.log(` - 應用 ${targetAppId}: ${viewCount[0].count} 瀏覽, ${likeCount[0].count}`);
// 7. 顯示最終統計
console.log('\n📊 數據插入完成!最終統計:');
const [appStats] = await connection.execute(`
SELECT
views_count,
likes_count
FROM apps
WHERE id = ?
`, [targetAppId]);
const [ratingStats] = await connection.execute(`
SELECT
COUNT(*) as total_ratings,
AVG(rating) as avg_rating
FROM user_ratings
WHERE app_id = ?
`, [targetAppId]);
const [viewStats] = await connection.execute(`
SELECT COUNT(*) as total_views FROM user_views WHERE app_id = ?
`, [targetAppId]);
const [likeStats] = await connection.execute(`
SELECT COUNT(*) as total_likes FROM user_likes WHERE app_id = ?
`, [targetAppId]);
console.log(` - 應用瀏覽數: ${appStats[0].views_count}`);
console.log(` - 應用讚數: ${appStats[0].likes_count}`);
console.log(` - 總瀏覽數: ${viewStats[0].total_views}`);
console.log(` - 總讚數: ${likeStats[0].total_likes}`);
console.log(` - 評分總數: ${ratingStats[0].total_ratings}`);
console.log(` - 平均評分: ${ratingStats[0].avg_rating.toFixed(1)}`);
console.log('\n🎉 真實測試數據插入完成!');
console.log('\n💡 現在您可以重新載入應用管理頁面查看真實的資料庫數據');
} catch (error) {
console.error('❌ 插入測試數據時發生錯誤:', error);
if (error.code === 'ECONNREFUSED') {
console.log('\n💡 請確保 MySQL 服務正在運行,並且連接參數正確');
console.log(' - Host: localhost');
console.log(' - User: root');
console.log(' - Password: 123456');
console.log(' - Database: ai_showcase_platform');
}
} finally {
if (connection) {
await connection.end();
console.log('\n🔌 資料庫連接已關閉');
}
}
}
insertTestData();