Files
api/src/audit/audit.service.ts
T

85 lines
2.0 KiB
TypeScript
Raw Normal View History

2026-07-23 10:25:32 +03:30
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
type AuditInput = {
action: string;
entityType: string;
entityId?: string;
tenantId?: string;
userId?: string;
before?: Prisma.InputJsonValue;
after?: Prisma.InputJsonValue;
meta?: Prisma.InputJsonValue;
};
@Injectable()
export class AuditService {
constructor(private readonly prisma: PrismaService) {}
log(input: AuditInput) {
return this.prisma.auditLog.create({
data: {
action: input.action,
entityType: input.entityType,
entityId: input.entityId,
tenantId: input.tenantId,
userId: input.userId,
before: input.before,
after: input.after,
meta: input.meta,
},
});
}
findAll(limit = 50) {
return this.prisma.auditLog
.findMany({
take: Math.min(limit, 200),
orderBy: { createdAt: 'desc' },
include: {
user: {
select: { id: true, firstName: true, lastName: true, mobile: true },
},
tenant: { select: { id: true, slug: true, nameFa: true } },
},
})
.then((rows) =>
rows.map((row) => ({
...row,
user: row.user
? {
...row.user,
name: `${row.user.firstName} ${row.user.lastName}`.trim(),
}
: null,
})),
);
2026-07-23 10:25:32 +03:30
}
async findOne(id: string) {
const row = await this.prisma.auditLog.findUnique({
where: { id },
include: {
user: {
select: { id: true, firstName: true, lastName: true, mobile: true },
},
2026-07-23 10:25:32 +03:30
tenant: { select: { id: true, slug: true, nameFa: true } },
},
});
if (!row) {
throw new NotFoundException('لاگ یافت نشد');
}
return {
...row,
user: row.user
? {
...row.user,
name: `${row.user.firstName} ${row.user.lastName}`.trim(),
}
: null,
};
2026-07-23 10:25:32 +03:30
}
}