Files
CRM_Montzar/apps/api/src/attendance/attendance.service.ts
T

196 lines
6.1 KiB
TypeScript
Raw Normal View History

import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import type { Actor } from '../common/record-scope';
import { PrismaService } from '../prisma/prisma.service';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
import {
loggedInAfterCutoff,
tehranClock,
tehranCutoff,
type AttendanceKind,
} from './attendance-time';
export const WORKDAY_ENDED_MESSAGE =
'ساعت کاری امروز تمام شده است. برای ادامه دوباره وارد شوید.';
type RecordInput = {
organizationId: string;
userId: string;
role: string;
kind: AttendanceKind;
at: Date;
afterHours: boolean;
sessionStartedAt: Date | null;
};
@Injectable()
export class AttendanceService {
private readonly logger = new Logger(AttendanceService.name);
constructor(
private readonly prisma: PrismaService,
private readonly sms: SmsGatewayService,
) {}
async recordLogin(organizationId: string, userId: string, role: string, at = new Date()) {
if (role === 'owner') {
await this.write({
organizationId,
userId,
role,
kind: 'login',
at,
afterHours: false,
sessionStartedAt: at,
});
return;
}
const membership = await this.prisma.membership.findFirst({
where: { organizationId, userId, isActive: true },
select: { logoutTime: true },
});
const afterHours = loggedInAfterCutoff(at, membership?.logoutTime);
await this.write({
organizationId,
userId,
role,
kind: 'login',
at,
afterHours,
sessionStartedAt: at,
});
}
async recordLogout(actor: Actor) {
if (actor.viewAsReadOnly) return { ok: true };
const at = new Date();
await this.write({
organizationId: actor.organizationId,
userId: actor.userId,
role: actor.role,
kind: 'logout',
at,
afterHours: false,
sessionStartedAt: actor.sessionStartedAt ?? at,
});
return { ok: true };
}
/** اگر نشست قبل از ساعت خروج امروز شروع شده و آن ساعت گذشته، یک بار خروج اجباری ثبت و رد می‌شود. */
async assertSession(actor: Actor) {
if (actor.viewAsReadOnly || actor.role === 'owner' || !actor.sessionStartedAt) return;
const membership = await this.prisma.membership.findFirst({
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
select: { logoutTime: true, role: true },
});
const logoutTime = membership?.logoutTime;
if (!logoutTime || membership?.role === 'owner') return;
const now = new Date();
const cutoff = tehranCutoff(now, logoutTime);
if (!cutoff || now.getTime() < cutoff.getTime()) return;
if (actor.sessionStartedAt.getTime() >= cutoff.getTime()) return;
await this.write({
organizationId: actor.organizationId,
userId: actor.userId,
role: actor.role,
kind: 'forced_logout',
at: now,
afterHours: false,
sessionStartedAt: actor.sessionStartedAt,
});
throw new UnauthorizedException(WORKDAY_ENDED_MESSAGE);
}
async list(
organizationId: string,
opts: { q?: string; userId?: string; page?: number; limit?: number },
) {
const page = opts.page ?? 1;
const limit = opts.limit ?? 20;
const q = opts.q?.trim();
const where: Prisma.AttendanceEventWhereInput = {
organizationId,
...(opts.userId ? { userId: opts.userId } : {}),
...(q
? { user: { fullName: { contains: q, mode: 'insensitive' } } }
: {}),
};
const [rows, total] = await this.prisma.$transaction([
this.prisma.attendanceEvent.findMany({
where,
include: { user: { select: { fullName: true } } },
orderBy: { at: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
this.prisma.attendanceEvent.count({ where }),
]);
return {
items: rows.map((row) => ({
id: row.id,
userId: row.userId,
fullName: row.user.fullName,
kind: row.kind as AttendanceKind,
at: row.at.toISOString(),
afterHours: row.afterHours,
})),
total,
page,
limit,
};
}
private async write(input: RecordInput) {
try {
await this.prisma.attendanceEvent.create({
data: {
organizationId: input.organizationId,
userId: input.userId,
kind: input.kind,
at: input.at,
afterHours: input.afterHours,
sessionStartedAt: input.sessionStartedAt,
},
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
return;
}
throw e;
}
if (input.role === 'owner') return;
void this.notifyOwner(input).catch((err) => {
this.logger.warn(`پیامک ورود و خروج ناموفق بود: ${err instanceof Error ? err.message : err}`);
});
}
private async notifyOwner(input: RecordInput) {
const owner = await this.prisma.membership.findFirst({
where: { organizationId: input.organizationId, role: 'owner', isActive: true },
select: { userId: true, user: { select: { mobile: true } } },
});
if (!owner?.user.mobile || owner.userId === input.userId) return;
const person = await this.prisma.user.findUnique({
where: { id: input.userId },
select: { fullName: true },
});
const name = person?.fullName?.trim() || 'کارمند';
const clock = tehranClock(input.at);
const text =
input.kind === 'login'
? input.afterHours
? `${name} بعد از ساعت خروج دوباره وارد منتکت شد. ساعت ${clock}`
: `${name} وارد منتکت شد. ساعت ${clock}`
: input.kind === 'forced_logout'
? `${name} در ساعت تعیین‌شده از منتکت خارج شد. ساعت ${clock}`
: `${name} از منتکت خارج شد. ساعت ${clock}`;
await this.sms.send({
organizationId: input.organizationId,
phone: owner.user.mobile,
text,
source: 'attendance',
});
}
}