55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
import type { GpsUpdateDto } from "../../dtos/index.js";
|
|
import type { NotificationCacheRepository } from "../../repositories/notification-cache.repository.js";
|
|
import {
|
|
NotificationType,
|
|
notificationPayloads,
|
|
positionTriggers,
|
|
} from "../../../data/mocks/notification-types.mock.js";
|
|
import { users } from "../../../data/mocks/users.mock.js";
|
|
|
|
export interface EvaluatedNotification {
|
|
userId: number;
|
|
type: NotificationType;
|
|
title: string;
|
|
body: string;
|
|
}
|
|
|
|
export class EvaluateNotificationUseCase {
|
|
constructor(private readonly cache: NotificationCacheRepository) {}
|
|
|
|
async execute(gps: GpsUpdateDto): Promise<EvaluatedNotification[]> {
|
|
const targets = users.filter((u) => u.routeId === gps.routeId);
|
|
if (targets.length === 0) return [];
|
|
|
|
const type = this.resolveType(gps);
|
|
if (!type) return [];
|
|
|
|
const payload = notificationPayloads[type];
|
|
const result: EvaluatedNotification[] = [];
|
|
|
|
for (const user of targets) {
|
|
const key = `${user.id}-${gps.routeId}-${type}`;
|
|
if (await this.cache.wasSent(key)) continue;
|
|
|
|
await this.cache.markSent(key);
|
|
result.push({
|
|
userId: user.id,
|
|
type,
|
|
title: payload.title,
|
|
body: payload.body,
|
|
});
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private resolveType(gps: GpsUpdateDto): NotificationType | null {
|
|
if (gps.status === "FALLA") {
|
|
return NotificationType.MECHANICAL_FAILURE;
|
|
}
|
|
if (gps.positionId !== undefined && positionTriggers[gps.positionId]) {
|
|
return positionTriggers[gps.positionId] ?? null;
|
|
}
|
|
return null;
|
|
}
|
|
} |