55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { TenantDatabaseService } from '../tenant/tenant-database.service';
|
|
import { ActivityLog } from '../models/activity-log.model';
|
|
|
|
export interface ActivityLogInput {
|
|
action: string;
|
|
subjectType: string;
|
|
subjectId: string;
|
|
description?: string;
|
|
properties?: Record<string, any>;
|
|
causerId?: string | null;
|
|
}
|
|
|
|
@Injectable()
|
|
export class ActivityLogService {
|
|
constructor(private tenantDbService: TenantDatabaseService) {}
|
|
|
|
private async getKnex(tenantId: string) {
|
|
const resolved = await this.tenantDbService.resolveTenantId(tenantId);
|
|
return this.tenantDbService.getTenantKnexById(resolved);
|
|
}
|
|
|
|
async logActivity(tenantId: string, input: ActivityLogInput) {
|
|
const knex = await this.getKnex(tenantId);
|
|
return ActivityLog.query(knex).insert({
|
|
action: input.action,
|
|
subjectType: input.subjectType,
|
|
subjectId: input.subjectId,
|
|
description: input.description,
|
|
properties: input.properties ?? null,
|
|
causerId: input.causerId ?? null,
|
|
});
|
|
}
|
|
|
|
async listActivities(
|
|
tenantId: string,
|
|
filters: {
|
|
subjectType?: string;
|
|
subjectId?: string;
|
|
causerId?: string;
|
|
action?: string;
|
|
},
|
|
) {
|
|
const knex = await this.getKnex(tenantId);
|
|
return ActivityLog.query(knex)
|
|
.modify((qb) => {
|
|
if (filters.subjectType) qb.where('subjectType', filters.subjectType);
|
|
if (filters.subjectId) qb.where('subjectId', filters.subjectId);
|
|
if (filters.causerId) qb.where('causerId', filters.causerId);
|
|
if (filters.action) qb.where('action', filters.action);
|
|
})
|
|
.orderBy('createdAt', 'desc');
|
|
}
|
|
}
|