import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../../../infrastructure/database/database.service';
@Injectable()
export class TeamReadModelService {
constructor(private readonly database: DatabaseService) {}
async list(organizationId: string, employeeId?: string) {
return this.database.query(
`select
e.id as employee_id,
e.first_name,
e.last_name,
coalesce(e.display_name, trim(e.first_name || ' ' || e.last_name)) as display_name,
e.status,
e.employee_number,
e.preferred_locale,
coalesce(
jsonb_agg(distinct jsonb_build_object(
'roleId', r.id,
'roleKey', r.role_key,
'roleName', r.display_name,
'locationId', mr.location_id
)) filter (where r.id is not null),
'[]'::jsonb
) as roles,
coalesce(
jsonb_agg(distinct jsonb_build_object(
'locationId', l.id,
'locationName', l.name
)) filter (where l.id is not null),
'[]'::jsonb
) as location_scopes
from employees e
left join memberships m
on m.employee_id = e.id
and m.organization_id = e.organization_id
and m.status <> 'revoked'
left join membership_roles mr on mr.membership_id = m.id
left join roles r on r.id = mr.role_id
left join membership_location_scopes mls on mls.membership_id = m.id
left join locations l on l.id = mls.location_id
where e.organization_id = $1
and ($2::uuid is null or e.id = $2)
group by e.id
order by lower(coalesce(e.display_name, e.last_name)), e.id`,
[organizationId, employeeId ?? null],
);
}
async get(organizationId: string, employeeId: string) {
const rows = await this.list(organizationId, employeeId);
return rows[0] ?? null;
}
}
