76 lines
2.4 KiB
JavaScript
76 lines
2.4 KiB
JavaScript
/**
|
|
* Seed system roles per organisation and link OrganizationUserMap.customRole.
|
|
* Run: cd backend && node scripts/seed-org-roles.js
|
|
*/
|
|
const path = require('path');
|
|
|
|
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
|
|
const mongoose = require('mongoose');
|
|
const Organization = require(path.join(__dirname, '..', 'src', 'models', 'Organization'));
|
|
const OrganizationUserMap = require(path.join(__dirname, '..', 'src', 'models', 'OrganizationUserMap'));
|
|
const Role = require(path.join(__dirname, '..', 'src', 'models', 'Role'));
|
|
const {
|
|
SYSTEM_ROLE_KEYS,
|
|
SYSTEM_ROLE_PERMISSIONS,
|
|
SYSTEM_ROLE_LABELS,
|
|
} = require(path.join(__dirname, '..', 'src', 'config', 'systemRolePermissions'));
|
|
|
|
async function ensureSystemRolesForOrg(orgId) {
|
|
const rolesByKey = {};
|
|
for (const systemKey of SYSTEM_ROLE_KEYS) {
|
|
let role = await Role.findOne({ organization: orgId, systemKey, isSystem: true });
|
|
if (!role) {
|
|
role = await Role.create({
|
|
organization: orgId,
|
|
name: SYSTEM_ROLE_LABELS[systemKey] || systemKey,
|
|
description: `System role: ${systemKey}`,
|
|
systemKey,
|
|
isSystem: true,
|
|
permissions: SYSTEM_ROLE_PERMISSIONS[systemKey] || [],
|
|
});
|
|
console.log(` Created system role ${systemKey} for org ${orgId}`);
|
|
} else {
|
|
role.permissions = SYSTEM_ROLE_PERMISSIONS[systemKey] || [];
|
|
role.name = SYSTEM_ROLE_LABELS[systemKey] || systemKey;
|
|
await role.save();
|
|
}
|
|
rolesByKey[systemKey] = role;
|
|
}
|
|
return rolesByKey;
|
|
}
|
|
|
|
async function run() {
|
|
const uri = process.env.MONGODB_URI;
|
|
if (!uri) {
|
|
console.error('MONGODB_URI is not set');
|
|
process.exit(1);
|
|
}
|
|
await mongoose.connect(uri);
|
|
|
|
const orgs = await Organization.find({}).select('_id name').lean();
|
|
let mapsUpdated = 0;
|
|
|
|
for (const org of orgs) {
|
|
console.log(`Org: ${org.name} (${org._id})`);
|
|
const rolesByKey = await ensureSystemRolesForOrg(org._id);
|
|
|
|
const maps = await OrganizationUserMap.find({ organization: org._id });
|
|
for (const map of maps) {
|
|
const roleDoc = rolesByKey[map.role];
|
|
if (roleDoc && String(map.customRole || '') !== String(roleDoc._id)) {
|
|
map.customRole = roleDoc._id;
|
|
await map.save();
|
|
mapsUpdated += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(`Done. ${orgs.length} org(s), ${mapsUpdated} membership(s) linked to customRole.`);
|
|
await mongoose.disconnect();
|
|
}
|
|
|
|
run().catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|