import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../../infrastructure/database/database.service';
@Injectable()
export class IdentityService {
constructor(private readonly database: DatabaseService) {}
async getMe(userId: string) {
const users = await this.database.query<{
id: string;
display_name: string | null;
email_normalized: string | null;
preferred_locale: string;
status: string;
}>(
`select id, display_name, email_normalized, preferred_locale, status
from user_accounts
where id = $1`,
[userId],
);
const user = users[0];
const memberships = await this.database.query<{
membership_id: string;
organization_id: string;
organization_name: string;
membership_status: string;
}>(
`select
m.id as membership_id,
m.organization_id,
o.name as organization_name,
m.status as membership_status
from memberships m
join organizations o on o.id = m.organization_id
where m.user_account_id = $1
and m.status = 'active'
and o.status = 'active'
order by o.name`,
[userId],
);
const locations = await this.database.query<{
id: string;
organization_id: string;
name: string;
timezone: string;
default_locale: string;
legal_entity_id: string | null;
version: number;
}>(
`select l.id, l.organization_id, l.name, l.timezone, l.default_locale,
l.legal_entity_id, l.version
from locations l
where l.status = 'active'
and exists (
select 1
from memberships m
where m.user_account_id = $1
and m.organization_id = l.organization_id
and m.status = 'active'
)
order by l.name`,
[userId],
);
const permissions = await this.database.query<{
organization_id: string;
location_id: string | null;
permission_key: string;
}>(
`select distinct
m.organization_id,
mr.location_id,
rp.permission_key
from memberships m
join membership_roles mr on mr.membership_id = m.id
join role_permissions rp on rp.role_id = mr.role_id
where m.user_account_id = $1
and m.status = 'active'`,
[userId],
);
return {
user,
memberships,
locations,
permissions,
entitlements: [],
locale: user?.preferred_locale ?? 'en-GB',
};
}
}
