1
|
using Core.Contexts;
|
2
|
using Core.Entities;
|
3
|
using Models.Annotations;
|
4
|
using Models.Enums;
|
5
|
using Serilog;
|
6
|
using System;
|
7
|
using System.Collections.Generic;
|
8
|
using System.Linq;
|
9
|
using System.Text;
|
10
|
using System.Threading.Tasks;
|
11
|
|
12
|
namespace Core.Services.AnnotationService
|
13
|
{
|
14
|
public class AnnotationServiceEF : IAnnotationService
|
15
|
{
|
16
|
private readonly DatabaseContext context;
|
17
|
private readonly ILogger logger;
|
18
|
|
19
|
public AnnotationServiceEF(DatabaseContext context, ILogger logger)
|
20
|
{
|
21
|
this.context = context;
|
22
|
this.logger = logger;
|
23
|
}
|
24
|
|
25
|
public void CreateDocumentAnnotations(AnnotationsAddRequest request, Guid clientUserId)
|
26
|
{
|
27
|
User addingUser = context.Users.Single(u => u.Id == clientUserId);
|
28
|
|
29
|
// Check the documents exist
|
30
|
foreach (Guid docId in request.DocumentIdList)
|
31
|
{
|
32
|
if (!context.Documents.Any(d => d.Id == docId))
|
33
|
{
|
34
|
logger.Information($"Received a non-existent Document ID when assigning documents to users");
|
35
|
throw new InvalidOperationException($"Document with ID {docId} does not exist");
|
36
|
}
|
37
|
}
|
38
|
|
39
|
foreach (Guid userId in request.UserIdList)
|
40
|
{
|
41
|
var user = context.Users.Single(u => u.Id == userId);
|
42
|
var userAnnotatedDocuments = context.Annotations.Where(a => a.User.Id == userId).Select(a => a.Document.Id);
|
43
|
|
44
|
foreach (Guid docId in request.DocumentIdList)
|
45
|
{
|
46
|
if (userAnnotatedDocuments.Contains(docId))
|
47
|
{
|
48
|
logger.Information($"User {user.Username} has already been assigned the document {docId}, ignoring");
|
49
|
}
|
50
|
|
51
|
var document = context.Documents.Single(d => d.Id == docId);
|
52
|
|
53
|
context.Annotations.Add(new Annotation()
|
54
|
{
|
55
|
User = user,
|
56
|
UserAssigned = addingUser,
|
57
|
DateAssigned = DateTime.Now,
|
58
|
DateLastChanged = DateTime.Now,
|
59
|
Document = document,
|
60
|
State = EState.NEW,
|
61
|
Note = ""
|
62
|
});
|
63
|
}
|
64
|
}
|
65
|
|
66
|
context.SaveChanges();
|
67
|
}
|
68
|
}
|
69
|
}
|