| 119 | } |
| 120 | |
| 121 | export async function syncTeamProjects({ |
| 122 | organizationId, |
| 123 | teamProjects, |
| 124 | }: { |
| 125 | teamProjects: TeamProject[]; |
| 126 | organizationId: string; |
| 127 | }) { |
| 128 | // assumption: api teamProjects is the source of truth for migrated projects |
| 129 | // once migrated orgs become the source of truth for projects |
| 130 | // its important that migration be completed before this code is run |
| 131 | const existingRemoteProjects = await list({ |
| 132 | remoteId: { $in: teamProjects.map(p => p.id) }, |
| 133 | }); |
| 134 | |
| 135 | const existingRemoteProjectsRemoteIds = existingRemoteProjects.map(p => p.remoteId); |
| 136 | const remoteProjectsThatNeedToBeCreated = teamProjects.filter(p => !existingRemoteProjectsRemoteIds.includes(p.id)); |
| 137 | |
| 138 | // this will create a new project for any remote projects that don't exist in the current organization |
| 139 | await Promise.all( |
| 140 | remoteProjectsThatNeedToBeCreated.map(async prj => { |
| 141 | await create({ |
| 142 | remoteId: prj.id, |
| 143 | name: prj.name, |
| 144 | parentId: organizationId, |
| 145 | }); |
| 146 | }), |
| 147 | ); |
| 148 | |
| 149 | const remoteProjectsThatNeedToBeUpdated = await list({ |
| 150 | // Remote ID is in the list of remote projects |
| 151 | remoteId: { $in: teamProjects.map(p => p.id) }, |
| 152 | }); |
| 153 | |
| 154 | await Promise.all( |
| 155 | remoteProjectsThatNeedToBeUpdated.map(async prj => { |
| 156 | const remoteProject = teamProjects.find(p => p.id === prj.remoteId); |
| 157 | if (remoteProject && remoteProject.name !== prj.name) { |
| 158 | await update(prj, { |
| 159 | name: remoteProject.name, |
| 160 | }); |
| 161 | } |
| 162 | }), |
| 163 | ); |
| 164 | |
| 165 | // Turn remote projects from the current organization that are not in the list of remote projects into local projects. |
| 166 | const removedRemoteProjects = await list({ |
| 167 | // filter by this organization so no legacy data can be accidentally removed, because legacy had null parentId |
| 168 | parentId: organizationId, |
| 169 | // Remote ID is not in the list of remote projects. |
| 170 | // add `$ne: null` condition because if remoteId is already null, we dont need to remove it again. |
| 171 | // nedb use append-only format, all updates and deletes actually result in lines added |
| 172 | remoteId: { |
| 173 | $nin: teamProjects.map(p => p.id), |
| 174 | $ne: null, |
| 175 | }, |
| 176 | }); |
| 177 | |
| 178 | await Promise.all( |