2023-04-12 01:59:14 -07:00
|
|
|
import { Service } from 'typedi';
|
2024-01-05 04:06:24 -08:00
|
|
|
import { DataSource, In, Repository } from 'typeorm';
|
2023-04-12 01:59:14 -07:00
|
|
|
import type { RoleNames, RoleScopes } from '../entities/Role';
|
|
|
|
import { Role } from '../entities/Role';
|
2023-12-20 06:14:31 -08:00
|
|
|
import { User } from '../entities/User';
|
2023-04-12 01:59:14 -07:00
|
|
|
|
|
|
|
@Service()
|
|
|
|
export class RoleRepository extends Repository<Role> {
|
|
|
|
constructor(dataSource: DataSource) {
|
|
|
|
super(Role, dataSource.manager);
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:58:36 -07:00
|
|
|
async findRole(scope: RoleScopes, name: RoleNames) {
|
2023-04-12 01:59:14 -07:00
|
|
|
return this.findOne({ where: { scope, name } });
|
|
|
|
}
|
2023-12-19 08:02:52 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Counts the number of users in each role, e.g. `{ admin: 2, member: 6, owner: 1 }`
|
|
|
|
*/
|
|
|
|
async countUsersByRole() {
|
2023-12-20 06:14:31 -08:00
|
|
|
type Row = { role_name: string; count: number | string };
|
2023-12-19 08:02:52 -08:00
|
|
|
|
|
|
|
const rows: Row[] = await this.createQueryBuilder('role')
|
|
|
|
.select('role.name')
|
|
|
|
.addSelect('COUNT(user.id)', 'count')
|
2023-12-20 06:14:31 -08:00
|
|
|
.innerJoin(User, 'user', 'role.id = user.globalRoleId')
|
2023-12-19 08:02:52 -08:00
|
|
|
.groupBy('role.name')
|
|
|
|
.getRawMany();
|
|
|
|
|
|
|
|
return rows.reduce<Record<string, number>>((acc, item) => {
|
2023-12-20 06:14:31 -08:00
|
|
|
acc[item.role_name] = typeof item.count === 'number' ? item.count : parseInt(item.count, 10);
|
2023-12-19 08:02:52 -08:00
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
}
|
2024-01-05 04:06:24 -08:00
|
|
|
|
|
|
|
async getIdsInScopeWorkflowByNames(roleNames: RoleNames[]) {
|
|
|
|
return this.find({
|
|
|
|
select: ['id'],
|
|
|
|
where: { name: In(roleNames), scope: 'workflow' },
|
|
|
|
}).then((role) => role.map(({ id }) => id));
|
|
|
|
}
|
2023-04-12 01:59:14 -07:00
|
|
|
}
|