-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathCourseFilterService.cs
More file actions
321 lines (272 loc) · 12.9 KB
/
CourseFilterService.cs
File metadata and controls
321 lines (272 loc) · 12.9 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using System.Linq;
using System.Threading.Tasks;
using HwProj.CoursesService.API.Models;
using HwProj.CoursesService.API.Repositories;
using HwProj.Models.CoursesService;
using HwProj.Models.CoursesService.DTO;
using HwProj.Models.CoursesService.ViewModels;
using HwProj.Models.Result;
using System.Collections.Generic;
using System;
namespace HwProj.CoursesService.API.Services
{
public enum ApplyFilterOperation
{
Intersect,
Union,
Subtract
}
public class CourseFilterService : ICourseFilterService
{
private const string GlobalFilterId = "";
private readonly ICourseFilterRepository _courseFilterRepository;
private readonly IGroupsService _groupsService;
public CourseFilterService(
ICourseFilterRepository courseFilterRepository, IGroupsService groupsService)
{
_courseFilterRepository = courseFilterRepository;
_groupsService = groupsService;
}
public async Task<Result<long>> CreateOrUpdateCourseFilter(CreateCourseFilterModel courseFilterModel)
{
var filter = CourseFilterUtils.CreateFilter(courseFilterModel);
var existingCourseFilter =
await _courseFilterRepository.GetAsync(courseFilterModel.Id, courseFilterModel.CourseId);
if (existingCourseFilter != null)
{
await UpdateAsync(existingCourseFilter.Id, filter);
return Result<long>.Success(existingCourseFilter.Id);
}
var filterId = await AddCourseFilter(filter, courseFilterModel.CourseId, courseFilterModel.Id);
if (filterId == -1)
{
return Result<long>.Failed();
}
return Result<long>.Success(filterId);
}
public async Task UpdateAsync(long courseFilterId, Filter filter)
{
var courseFilter = new CourseFilter
{
Id = courseFilterId,
Filter = filter
};
await _courseFilterRepository.UpdateAsync(courseFilterId, f =>
new CourseFilter
{
FilterJson = courseFilter.FilterJson
});
}
public async Task<CourseDTO[]> ApplyFiltersToCourses(string userId, CourseDTO[] courses)
{
var result = new List<CourseDTO>();
foreach (var course in courses)
{
result.Add(await ApplyFilter(course, userId));
}
return result.ToArray();
}
public async Task<CourseDTO> ApplyFilter(CourseDTO course, string userId)
{
var isMentor = course.MentorIds.Contains(userId);
var isCourseStudent = course.AcceptedStudents.Any(t => t.StudentId == userId);
// Получаем группы пользователя из course
var studentGroups = course.Groups
.Where(g => g.StudentsIds.Contains(userId))
.ToArray();
var groupIds = studentGroups.Select(g => g.Id.ToString()).ToArray();
var findFiltersFor = isMentor || !isCourseStudent
? new[] { userId, GlobalFilterId }
: course.MentorIds.Concat(new[] { userId, GlobalFilterId }).Concat(groupIds).ToArray();
var courseFilters =
(await _courseFilterRepository.GetAsync(findFiltersFor, course.Id))
.ToDictionary(x => x.Id, x => x.CourseFilter);
if (!isMentor)
{
var globalFilter = courseFilters.GetValueOrDefault(GlobalFilterId);
var globalCourse = globalFilter != null
? ApplyFilterInternal(course, course, globalFilter, ApplyFilterOperation.Subtract)
: course;
var studentCourse = studentGroups
.Select(g => courseFilters.GetValueOrDefault(g.Id.ToString()))
.Where(cf => cf != null)
.Aggregate(globalCourse, (current, groupCourseFilter) =>
ApplyFilterInternal(course, current, groupCourseFilter, ApplyFilterOperation.Union));
var mentorIds = course.MentorIds
.Where(u =>
// Фильтрация не настроена вообще
!courseFilters.TryGetValue(u, out var courseFilter) ||
// Не отфильтрованы студенты
!courseFilter.Filter.StudentIds.Any() ||
// Фильтр содержит студента
courseFilter.Filter.StudentIds.Contains(userId))
.ToArray();
studentCourse.MentorIds = mentorIds;
return studentCourse;
}
return courseFilters.TryGetValue(userId, out var userFilter)
? ApplyFilterInternal(course, course, userFilter, ApplyFilterOperation.Intersect)
: course;
}
public async Task<MentorToAssignedStudentsDTO[]> GetAssignedStudentsIds(long courseId, string[] mentorsIds)
{
var usersCourseFilters = await _courseFilterRepository.GetAsync(mentorsIds, courseId);
if (usersCourseFilters == null || usersCourseFilters.Count == 0)
return Array.Empty<MentorToAssignedStudentsDTO>();
var groupIds = usersCourseFilters
.SelectMany(filter => filter.CourseFilter.Filter.GroupIds ?? Enumerable.Empty<long>())
.Distinct()
.ToArray();
var groups = await _groupsService.GetGroupsAsync(groupIds);
var groupToStudentIds = groups
.ToDictionary(
g => g.Id,
g => g.GroupMates?.Select(gm => gm.StudentId).ToArray() ?? Array.Empty<string>()
);
var result = usersCourseFilters
.Select(u =>
{
var directStudents = u.CourseFilter.Filter.StudentIds ?? new List<string>() {};
var groupIdsForMentor = u.CourseFilter.Filter.GroupIds ?? Enumerable.Empty<long>();
var studentsFromGroups = groupIdsForMentor
.Where(gid => groupToStudentIds.ContainsKey(gid))
.SelectMany(gid => groupToStudentIds[gid])
.Distinct()
.ToList();
return new MentorToAssignedStudentsDTO
{
MentorId = u.Id,
SelectedStudentsIds = directStudents.Concat(studentsFromGroups).Distinct().ToList()
};
})
.ToArray();
return result;
}
private async Task<long> AddCourseFilter(Filter filter, long courseId, string userId)
{
var courseFilterId =
await _courseFilterRepository.AddAsync(new CourseFilter { Filter = filter }, userId, courseId);
return courseFilterId;
}
private CourseDTO ApplyFilterInternal(CourseDTO initialCourseDto, CourseDTO editingCourseDto,
CourseFilter? courseFilter, ApplyFilterOperation filterType)
{
var filter = courseFilter?.Filter;
if (filter == null)
return editingCourseDto;
var homeworks = filter.HomeworkIds.Count != 0
? filterType switch
{
ApplyFilterOperation.Intersect => editingCourseDto.Homeworks
.Where(hw => filter.HomeworkIds.Contains(hw.Id))
.ToArray(),
ApplyFilterOperation.Subtract => editingCourseDto.Homeworks
.Where(hw => !filter.HomeworkIds.Contains(hw.Id))
.ToArray(),
ApplyFilterOperation.Union => editingCourseDto.Homeworks
.Concat(initialCourseDto.Homeworks
.Where(hw => filter.HomeworkIds.Contains(hw.Id)))
.ToArray(),
_ => editingCourseDto.Homeworks
}
: editingCourseDto.Homeworks;
var groups = filter.GroupIds.Any()
? editingCourseDto.Groups.Where(g => filter.GroupIds.Contains(g.Id))
: editingCourseDto.Groups;
var filteredStudentIds = filter.GroupIds.Any()
? filter.StudentIds.Concat(groups.SelectMany(g => g.StudentsIds))
: filter.StudentIds.Any()
? filter.StudentIds
: editingCourseDto.AcceptedStudents.Select(st => st.StudentId);
var filteredGroups = filteredStudentIds.Any()
? editingCourseDto.Groups
.Select(gs =>
{
var groupStudentsIds = gs.StudentsIds.Intersect(filteredStudentIds).ToArray();
return groupStudentsIds.Any()
? new GroupViewModel
{
Id = gs.Id,
Name = gs.Name,
StudentsIds = groupStudentsIds
}
: null;
})
.Where(t => t != null)
.ToArray()
: editingCourseDto.Groups;
return new CourseDTO
{
Id = editingCourseDto.Id,
Name = editingCourseDto.Name,
GroupName = editingCourseDto.GroupName,
IsCompleted = editingCourseDto.IsCompleted,
IsOpen = editingCourseDto.IsOpen,
InviteCode = editingCourseDto.InviteCode,
Groups = filter.GroupIds.Any()
? filteredGroups
.Where(g => filter.GroupIds.Contains(g.Id) || g.Name == string.Empty)
.ToArray()
: filteredGroups,
MentorIds = filter.MentorIds.Any()
? editingCourseDto.MentorIds.Intersect(filter.MentorIds).ToArray()
: editingCourseDto.MentorIds,
CourseMates = editingCourseDto.CourseMates
.Where(mate => !mate.IsAccepted || filteredStudentIds.Contains(mate.StudentId))
.ToArray(),
Homeworks = homeworks
.Where(hw => hw.GroupId == null || groups.Any(g => g.Id == hw.GroupId))
.OrderBy(hw => hw.PublicationDate)
.ToArray()
};
}
public async Task UpdateGroupFilters(long courseId, long homeworkId, Group group)
{
var filterIds = group != null
? new[] { GlobalFilterId, group.Id.ToString() }
: new[] { GlobalFilterId };
var filters = await _courseFilterRepository.GetAsync(filterIds, courseId);
foreach (var filterId in filterIds)
{
var existingCourseFilter = filters.SingleOrDefault(f => f.Id == filterId)?.CourseFilter;
var newFilter = existingCourseFilter?.Filter
?? new Filter { GroupIds = new List<long>(), StudentIds = new List<string>(),
HomeworkIds = new List<long>(), MentorIds = new List<string>() };
newFilter.HomeworkIds.Add(homeworkId);
if (existingCourseFilter != null)
await UpdateAsync(existingCourseFilter.Id, newFilter);
else
await AddCourseFilter(newFilter, courseId, filterId);
}
}
public async Task AddToFilter(long courseId, string userId, Filter filter)
{
var existingCourseFilter = await _courseFilterRepository.GetAsync(userId, courseId);
if (existingCourseFilter?.Filter is null)
return;
var targetFilter = existingCourseFilter.Filter.FillEmptyFields();
filter.FillEmptyFields();
var hasChanges =
AddToFilterList(targetFilter.GroupIds, filter.GroupIds)
| AddToFilterList(targetFilter.StudentIds, filter.StudentIds)
| AddToFilterList(targetFilter.HomeworkIds, filter.HomeworkIds)
| AddToFilterList(targetFilter.MentorIds, filter.MentorIds);
if (hasChanges)
await UpdateAsync(existingCourseFilter.Id, targetFilter);
}
private static bool AddToFilterList<T>(List<T> target, IEnumerable<T> itemsToAdd)
{
if (!target.Any())
return false;
var hasChanges = false;
foreach (var item in itemsToAdd.Distinct())
{
if (target.Contains(item))
continue;
target.Add(item);
hasChanges = true;
}
return hasChanges;
}
}
}