const mongoose = require('mongoose'); const connectDB = require('../config/db'); const Scene = require('../models/Scene'); const Tour = require('../models/Tour'); /** * Script migration Giai đoạn 3: * 1. Tạo các bản ghi Tour tương ứng cho mỗi "Cảnh gốc" (Dựa trên tourId cũ). * 2. Gán lại tourId của tất cả các cảnh con vào bản ghi Tour mới (Ref: Tour). * 3. Chuyển thông tin chia sẻ từ Scene gốc sang Tour làm nguồn dữ liệu chính. */ const migrateToTours = async () => { try { console.log('--- Bắt đầu quy trình migration sang cấu trúc Tour-centric ---'); await connectDB(); // Lấy danh sách tất cả các tourId hiện có (trước đây trỏ đến Scene ID) // Sử dụng distinct để lọc ra các nhóm Tour độc lập const oldTourIds = await Scene.distinct('tourId'); console.log(`Tìm thấy ${oldTourIds.length} nhóm cảnh cần chuyển đổi sang Tour.`); for (const oldId of oldTourIds) { if (!oldId) continue; // Tìm "Cảnh gốc" của tour này (Cảnh có ID trùng với tourId cũ) // Nếu không tìm thấy (do dữ liệu cũ lỗi), lấy cảnh đầu tiên trong nhóm làm gốc let rootScene = await Scene.findById(oldId).lean(); if (!rootScene) { rootScene = await Scene.findOne({ tourId: oldId }).lean(); } if (!rootScene) { console.warn(`[!] Không tìm thấy dữ liệu cảnh cho tourId cũ: ${oldId}. Bỏ qua.`); continue; } console.log(`Đang tạo Tour cho: ${rootScene.name || rootScene.title} (${rootScene._id})`); // 1. Khởi tạo Tour mới và sao chép thông tin chia sẻ từ Scene gốc const newTour = new Tour({ name: rootScene.name || rootScene.title || "Tour mới", description: rootScene.description || "", location: { lat: rootScene.gps?.lat || 0, lng: rootScene.gps?.lng || 0 }, createdBy: rootScene.createdBy, rootSceneId: rootScene._id, privacy: rootScene.privacy || 'private', shareToken: rootScene.shareToken, shareTokenExpires: rootScene.shareTokenExpires, sharedWith: rootScene.sharedWith || [], sharedEmails: rootScene.sharedEmails || [], scenes: [] // Sẽ được cập nhật danh sách ID cảnh con bên dưới }); // 2. Thu thập tất cả các cảnh con thuộc tour này const memberScenes = await Scene.find({ tourId: oldId }); newTour.scenes = memberScenes.map(s => s._id); await newTour.save(); // 3. Cập nhật tourId của tất cả cảnh trỏ về bản ghi Tour (ObjectId) mới tạo // Việc này chuyển đổi từ quan hệ Scene -> Scene sang Scene -> Tour await Scene.updateMany( { tourId: oldId }, { $set: { tourId: newTour._id } } ); console.log(` -> Thành công: Tour [${newTour._id}] đã nhận ${memberScenes.length} cảnh.`); } console.log('--- Hoàn tất migration sang cấu trúc Tour! ---'); mongoose.connection.close(); process.exit(0); } catch (error) { console.error('Lỗi Migration:', error.message); if (mongoose.connection) mongoose.connection.close(); process.exit(1); } }; migrateToTours();