Projekt

Obecné

Profil

Stáhnout (2.34 KB) Statistiky
| Větev: | Tag: | Revize:
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
            var documents = context.Documents.Where(d => request.DocumentIdList.Contains(d.Id)).ToList();
31
            if (documents.Count() != request.DocumentIdList.Count)
32
            {
33
                logger.Information($"Received a non-existent Document ID when assigning documents to users");
34
                throw new InvalidOperationException($"{request.DocumentIdList.Count - documents.Count()} of the received documents do not exist");
35
            }
36

    
37
            var users = context.Users.Where(u => request.UserIdList.Contains(u.Id)).ToList(); 
38
            foreach (var user in users)
39
            {
40
                var userAnnotatedDocuments = context.Annotations.Where(a => a.User == user).Select(a => a.Document).ToList();
41
                foreach (var doc in documents)
42
                {
43
                    if (userAnnotatedDocuments.Contains(doc))
44
                    {
45
                        logger.Information($"User {user.Username} has already been assigned the document {doc.Id}, ignoring");
46
                        continue;
47
                    }
48

    
49
                    context.Annotations.Add(new Annotation()
50
                    {
51
                        User = user,
52
                        UserAssigned = addingUser,
53
                        DateAssigned = DateTime.Now,
54
                        DateLastChanged = DateTime.Now,
55
                        Document = doc,
56
                        State = EState.NEW,
57
                        Note = ""
58
                    });
59
                }
60
            }
61

    
62
            context.SaveChanges();
63
        }
64
    }
65
}
(1-1/2)