-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathrisks.service.ts
More file actions
256 lines (232 loc) · 6.66 KB
/
risks.service.ts
File metadata and controls
256 lines (232 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { BadRequestException, Injectable, NotFoundException, Logger } from '@nestjs/common';
import { db, Prisma } from '@trycompai/db';
import { CreateRiskDto } from './dto/create-risk.dto';
import { GetRisksQueryDto } from './dto/get-risks-query.dto';
import { UpdateRiskDto } from './dto/update-risk.dto';
export interface PaginatedRisksResult {
data: Prisma.RiskGetPayload<{
include: {
assignee: {
include: {
user: {
select: { id: true; name: true; email: true; image: true };
};
};
};
};
}>[];
totalCount: number;
page: number;
pageCount: number;
}
@Injectable()
export class RisksService {
private readonly logger = new Logger(RisksService.name);
private async validateAssigneeNotPlatformAdmin(assigneeId: string, organizationId: string) {
const member = await db.member.findFirst({
where: { id: assigneeId, organizationId },
include: { user: { select: { isPlatformAdmin: true } } },
});
if (member?.user.isPlatformAdmin) {
throw new BadRequestException('Cannot assign a platform admin as assignee');
}
}
async findAllByOrganization(
organizationId: string,
assignmentFilter: Prisma.RiskWhereInput = {},
query: GetRisksQueryDto = {},
): Promise<PaginatedRisksResult> {
const {
title,
page = 1,
perPage = 50,
sort = 'createdAt',
sortDirection = 'desc',
status,
category,
department,
assigneeId,
} = query;
try {
const where: Prisma.RiskWhereInput = {
organizationId,
...assignmentFilter,
...(title && {
title: { contains: title, mode: Prisma.QueryMode.insensitive },
}),
...(status && { status }),
...(category && { category }),
...(department && { department }),
...(assigneeId && { assigneeId }),
};
const [risks, totalCount] = await Promise.all([
db.risk.findMany({
where,
skip: (page - 1) * perPage,
take: perPage,
orderBy: { [sort]: sortDirection },
include: {
assignee: {
include: {
user: {
select: {
id: true,
name: true,
email: true,
image: true,
},
},
},
},
},
}),
db.risk.count({ where }),
]);
const pageCount = Math.ceil(totalCount / perPage);
this.logger.log(
`Retrieved ${risks.length} risks (page ${page}/${pageCount}) for organization ${organizationId}`,
);
return { data: risks, totalCount, page, pageCount };
} catch (error) {
this.logger.error(
`Failed to retrieve risks for organization ${organizationId}:`,
error,
);
throw error;
}
}
async findById(id: string, organizationId: string) {
try {
const risk = await db.risk.findFirst({
where: {
id,
organizationId,
},
include: {
assignee: {
include: {
user: true,
},
},
},
});
if (!risk) {
throw new NotFoundException(
`Risk with ID ${id} not found in organization ${organizationId}`,
);
}
this.logger.log(`Retrieved risk: ${risk.title} (${id})`);
return risk;
} catch (error) {
if (error instanceof NotFoundException) {
throw error;
}
this.logger.error(`Failed to retrieve risk ${id}:`, error);
throw error;
}
}
async create(organizationId: string, createRiskDto: CreateRiskDto) {
try {
if (createRiskDto.assigneeId) {
await this.validateAssigneeNotPlatformAdmin(createRiskDto.assigneeId, organizationId);
}
const risk = await db.risk.create({
data: {
...createRiskDto,
organizationId,
},
});
this.logger.log(
`Created new risk: ${risk.title} (${risk.id}) for organization ${organizationId}`,
);
return risk;
} catch (error) {
this.logger.error(
`Failed to create risk for organization ${organizationId}:`,
error,
);
throw error;
}
}
async updateById(
id: string,
organizationId: string,
updateRiskDto: UpdateRiskDto,
) {
try {
// First check if the risk exists in the organization
await this.findById(id, organizationId);
if (updateRiskDto.assigneeId) {
await this.validateAssigneeNotPlatformAdmin(updateRiskDto.assigneeId, organizationId);
}
const updatedRisk = await db.risk.update({
where: { id },
data: updateRiskDto,
});
this.logger.log(`Updated risk: ${updatedRisk.title} (${id})`);
return updatedRisk;
} catch (error) {
if (error instanceof NotFoundException) {
throw error;
}
this.logger.error(`Failed to update risk ${id}:`, error);
throw error;
}
}
async deleteById(id: string, organizationId: string) {
try {
// First check if the risk exists in the organization
const existingRisk = await this.findById(id, organizationId);
await db.risk.delete({
where: { id },
});
this.logger.log(`Deleted risk: ${existingRisk.title} (${id})`);
return {
message: 'Risk deleted successfully',
deletedRisk: {
id: existingRisk.id,
title: existingRisk.title,
},
};
} catch (error) {
if (error instanceof NotFoundException) {
throw error;
}
this.logger.error(`Failed to delete risk ${id}:`, error);
throw error;
}
}
async getStatsByAssignee(organizationId: string) {
const members = await db.member.findMany({
where: { organizationId },
select: {
id: true,
risks: {
where: { organizationId },
select: { status: true },
},
user: {
select: { name: true, image: true, email: true },
},
},
});
return members
.filter((m) => m.risks.length > 0)
.map((m) => ({
id: m.id,
user: m.user,
totalRisks: m.risks.length,
openRisks: m.risks.filter((r) => r.status === 'open').length,
pendingRisks: m.risks.filter((r) => r.status === 'pending').length,
closedRisks: m.risks.filter((r) => r.status === 'closed').length,
archivedRisks: m.risks.filter((r) => r.status === 'archived').length,
}));
}
async getStatsByDepartment(organizationId: string) {
return db.risk.groupBy({
by: ['department'],
where: { organizationId },
_count: true,
});
}
}