-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathCoursesController.cs
More file actions
317 lines (274 loc) · 11.9 KB
/
CoursesController.cs
File metadata and controls
317 lines (274 loc) · 11.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
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using HwProj.APIGateway.API.Models;
using HwProj.AuthService.Client;
using HwProj.CoursesService.Client;
using HwProj.Models.AuthService.DTO;
using HwProj.Models.AuthService.ViewModels;
using HwProj.Models.CoursesService.DTO;
using HwProj.Models.CoursesService.ViewModels;
using HwProj.Models.Roles;
using IStudentsInfo;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace HwProj.APIGateway.API.Controllers;
[Route("api/[controller]")]
[ApiController]
public class CoursesController : AggregationController
{
private readonly ICoursesServiceClient _coursesClient;
private readonly IMapper _mapper;
private readonly IStudentsInformationProvider _studentsInfo;
public CoursesController(
ICoursesServiceClient coursesClient,
IAuthServiceClient authServiceClient,
IMapper mapper,
IStudentsInformationProvider studentsInfo) : base(authServiceClient)
{
_coursesClient = coursesClient;
_mapper = mapper;
_studentsInfo = studentsInfo;
}
[HttpGet]
[Authorize]
public async Task<CoursePreviewView[]> GetAllCourses()
{
var courses = await _coursesClient.GetAllCourses();
var result = await GetCoursePreviews(courses);
return result;
}
[HttpGet("getAllData/{courseId}")]
[ProducesResponseType(typeof(CourseAllData), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetAllCourseData(long courseId)
{
var courseResult = await _coursesClient.GetCourseDataRaw(courseId);
if (!courseResult.Succeeded)
return BadRequest(courseResult.Errors[0]);
var assignedStudents = await _coursesClient.GetMentorsToAssignedStudents(courseId);
var result = new CourseAllData
{
Course = await ToCourseViewModel(courseResult.Value),
AssignedStudents = assignedStudents
};
return Ok(result);
}
[HttpGet("{courseId}")]
[ProducesResponseType(typeof(CourseViewModel), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetCourseData(long courseId)
{
var course = await _coursesClient.GetCourseView(courseId);
if (course == null) return NotFound();
var result = await ToCourseViewModel(course);
return Ok(result);
}
[HttpDelete("{courseId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> DeleteCourse(long courseId)
{
await _coursesClient.DeleteCourse(courseId);
return Ok();
}
[HttpGet("getGroups")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(List<GroupModel>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetGroups(string programName)
{
var groups = await _studentsInfo.GetGroups(programName);
return Ok(groups);
}
[HttpGet("getProgramNames")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(List<ProgramModel>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetProgramNames()
{
return Ok(await _studentsInfo.GetProgramNames());
}
[HttpPost("create")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)]
public async Task<IActionResult> CreateCourse(CreateCourseViewModel model)
{
if (model.GroupNames.Any() && model.FetchStudents)
{
var studentCandidates = new List<StudentModel>();
foreach (var groupName in model.GroupNames)
{
var students = _studentsInfo.GetStudentInformation(groupName);
studentCandidates.AddRange(students);
}
var registrationModels = studentCandidates
.Where(student => !string.IsNullOrEmpty(student.Email))
.OrderBy(student => student.Surname)
.ThenBy(student => student.Name)
.Select(student => new RegisterViewModel
{
Email = student.Email,
Name = student.Name,
Surname = student.Surname,
MiddleName = student.MiddleName
})
.Distinct()
.ToList();
var userIds = await AuthServiceClient.GetOrRegisterStudentsBatchAsync(registrationModels);
var successfulIds = userIds
.Where(x => x.Succeeded)
.Select(x => x.Value)
.ToList();
model.StudentIDs = successfulIds;
}
var result = await _coursesClient.CreateCourse(model);
return result.Succeeded
? Ok(result.Value)
: BadRequest(result.Errors);
}
[HttpPost("update/{courseId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> UpdateCourse(UpdateCourseViewModel model, long courseId)
{
await _coursesClient.UpdateCourse(model, courseId);
return Ok();
}
[HttpPost("signInCourse/{courseId}")]
[Authorize(Roles = Roles.StudentRole)]
public async Task<IActionResult> SignInCourse(long courseId)
{
await _coursesClient.SignInCourse(courseId, UserId);
return Ok();
}
[HttpPost("acceptStudent/{courseId}/{studentId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> AcceptStudent(long courseId, string studentId)
{
await _coursesClient.AcceptStudent(courseId, studentId);
return Ok();
}
[HttpPost("rejectStudent/{courseId}/{studentId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> RejectStudent(long courseId, string studentId)
{
await _coursesClient.RejectStudent(courseId, studentId);
return Ok();
}
[HttpPost("updateCharacteristics/{courseId}/{studentId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> UpdateStudentCharacteristics(long courseId, string studentId,
[FromBody] StudentCharacteristicsDto characteristics)
{
await _coursesClient.UpdateStudentCharacteristics(courseId, studentId, characteristics);
return Ok();
}
[HttpGet("userCourses")]
[Authorize]
public async Task<CoursePreviewView[]> GetAllUserCourses()
{
var userCourses = await _coursesClient.GetAllUserCourses();
var result = await GetCoursePreviews(userCourses);
return result;
}
[HttpGet("acceptLecturer/{courseId}/{lecturerEmail}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> AcceptLecturer(long courseId, string lecturerEmail)
{
var lecturer = await AuthServiceClient.GetAccountDataByEmail(lecturerEmail);
if (lecturer == null) return NotFound("Преподаватель с такой почтой не найден");
if (lecturer.Role != Roles.LecturerRole && lecturer.Role != Roles.ExpertRole)
return BadRequest("Пользователь не является преподавателем");
var result = await _coursesClient.AcceptLecturer(courseId, lecturerEmail, lecturer.UserId);
return result.Succeeded
? Ok(result)
: BadRequest(result.Errors);
}
[HttpGet("getLecturersAvailableForCourse/{courseId}")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetLecturersAvailableForCourse(long courseId)
{
var lecturers = await AuthServiceClient.GetAllLecturers();
var courseMentors = await _coursesClient.GetCourseLecturersIds(courseId);
var result = lecturers.Where(x => !courseMentors.Contains(x.UserId));
return Ok(result.ToArray());
}
[HttpGet("tags/{courseId}")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(string[]), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetAllTagsForCourse(long courseId)
{
var result = await _coursesClient.GetAllTagsForCourse(courseId);
return result.Succeeded
? Ok(result.Value)
: BadRequest(result.Errors);
}
[HttpPost("editMentorWorkspace/{courseId}/{mentorId}")]
[Authorize(Roles = Roles.LecturerRole)]
public async Task<IActionResult> EditMentorWorkspace(
long courseId, string mentorId, EditMentorWorkspaceDTO editMentorWorkspaceDto)
{
var mentor = await AuthServiceClient.GetAccountData(mentorId);
if (mentor == null)
return NotFound("Пользователь с такой почтой не найден");
if (!Roles.LecturerOrExpertRole.Contains(mentor.Role))
return BadRequest("Пользователь с такой почтой не является преподавателем или экспертом");
var courseFilterModel = _mapper.Map<CreateCourseFilterDTO>(editMentorWorkspaceDto);
courseFilterModel.Id = mentorId;
var courseFilterCreationResult =
await _coursesClient.CreateOrUpdateCourseFilter(courseId, courseFilterModel);
return courseFilterCreationResult.Succeeded
? Ok()
: BadRequest(courseFilterCreationResult.Errors[0]);
}
[HttpGet("getMentorWorkspace/{courseId}/{mentorId}")]
[Authorize(Roles = Roles.LecturerRole)]
[ProducesResponseType(typeof(WorkspaceViewModel), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetMentorWorkspace(long courseId, string mentorId)
{
var mentor = await AuthServiceClient.GetAccountData(mentorId);
if (mentor == null)
return NotFound("Пользователь с такой почтой не найден");
if (!Roles.LecturerOrExpertRole.Contains(mentor.Role))
return BadRequest("Пользователь с такой почтой не является преподавателем или экспертом");
var mentorCourseView = await _coursesClient.GetCourseByIdForMentor(courseId, mentorId);
if (!mentorCourseView.Succeeded)
return BadRequest(mentorCourseView.Errors[0]);
var studentIds = mentorCourseView.Value.CourseMates.Select(t => t.StudentId).ToArray();
var students = await AuthServiceClient.GetAccountsData(studentIds);
var workspace = new WorkspaceViewModel
{
Homeworks = mentorCourseView.Value.Homeworks,
Students = students.OrderBy(x => x.Surname).ThenBy(x => x.Name).ToArray(),
Groups = mentorCourseView.Value.Groups,
};
return Ok(workspace);
}
private async Task<CourseViewModel> ToCourseViewModel(CourseDTO course)
{
var studentIds = course.CourseMates.Select(t => t.StudentId).ToArray();
var getStudentsTask = AuthServiceClient.GetAccountsData(studentIds);
var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds);
await Task.WhenAll(getStudentsTask, getMentorsTask);
var students = getStudentsTask.Result;
var acceptedStudents = new List<AccountDataDto>();
var newStudents = new List<AccountDataDto>();
for (var i = 0; i < students.Length; i++)
{
if (!(students[i] is { } student)) continue;
if (course.CourseMates[i].IsAccepted) acceptedStudents.Add(student);
else newStudents.Add(student);
}
return new CourseViewModel
{
Id = course.Id,
Name = course.Name,
GroupName = course.GroupName,
Mentors = getMentorsTask.Result.Where(t => t != null).ToArray(),
AcceptedStudents = acceptedStudents.ToArray(),
NewStudents = newStudents.ToArray(),
Homeworks = course.Homeworks,
Groups = course.Groups,
IsCompleted = course.IsCompleted,
IsOpen = course.IsOpen
};
}
}