import { Injectable } from '@nestjs/common';
import { NotificationService } from './notification.service';
import { DatabaseService } from '../../../infrastructure/database/database.service';
@Injectable()
export class DomainNotificationHandlerService {
constructor(
private readonly notifications:NotificationService,
private readonly database:DatabaseService,
) {}
async exportCompleted(input:{
eventId:string;
organizationId:string;
locationId?:string;
exportJobId:string;
requestedByUserId:string;
}) {
return this.notifications.create({
organizationId:input.organizationId,
userId:input.requestedByUserId,
locationId:input.locationId,
notificationType:'export_ready',
titleKey:'notification.exportReady.title',
bodyKey:'notification.exportReady.body',
severity:'info',
relatedEntityType:'ExportJob',
relatedEntityId:input.exportJobId,
deduplicationKey:`${input.eventId}:${input.requestedByUserId}:export_ready`,
});
}
async safetyFailed(input:{
eventId:string;
organizationId:string;
locationId:string;
safetyCheckId:string;
}) {
const recipients=await this.database.query<{user_id:string}>(
`select distinct m.user_account_id as user_id
from memberships m
join membership_roles mr on mr.membership_id=m.id
join roles r on r.id=mr.role_id
join role_permissions rp on rp.role_id=r.id
join permissions p on p.id=rp.permission_id
where m.organization_id=$1 and m.status='active'
and (mr.location_id is null or mr.location_id=$2)
and p.permission_key='safety.corrective.manage'`,
[input.organizationId,input.locationId],
);
for(const recipient of recipients) {
await this.notifications.create({
organizationId:input.organizationId,
userId:recipient.user_id,
locationId:input.locationId,
notificationType:'safety_failed',
titleKey:'notification.safetyFailed.title',
bodyKey:'notification.safetyFailed.body',
severity:'critical',
relatedEntityType:'SafetyCheck',
relatedEntityId:input.safetyCheckId,
deduplicationKey:`${input.eventId}:${recipient.user_id}:safety_failed`,
});
}
return {recipients:recipients.length};
}
}
