|
| 1 | +import { Injectable, Inject, OnModuleInit } from "@nestjs/common"; |
| 2 | +import { Db, ObjectId } from "mongodb"; |
| 3 | +import { Collections } from "@src/modules/common/enum/database.collection.enum"; |
| 4 | +import { LimitArea } from "@src/modules/common/models/plan.model"; |
| 5 | +import { ConfigService } from "@nestjs/config"; |
| 6 | + |
| 7 | +@Injectable() |
| 8 | +export class AddCommunityPlanToTeamsMigration implements OnModuleInit { |
| 9 | + private hasRun = false; |
| 10 | + |
| 11 | + constructor( |
| 12 | + @Inject("DATABASE_CONNECTION") private readonly db: Db, |
| 13 | + private readonly configService: ConfigService, |
| 14 | + ) {} |
| 15 | + |
| 16 | + async onModuleInit(): Promise<void> { |
| 17 | + if (this.hasRun) return; |
| 18 | + |
| 19 | + try { |
| 20 | + console.log("Running AddCommunityPlanToTeamsMigration..."); |
| 21 | + |
| 22 | + const teamCollection = this.db.collection(Collections.TEAM); |
| 23 | + const planCollection = this.db.collection(Collections.PLAN); |
| 24 | + |
| 25 | + // Get the default hub plan name from config |
| 26 | + const defaultHubPlan = |
| 27 | + this.configService.get<string>("app.defaultHubPlan"); |
| 28 | + // Fetch the plan from plan collection |
| 29 | + const planDoc = await planCollection.findOne({ name: defaultHubPlan }); |
| 30 | + if (!planDoc) { |
| 31 | + console.warn( |
| 32 | + `Plan '${defaultHubPlan}' not found in plan collection. Skipping team updates.`, |
| 33 | + ); |
| 34 | + return; |
| 35 | + } |
| 36 | + const { _id, ...planData } = planDoc; |
| 37 | + |
| 38 | + // Update teams that don't have a plan or where plan.id is missing |
| 39 | + const query = { |
| 40 | + $or: [ |
| 41 | + { plan: { $exists: false } }, |
| 42 | + { plan: null }, |
| 43 | + { "plan.id": { $exists: false } }, |
| 44 | + ], |
| 45 | + }; |
| 46 | + |
| 47 | + const update = { |
| 48 | + $set: { |
| 49 | + plan: { |
| 50 | + id: _id, |
| 51 | + ...planData, |
| 52 | + }, |
| 53 | + }, |
| 54 | + }; |
| 55 | + |
| 56 | + const result = await teamCollection.updateMany(query, update); |
| 57 | + console.log( |
| 58 | + `Updated ${result.modifiedCount} team(s) with the Community plan.`, |
| 59 | + ); |
| 60 | + |
| 61 | + this.hasRun = true; |
| 62 | + } catch (error) { |
| 63 | + console.error("Error during AddCommunityPlanToTeamsMigration:", error); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments