Exemplo n.º 1
0
        public async Task UpdateInvoice(string invoiceId, InvoiceAddEditDTO invoiceDto, string actorId)
        {
            if (string.IsNullOrWhiteSpace(invoiceId))
            {
                throw new ArgumentException(nameof(invoiceId));
            }

            if (invoiceDto == null)
            {
                throw new ArgumentNullException(nameof(invoiceDto));
            }

            Invoice invoice = await this.invoiceRepo.GetById(invoiceId);

            if (invoice == null)
            {
                throw new InvalidOperationException($"Invoice with id='{invoice.Id}' doesn't exist.");
            }

            Invoice updatedInvoice = this.mapper.Map <Invoice>(invoiceDto);
            IReadOnlyCollection <AuditLogUpdate> invoiceChanges = this.changeDetector.DetectChanges(invoice, updatedInvoice);

            if (invoiceChanges.Count > 0)
            {
                updatedInvoice.Id            = invoice.Id;
                updatedInvoice.LastUpdateLog = AuditLog.Create(actorId, invoiceChanges);

                await this.invoiceRepo.Update(updatedInvoice);
            }
        }
Exemplo n.º 2
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                if (String.IsNullOrEmpty(request.ModuleId))
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId   = ObjectId.Parse(request.UserId);
                var moduleId = ObjectId.Parse(request.ModuleId);

                var draft = await _db.ModuleDraftCollection.AsQueryable()
                            .Where(x => (
                                       x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                       ) && !x.DraftPublished && (
                                       x.Id == moduleId || x.ModuleId == moduleId
                                       )
                                   )
                            .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (draft == null)
                {
                    return(Result.Fail("Rascunho não Encontrado"));
                }

                var oldValues = JsonConvert.SerializeObject(new List <ModuleDraft>
                {
                    draft
                });

                draft.QuestionsLimit = request.QuestionsLimit;

                await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                                                                t.Id == draft.Id, draft,
                                                                cancellationToken : cancellationToken
                                                                );

                var newDraftList = new List <ModuleDraft>
                {
                    draft
                };

                var changeLog = AuditLog.Create(userId, draft.Id, draft.GetType().ToString(),
                                                JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                return(Result.Ok());
            }
Exemplo n.º 3
0
        public async Task <string> CreateInvoice(InvoiceAddEditDTO invoiceDto, string actorId)
        {
            if (invoiceDto == null)
            {
                throw new ArgumentNullException(nameof(invoiceDto));
            }

            Invoice invoice = this.mapper.Map <Invoice>(invoiceDto);

            invoice.CreateLog = AuditLog.Create(actorId);

            await this.invoiceRepo.Create(invoice);

            return(invoice.Id);
        }
Exemplo n.º 4
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var draftId = ObjectId.Parse(request.EventId);

                var draft = await _db.EventDraftCollection.AsQueryable()
                            .Where(x => (
                                       x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                       ) && !x.DraftPublished && (
                                       x.Id == draftId || x.EventId == draftId
                                       )
                                   )
                            .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (draft == null)
                {
                    return(Result.Fail("Rascunho não encontrado"));
                }

                if (request.UserRole == "Student")
                {
                    var userId = ObjectId.Parse(request.UserId);

                    if (!draft.InstructorId.HasValue || draft.InstructorId.Value != userId)
                    {
                        return(Result.Fail("Acesso Negado"));
                    }
                }

                draft.DeletedBy = ObjectId.Parse(request.UserId);
                draft.DeletedAt = DateTimeOffset.Now;

                await _db.EventDraftCollection.ReplaceOneAsync(t =>
                                                               t.Id == draft.Id, draft,
                                                               cancellationToken : cancellationToken
                                                               );

                var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), draftId, draft.GetType().ToString(),
                                                "", EntityAction.Delete, JsonConvert.SerializeObject(draft));


                return(Result.Ok());
            }
Exemplo n.º 5
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Student" || request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId     = ObjectId.Parse(request.UserId);
                var questionId = ObjectId.Parse(request.Id);

                var question = await _db.QuestionDraftCollection
                               .AsQueryable()
                               .FirstOrDefaultAsync(x => x.Id == questionId);

                if (question == null)
                {
                    return(Result.Fail("Pergunta não encontrada"));
                }

                await _db.QuestionDraftCollection.DeleteOneAsync(x =>
                                                                 x.Id == questionId,
                                                                 cancellationToken : cancellationToken
                                                                 );

                var oldQuestionList = new List <QuestionDraft>
                {
                    question
                };
                var oldValues = JsonConvert.SerializeObject(oldQuestionList);

                var deleteLog = AuditLog.Create(userId, question.DraftId,
                                                oldQuestionList[0].GetType().ToString(), "", EntityAction.Delete, oldValues);

                await _db.AuditLogCollection.InsertOneAsync(deleteLog);

                return(Result.Ok());
            }
Exemplo n.º 6
0
            public async Task<Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole != "Admin" && request.UserRole != "Author")
                    return Result.Fail("Acesso Negado");

                var userId = ObjectId.Parse(request.UserId);
                var modId = ObjectId.Parse(request.Id);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                    .Where(x => (
                            x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                        ) && !x.DraftPublished && (
                            x.Id == modId || x.ModuleId == modId
                        )
                    )
                    .FirstOrDefaultAsync(cancellationToken: cancellationToken);


                if (request.UserRole == "Author" && module.CreatedBy != userId)
                    return Result.Fail("Você não tem permissão para alterar o módulo selecionado.");

                Duration duration = null;
                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                        return Result.Fail(durationResult.Error);

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;
                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                        return Result.Fail(durationResult.Error);

                    videoDuration = durationResult.Data;
                }

                if (request.TutorsIds == null)
                    request.TutorsIds = new List<string>();

                if (request.ExtraInstructorIds == null)
                    request.ExtraInstructorIds = new List<string>();

                if (module == null)
                {
                    var originalModule = await GetModule(request.Id);
                    if (originalModule == null)
                        return Result.Fail("Módulo não existe");

                    module = await CreateModuleDraft(userId, request, originalModule, 
                        duration, videoDuration, cancellationToken
                    );
                }
                else
                {
                    var oldValues = JsonConvert.SerializeObject(new List<ModuleDraft>
                    {
                        module
                    });

                    module.Title = request.Title;
                    module.Excerpt = request.Excerpt;
                    module.InstructorId = string.IsNullOrEmpty(request.InstructorId) ? ObjectId.Empty : ObjectId.Parse(request.InstructorId);
                    module.Instructor = request.Instructor;
                    module.InstructorMiniBio = request.InstructorMiniBio;
                    module.InstructorImageUrl = request.InstructorImageUrl;
                    module.ImageUrl = request.ImageUrl;
                    module.VideoUrl = request.VideoUrl;
                    module.VideoDuration = videoDuration;
                    module.Published = request.Published;
                    module.Duration = duration;
                    module.Tags = request.Tags.Select(
                        t => Tag.Create(t).Data
                    ).ToList();
                    module.CertificateUrl = request.CertificateUrl;
                    module.TutorsIds = request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList();
                    module.ExtraInstructorIds = request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList();
                    module.StoreUrl = request.StoreUrl;
                    module.EcommerceUrl = request.EcommerceUrl;
                    module.CreateInEcommerce = request.CreateInEcommerce.HasValue ? request.CreateInEcommerce.Value : false;
                    module.EcommerceId = request.EcommerceId;
                    module.ModuleGradeType = request.ModuleGradeType;
                    module.ValidFor = request.ValidFor;

                    await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                        t.Id == module.Id, module,
                        cancellationToken: cancellationToken
                    );

                    var newDraftList = new List<ModuleDraft>
                    {
                        module
                    };

                    var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                    JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);

                }

                return Result.Ok();
            }
Exemplo n.º 7
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId = ObjectId.Parse(request.UserId);
                var modId  = ObjectId.Parse(request.ModuleId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == modId || x.ModuleId == modId
                                        )
                                    )
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    var originalModule = await GetModule(request.ModuleId);

                    if (originalModule == null)
                    {
                        return(Result.Fail("Módulo não existe"));
                    }

                    module = await CreateModuleDraft(
                        request, originalModule, cancellationToken
                        );
                }

                var oldValues = JsonConvert.SerializeObject(new List <ModuleDraft>
                {
                    module
                });

                if (request.DeleteNonExistent)
                {
                    module = DeleteNonExisting(module, request.Contents);
                }

                foreach (var ccontent in request.Contents)
                {
                    var subjectId = ObjectId.Parse(ccontent.SubjectId);
                    var subject   = module.Subjects.FirstOrDefault(x => x.Id == subjectId);
                    if (subject == null)
                    {
                        return(Result.Fail <bool>("Assunto não Encontrado"));
                    }

                    Content content = null;
                    if (string.IsNullOrEmpty(ccontent.Id))
                    {
                        var contentConcepts = ccontent.Concepts.Select(
                            x => new ConceptPosition(x.Name, x.Positions, x.Anchors)
                            ).ToList();

                        var contentResult = Content.Create(
                            ccontent.Title, ccontent.Excerpt, contentConcepts,
                            ccontent.ReferenceUrls, ccontent.Value,
                            ccontent.Type, ccontent.Duration, ccontent.numPages
                            );

                        if (contentResult.IsFailure)
                        {
                            return(Result.Fail(contentResult.Error));
                        }

                        content               = contentResult.Data;
                        content.UpdatedAt     = DateTimeOffset.UtcNow;
                        content.ReferenceUrls = new List <string>(ccontent.ReferenceUrls);

                        subject.Contents.Add(content);
                    }
                    else
                    {
                        content = subject.Contents.FirstOrDefault(x => x.Id == ObjectId.Parse(ccontent.Id));
                        if (content == null)
                        {
                            return(Result.Fail($"Conteúdo não encontrado ({ccontent.Id} - {ccontent.Title})"));
                        }

                        content.Title   = ccontent.Title;
                        content.Excerpt = ccontent.Excerpt;

                        content.Duration      = ccontent.Duration;
                        content.Type          = ccontent.Type;
                        content.ReferenceUrls = new List <string>(ccontent.ReferenceUrls);
                        content.Concepts      = ccontent.Concepts
                                                .Select(x => new ConceptPosition(x.Name, x.Positions, x.Anchors)).ToList();
                        content.Value    = ccontent.Value;
                        content.NumPages = ccontent.numPages;
                    }
                }

                await _db.ModuleDraftCollection.ReplaceOneAsync(
                    t => t.Id == module.Id, module,
                    cancellationToken : cancellationToken
                    );

                var newDraftList = new List <ModuleDraft>
                {
                    module
                };

                var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                                JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                return(Result.Ok());
            }
Exemplo n.º 8
0
            public async Task <Result <ModuleDraft> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole != "Admin" && request.UserRole != "Author")
                {
                    return(Result.Fail <ModuleDraft>("Acesso Negado"));
                }

                var userId = ObjectId.Parse(request.UserId);
                var tags   = new List <Tag>();

                foreach (var tagStr in request.Tags)
                {
                    var tag = Tag.Create(tagStr);
                    tags.Add(tag.Data);
                }

                var tutorsIds = request.TutorsIds != null?
                                request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                    new List <ObjectId>();

                var instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                                   ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var extraInstructorIds = request.ExtraInstructorIds != null?
                                         request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList() :
                                             new List <ObjectId>();

                Module          dbModule          = null;
                List <Question> dbModuleQuestions = new List <Question>();

                if (!String.IsNullOrEmpty(request.ModuleId))
                {
                    dbModule = await GetModule(request.ModuleId);
                }

                if (dbModule == null)
                {
                    dbModule = Module.Create(
                        request.Title,
                        request.Excerpt,
                        request.Instructor,
                        request.ImageUrl,
                        new List <ObjectId>(),
                        instructorId,
                        new List <SupportMaterial>(),
                        new List <Requirement>(),
                        tags,
                        request.Published ?? false,
                        null,
                        new List <Subject>(),
                        request.CertificateUrl,
                        tutorsIds,
                        extraInstructorIds,
                        request.StoreUrl,
                        request.EcommerceUrl,
                        request.ModuleGradeType,
                        request.ValidFor
                        ).Data;

                    await _db.ModuleCollection.InsertOneAsync(
                        dbModule, cancellationToken : cancellationToken
                        );
                }
                else
                {
                    dbModuleQuestions = await GetModuleQuestions(request.ModuleId);
                }

                var draft = ModuleDraft.Create(
                    dbModule.Id, request.Title, request.Excerpt, request.ImageUrl, request.Published ?? false,
                    instructorId, request.Instructor, request.InstructorMiniBio, request.InstructorImageUrl,
                    null, null, null, request.CertificateUrl, request.StoreUrl, request.EcommerceUrl, request.CreateInEcommerce ?? false,
                    tags, tutorsIds, extraInstructorIds, request.ModuleGradeType
                    ).Data;

                var newDraftList = new List <ModuleDraft>
                {
                    draft
                };

                await _db.ModuleDraftCollection.InsertOneAsync(
                    draft, cancellationToken : cancellationToken
                    );

                var creationLog = AuditLog.Create(userId, draft.Id, draft.GetType().ToString(),
                                                  JsonConvert.SerializeObject(newDraftList), EntityAction.Add);

                await _db.AuditLogCollection.InsertOneAsync(creationLog);

                if (dbModuleQuestions.Count > 0)
                {
                    var draftQuestions = dbModuleQuestions.Select(q =>
                                                                  QuestionDraft.Create(
                                                                      q.Id, draft.Id,
                                                                      q.Text, q.Level, q.Duration,
                                                                      q.Concepts, q.Answers,
                                                                      q.ModuleId, q.SubjectId
                                                                      ).Data
                                                                  );

                    await _db.QuestionDraftCollection.InsertManyAsync(
                        draftQuestions, cancellationToken : cancellationToken
                        );
                }

                return(Result.Ok(draft));
            }
Exemplo n.º 9
0
            private async Task<ModuleDraft> CreateModuleDraft(ObjectId userId, Contract request, Module originalModule,
                Duration duration, Duration videoDuration, CancellationToken token
            ) {
                var tags = new List<Tag>();
                foreach (var tagStr in request.Tags)
                {
                    var tag = Tag.Create(tagStr);
                    tags.Add(tag.Data);
                }

                var tutorsIds = request.TutorsIds != null ?
                    request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                    new List<ObjectId>();

                var instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                    ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var extraInstructorIds = request.ExtraInstructorIds != null ?
                    request.ExtraInstructorIds.Select(x => ObjectId.Parse(x)).ToList() :
                    new List<ObjectId>();

                var moduleId = ObjectId.Parse(request.Id);

                var module = ModuleDraft.Create(
                    moduleId, request.Title, request.Excerpt, request.ImageUrl, request.Published,
                    instructorId, request.Instructor, request.InstructorMiniBio, request.InstructorImageUrl,
                    duration, videoDuration, request.VideoUrl, request.CertificateUrl, request.StoreUrl, request.EcommerceUrl,
                    request.CreateInEcommerce.HasValue ? request.CreateInEcommerce.Value : false,
                    tags, tutorsIds, extraInstructorIds, request.ModuleGradeType
                ).Data;

                module.Subjects = originalModule.Subjects;
                module.Requirements = originalModule.Requirements;
                module.SupportMaterials = originalModule.SupportMaterials;

                await _db.ModuleDraftCollection.InsertOneAsync(
                    module, cancellationToken: token
                );

                var creationLog = AuditLog.Create(userId, moduleId, module.GetType().ToString(),
                    JsonConvert.SerializeObject(module), EntityAction.Add);

                await _db.AuditLogCollection.InsertOneAsync(creationLog);

                var dbModuleQuestions = await _db.QuestionCollection.AsQueryable()
                    .Where(q => q.ModuleId == moduleId)
                    .ToListAsync();

                if (dbModuleQuestions.Count > 0)
                {
                    var draftQuestions = dbModuleQuestions.Select(q =>
                        QuestionDraft.Create(
                            q.Id, module.Id,
                            q.Text, q.Level, q.Duration,
                            q.Concepts, q.Answers,
                            q.ModuleId, q.SubjectId
                        ).Data
                    );

                    await _db.QuestionDraftCollection.InsertManyAsync(
                        draftQuestions, cancellationToken: token
                    );
                }

                return module;
            }
 public void Handle(AuditDomainEvent auditDomainEvent)
 {
     _efContext.AuditLog.Add(AuditLog.Create(auditDomainEvent.Description));
     _efContext.SaveChanges();
 }
Exemplo n.º 11
0
            public async Task <Result <List <ContractSubject> > > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail <List <ContractSubject> >("Acesso Negado"));
                }

                var userId = ObjectId.Parse(request.UserId);
                var modId  = ObjectId.Parse(request.ModuleId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == modId || x.ModuleId == modId
                                        )
                                    )
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    var originalModule = await GetModule(request.ModuleId);

                    if (originalModule == null)
                    {
                        return(Result.Fail <List <ContractSubject> >("Módulo não existe"));
                    }

                    module = await CreateModuleDraft(
                        request, originalModule, cancellationToken
                        );
                }

                if (request.Subjects != null)
                {
                    var oldValues = JsonConvert.SerializeObject(new List <ModuleDraft>
                    {
                        module
                    });

                    if (request.DeleteNonExistent)
                    {
                        var existingIds = from o in request.Subjects
                                          where !string.IsNullOrEmpty(o.Id)
                                          select ObjectId.Parse(o.Id);

                        var include = from c in module.Subjects
                                      where existingIds.Contains(c.Id)
                                      select c;

                        module.Subjects = include.ToList();
                    }

                    foreach (var csubject in request.Subjects)
                    {
                        Subject subject = null;
                        if (string.IsNullOrEmpty(csubject.Id))
                        {
                            var subjectResult = Subject.Create(csubject.Title, csubject.Excerpt, csubject.Concepts);
                            if (subjectResult.IsFailure)
                            {
                                return(Result.Fail <List <ContractSubject> >(subjectResult.Error));
                            }

                            subject           = subjectResult.Data;
                            subject.UpdatedAt = DateTimeOffset.UtcNow;
                            module.Subjects.Add(subject);
                        }
                        else
                        {
                            subject = module.Subjects.FirstOrDefault(x => x.Id == ObjectId.Parse(csubject.Id));
                            if (subject == null)
                            {
                                return(Result.Fail <List <ContractSubject> >($"Assunto não encontrado ({csubject.Id} - {csubject.Title})"));
                            }

                            subject.Title   = csubject.Title;
                            subject.Excerpt = csubject.Excerpt;

                            var clist = Concept.GetConcepts(csubject.Concepts);
                            if (clist.IsFailure)
                            {
                                return(Result.Fail <List <ContractSubject> >(clist.Error));
                            }

                            subject.Concepts = clist.Data;
                        }

                        if (csubject.UserProgresses != null)
                        {
                            subject.UserProgresses = new List <UserProgress>();

                            foreach (var crequirements in csubject.UserProgresses)
                            {
                                var req = UserProgress.Create(ProgressType.SubjectProgress, crequirements.Level,
                                                              crequirements.Percentage);
                                if (req.IsFailure)
                                {
                                    return(Result.Fail <List <ContractSubject> >(req.Error));
                                }

                                subject.UserProgresses.Add(req.Data);
                            }
                        }
                    }

                    var newDraftList = new List <ModuleDraft>
                    {
                        module
                    };

                    var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                await _db.ModuleDraftCollection.ReplaceOneAsync(
                    t => t.Id == module.Id, module,
                    cancellationToken : cancellationToken
                    );

                var response = module.Subjects.Select(subject =>
                                                      new ContractSubject()
                {
                    Concepts = subject.Concepts.Select(c => c.Name).ToArray(),
                    Excerpt  = subject.Excerpt,
                    Id       = subject.Id.ToString(),
                    Title    = subject.Title,
                    Contents = subject.Contents.Select(c => new ContentItem()
                    {
                        Duration      = c.Duration,
                        Excerpt       = c.Excerpt,
                        Id            = c.Id,
                        ReferenceUrls = c.ReferenceUrls,
                        Title         = c.Title,
                        Type          = c.Type,
                        Value         = c.Value,
                        Concepts      = c.Concepts.Select(concept => new ConceptItem()
                        {
                            Anchors   = concept.Anchors,
                            Positions = concept.Positions,
                            Name      = concept.Name
                        }).ToArray(),
                    }).ToList(),
                    UserProgresses = subject.UserProgresses.Select(up => new ContractUserProgress
                    {
                        Level      = up.Level,
                        Percentage = up.Percentage
                    }).ToList()
                }
                                                      ).ToList();

                return(Result.Ok(response));
            }
Exemplo n.º 12
0
            public async Task <Result <bool> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Student" || request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <bool>("Acesso Negado"));
                }

                var eId     = ObjectId.Parse(request.EventId);
                var eventDb = await(await _db
                                    .Database
                                    .GetCollection <Event>("Events")
                                    .FindAsync(x => x.Id == eId, cancellationToken: cancellationToken))
                              .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (eventDb == null)
                {
                    return(Result.Fail <bool>("Módulo não Encontrado"));
                }

                eventDb.DeletedBy = ObjectId.Parse(request.UserId);
                eventDb.DeletedAt = DateTimeOffset.Now;

                var tracks = await _db.Database
                             .GetCollection <Track>("Tracks")
                             .AsQueryable()
                             .ToListAsync();

                foreach (Track track in tracks)
                {
                    int removed = track.EventsConfiguration.RemoveAll(x =>
                                                                      x.EventId == eventDb.Id
                                                                      );

                    if (removed > 0)
                    {
                        await _db.TrackCollection.ReplaceOneAsync(t =>
                                                                  t.Id == track.Id, track,
                                                                  cancellationToken : cancellationToken
                                                                  );
                    }
                }

                var  eventAppCollection = _db.Database.GetCollection <UserEventItem>("EventApplications");
                var  eventAppQuery      = eventAppCollection.AsQueryable();
                bool deleteEvent        = eventAppQuery.FirstOrDefault(x => x.EventId == eventDb.Id) == null;

                var oldEventList = new List <Event>
                {
                    eventDb
                };


                if (deleteEvent)
                {
                    await _db.EventCollection.DeleteOneAsync(t =>
                                                             t.Id == eventDb.Id,
                                                             cancellationToken : cancellationToken
                                                             );
                }
                else
                {
                    await _db.EventCollection.ReplaceOneAsync(t =>
                                                              t.Id == eventDb.Id,
                                                              eventDb,
                                                              cancellationToken : cancellationToken
                                                              );
                }


                var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), eventDb.Id, eventDb.GetType().ToString(),
                                                "", EntityAction.Delete, JsonConvert.SerializeObject(oldEventList));

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                return(Result.Ok(true));
            }
Exemplo n.º 13
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ? ObjectId.Empty : ObjectId.Parse(request.InstructorId);
                var      tutorsIds    = request.TutorsIds != null?request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                            new List <ObjectId>();

                var eventResult = Event.Create(
                    request.Title,
                    request.Excerpt,
                    request.ImageUrl,
                    instructorId,
                    request.Instructor,
                    request.InstructorMiniBio,
                    request.InstructorImageUrl,
                    request.Tags,
                    request.VideoUrl,
                    request.VideoDuration,
                    request.Duration,
                    request.CertificateUrl,
                    tutorsIds,
                    request.StoreUrl,
                    request.ForceProblemStatement
                    );

                if (eventResult.IsFailure)
                {
                    return(Result.Fail <Contract>(eventResult.Error));
                }

                var newEvent = eventResult.Data;

                newEvent.PrepQuizQuestionList = new List <PrepQuizQuestion>();

                if (request.PrepQuizQuestionList != null && request.PrepQuizQuestionList.Count > 0)
                {
                    var questions = request.PrepQuizQuestionList.Select(x => x.Question).ToArray();

                    for (int i = 0; i < request.PrepQuizQuestionList.Count; i++)
                    {
                        var prepQuizResult = PrepQuizQuestion.Create(request.PrepQuizQuestionList[i].Question, request.PrepQuizQuestionList[i].FileAsAnswer, questions);
                        if (prepQuizResult.IsFailure)
                        {
                            return(Result.Fail <Contract>(prepQuizResult.Error));
                        }
                        newEvent.PrepQuizQuestionList.Add(prepQuizResult.Data);
                    }
                }

                if (string.IsNullOrEmpty(request.Id))
                {
                    if (request.UserRole == "Student")
                    {
                        return(Result.Fail <Contract>("Acesso Negado"));
                    }

                    string config = _configuration[$"EcommerceIntegration:Active"];

                    if (request.CreateInEcommerce.HasValue && request.CreateInEcommerce.Value && config == "True")
                    {
                        var response = await CreateEcommerceProduct(newEvent);

                        string content = await response.Content.ReadAsStringAsync();

                        if (response.StatusCode == HttpStatusCode.Created)
                        {
                            var parsed = JObject.Parse(content);
                            newEvent.EcommerceId = (long)parsed["product"]["id"];
                        }
                        else
                        {
                            var error = ErrorLog.Create(
                                ErrorLogTypeEnum.EcommerceIntegration,
                                "create-track", content
                                ).Data;

                            await _db.ErrorLogCollection.InsertOneAsync(
                                error, cancellationToken : cancellationToken
                                );
                        }
                    }

                    var newEventList = new List <Event>
                    {
                        newEvent
                    };

                    await _db.EventCollection.InsertOneAsync(
                        newEvent,
                        cancellationToken : cancellationToken
                        );

                    var creationLog = AuditLog.Create(ObjectId.Parse(request.UserId), newEvent.Id, newEvent.GetType().ToString(),
                                                      JsonConvert.SerializeObject(newEventList), EntityAction.Add);

                    await _db.AuditLogCollection.InsertOneAsync(creationLog);

                    request.Id          = newEvent.Id.ToString();
                    request.EcommerceId = newEvent.EcommerceId;
                }
                else
                {
                    var evt = await(await _db
                                    .Database
                                    .GetCollection <Event>("Events")
                                    .FindAsync(x => x.Id == ObjectId.Parse(request.Id), cancellationToken: cancellationToken))
                              .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                    if (evt == null)
                    {
                        return(Result.Fail <Contract>("Evento não Encontrado"));
                    }

                    if (request.UserRole == "Student")
                    {
                        var userId = ObjectId.Parse(request.UserId);

                        if (!evt.InstructorId.HasValue || evt.InstructorId.Value != userId)
                        {
                            return(Result.Fail <Contract>("Acesso Negado"));
                        }
                    }

                    var oldEventList = JsonConvert.SerializeObject(new List <Event>
                    {
                        newEvent
                    });

                    evt.Title              = newEvent.Title;
                    evt.Excerpt            = newEvent.Excerpt;
                    evt.ImageUrl           = newEvent.ImageUrl;
                    evt.InstructorId       = newEvent.InstructorId;
                    evt.Instructor         = newEvent.Instructor;
                    evt.InstructorMiniBio  = newEvent.InstructorMiniBio;
                    evt.InstructorImageUrl = newEvent.InstructorImageUrl;
                    evt.Tags                  = newEvent.Tags;
                    evt.VideoUrl              = newEvent.VideoUrl;
                    evt.VideoDuration         = newEvent.VideoDuration;
                    evt.Duration              = newEvent.Duration;
                    evt.PrepQuiz              = newEvent.PrepQuiz;
                    evt.CertificateUrl        = newEvent.CertificateUrl;
                    evt.TutorsIds             = newEvent.TutorsIds;
                    evt.StoreUrl              = newEvent.StoreUrl;
                    evt.EcommerceId           = request.EcommerceId;
                    evt.PrepQuizQuestionList  = newEvent.PrepQuizQuestionList;
                    evt.ForceProblemStatement = newEvent.ForceProblemStatement;

                    await _db.EventCollection.ReplaceOneAsync(t =>
                                                              t.Id == evt.Id, evt,
                                                              cancellationToken : cancellationToken
                                                              );

                    var newEventList = new List <Event>
                    {
                        evt
                    };

                    var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), evt.Id, evt.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newEventList), EntityAction.Update, oldEventList);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);

                    if (evt.EcommerceId.HasValue)
                    {
                        string config = _configuration[$"EcommerceIntegration:Active"];
                        if (config == "True")
                        {
                            await UpdateEcommerceProduct(evt);
                        }
                    }
                }

                return(Result.Ok(request));
            }
Exemplo n.º 14
0
            private async Task <bool> UpdateCurrentModule(ObjectId userId, ModuleDraft draft, CancellationToken token)
            {
                var module = await _db.ModuleCollection.AsQueryable()
                             .Where(mod => mod.Id == draft.ModuleId)
                             .FirstOrDefaultAsync();

                if (module == null)
                {
                    return(false);
                }

                string config = _configuration[$"EcommerceIntegration:Active"];

                if (!draft.EcommerceId.HasValue && draft.CreateInEcommerce && config == "True")
                {
                    var response = await CreateEcommerceProduct(module);

                    string content = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        var parsed = JObject.Parse(content);
                        module.EcommerceId = (long)parsed["product"]["id"];
                    }
                    else
                    {
                        var error = ErrorLog.Create(
                            ErrorLogTypeEnum.EcommerceIntegration,
                            "create-module", content
                            ).Data;

                        await _db.ErrorLogCollection.InsertOneAsync(
                            error, cancellationToken : token
                            );
                    }
                }

                var serializedModuleOldValues = JsonConvert.SerializeObject(new List <Module>
                {
                    module
                });

                module.Title              = draft.Title;
                module.Excerpt            = draft.Excerpt;
                module.ImageUrl           = draft.ImageUrl;
                module.Published          = draft.Published;
                module.InstructorId       = draft.InstructorId;
                module.ExtraInstructorIds = draft.ExtraInstructorIds;
                module.Instructor         = draft.Instructor;
                module.InstructorMiniBio  = draft.InstructorMiniBio;
                module.InstructorImageUrl = draft.InstructorImageUrl;
                module.Duration           = draft.Duration;
                module.VideoUrl           = draft.VideoUrl;
                module.VideoDuration      = draft.VideoDuration;
                module.CertificateUrl     = draft.CertificateUrl;
                module.StoreUrl           = draft.StoreUrl;
                module.EcommerceUrl       = draft.EcommerceUrl;
                module.Tags             = draft.Tags;
                module.TutorsIds        = draft.TutorsIds;
                module.Subjects         = draft.Subjects;
                module.Requirements     = draft.Requirements;
                module.SupportMaterials = draft.SupportMaterials;
                module.EcommerceId      = draft.EcommerceId;
                module.ModuleGradeType  = draft.ModuleGradeType;
                var listEcomerce = new List <EcommerceModule>();

                if (draft.EcommerceProducts != null && draft.EcommerceProducts.Count > 0)
                {
                    for (int i = 0; i < draft.EcommerceProducts.Count; i++)
                    {
                        var currentDraftProduct = draft.EcommerceProducts[i];
                        listEcomerce.Add(new EcommerceModule()
                        {
                            EcommerceId      = currentDraftProduct.EcommerceId,
                            UsersAmount      = currentDraftProduct.UsersAmount,
                            DisableEcommerce = currentDraftProduct.DisableEcommerce,
                            Price            = currentDraftProduct.Price,
                            DisableFreeTrial = currentDraftProduct.DisableFreeTrial,
                            LinkEcommerce    = currentDraftProduct.LinkEcommerce,
                            LinkProduct      = currentDraftProduct.LinkProduct,
                            Subject          = currentDraftProduct.Subject,
                            Hours            = currentDraftProduct.Hours
                        });
                    }
                }
                module.EcommerceProducts = listEcomerce;

                await _db.ModuleCollection.ReplaceOneAsync(t =>
                                                           t.Id == module.Id, module,
                                                           cancellationToken : token
                                                           );

                var newDraftList = new List <Module>
                {
                    module
                };

                var auditLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                               JsonConvert.SerializeObject(newDraftList), EntityAction.Update, serializedModuleOldValues);
                await _db.AuditLogCollection.InsertOneAsync(auditLog);

                return(true);
            }
Exemplo n.º 15
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                var mId = ObjectId.Parse(request.EventId);
                var evt = await(await _db
                                .Database
                                .GetCollection <Event>("Events")
                                .FindAsync(x => x.Id == mId, cancellationToken: cancellationToken))
                          .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                //var location = request.Location == null ? null : await _db.LocationCollection
                //        .AsQueryable()
                //        .Where(x => x.Id == ObjectId.Parse(request.Location))
                //        .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                var location = await(await _db
                                     .Database
                                     .GetCollection <Location>("Locations")
                                     .FindAsync(x => x.Id == ObjectId.Parse(request.Location)))
                               .FirstOrDefaultAsync(cancellationToken: cancellationToken);


                if (evt == null)
                {
                    return(Result.Fail <Contract>("Evento não Encontrado"));
                }

                var oldValuesJson = JsonConvert.SerializeObject(evt.Schedules);

                if (request.UserRole == "Student")
                {
                    var userId = ObjectId.Parse(request.UserId);

                    if (!evt.InstructorId.HasValue || evt.InstructorId.Value != userId)
                    {
                        return(Result.Fail <Contract>("Acesso Negado"));
                    }
                }

                var scheduleResponse = EventSchedule.Create(
                    request.EventDate, request.SubscriptionStartDate,
                    request.SubscriptionEndDate, request.Duration, request.Published,
                    request.WebinarUrl, request.ForumStartDate, request.ForumEndDate, request.ApplicationLimit, location
                    );

                if (scheduleResponse.IsFailure)
                {
                    return(Result.Fail <Contract>(scheduleResponse.Error));
                }

                evt.Schedules = evt.Schedules ?? new List <EventSchedule>();
                if (string.IsNullOrEmpty(request.Id))
                {
                    evt.Schedules.Add(scheduleResponse.Data);
                    request.Id = scheduleResponse.Data.Id.ToString();
                }
                else
                {
                    var newSchedule = scheduleResponse.Data;
                    var schedule    =
                        evt.Schedules.FirstOrDefault(x => x.Id == ObjectId.Parse(request.Id));
                    if (schedule == null)
                    {
                        return(Result.Fail <Contract>("Programação de evento não encontrada"));
                    }

                    schedule.Duration              = newSchedule.Duration;
                    schedule.EventDate             = newSchedule.EventDate;
                    schedule.SubscriptionStartDate = newSchedule.SubscriptionStartDate;
                    schedule.SubscriptionEndDate   = newSchedule.SubscriptionEndDate;
                    schedule.ForumStartDate        = newSchedule.ForumStartDate;
                    schedule.ForumEndDate          = newSchedule.ForumEndDate;
                    schedule.Published             = newSchedule.Published;
                    schedule.WebinarUrl            = newSchedule.WebinarUrl;
                    schedule.Location              = newSchedule.Location;
                }

                await _db.EventCollection.ReplaceOneAsync(t =>
                                                          t.Id == evt.Id, evt,
                                                          cancellationToken : cancellationToken
                                                          );


                var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), evt.Id, evt.Schedules.GetType().ToString(),
                                                JsonConvert.SerializeObject(evt.Schedules), EntityAction.Update, oldValuesJson);

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                return(Result.Ok(request));
            }
Exemplo n.º 16
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Student" || request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                Duration duration = null;

                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;

                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    videoDuration = durationResult.Data;
                }

                ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                                        ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var tutorsIds = request.TutorsIds != null?
                                request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                    new List <ObjectId>();

                Event dbEvent = null;

                if (!String.IsNullOrEmpty(request.Id))
                {
                    dbEvent = await GetEvent(request.Id);
                }

                if (dbEvent == null)
                {
                    dbEvent = Event.Create(
                        request.Title,
                        request.Excerpt,
                        request.ImageUrl,
                        instructorId,
                        request.Instructor,
                        request.InstructorMiniBio,
                        request.InstructorImageUrl,
                        request.Tags,
                        request.VideoUrl,
                        request.VideoDuration,
                        request.Duration,
                        request.CertificateUrl,
                        tutorsIds,
                        request.StoreUrl
                        ).Data;

                    await _db.EventCollection.InsertOneAsync(
                        dbEvent, cancellationToken : cancellationToken
                        );

                    var newEventList = new List <Event>
                    {
                        dbEvent
                    };

                    var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), dbEvent.Id, dbEvent.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newEventList), EntityAction.Add, "");

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                var newEvent = await CreateEventDraft(request, dbEvent, duration, videoDuration, cancellationToken);

                request.Id = newEvent.Id.ToString();

                return(Result.Ok(request));
            }
Exemplo n.º 17
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary" || request.UserRole == "Recruiter")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                var mId    = ObjectId.Parse(request.ModuleId);
                var userId = ObjectId.Parse(request.UserId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == mId || x.ModuleId == mId
                                        )
                                    )
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    return(Result.Fail <Contract>("Módulo não Encontrado"));
                }

                if (request.UserRole == "Student")
                {
                    if (!ModuleDraft.IsInstructor(module, userId).Data)
                    {
                        return(Result.Fail <Contract>("Acesso Negado"));
                    }
                }

                var subject = module.Subjects.FirstOrDefault(x =>
                                                             x.Id == ObjectId.Parse(request.SubjectId)
                                                             );

                if (subject == null)
                {
                    return(Result.Fail <Contract>("Assunto não Encontrado"));
                }

                var answers = request.Answers.Select(x =>
                                                     new Answer(
                                                         x.Description, x.Points,
                                                         x.Concepts.Select(y => new AnswerConcept(y.Concept, y.IsRight)).ToList()
                                                         )
                                                     ).ToList();

                Result <QuestionDraft> newObject;

                if (!String.IsNullOrEmpty(request.QuestionId))
                {
                    var questionId = ObjectId.Parse(request.QuestionId);

                    newObject = QuestionDraft.Create(
                        questionId, module.Id, request.Text, request.Level, request.Duration,
                        request.Concepts, answers, module.ModuleId, ObjectId.Parse(request.SubjectId)
                        );
                }
                else
                {
                    newObject = QuestionDraft.Create(
                        module.Id, request.Text, request.Level, request.Duration,
                        request.Concepts, answers, module.ModuleId, ObjectId.Parse(request.SubjectId)
                        );
                }

                if (newObject.IsFailure)
                {
                    return(Result.Fail <Contract>(newObject.Error));
                }

                var newQuestion     = newObject.Data;
                var newQuestionList = new List <QuestionDraft>
                {
                    newQuestion
                };


                if (string.IsNullOrEmpty(request.Id))
                {
                    await _db.QuestionDraftCollection.InsertOneAsync(
                        newQuestion,
                        cancellationToken : cancellationToken
                        );

                    request.Id = newQuestion.Id.ToString();

                    var creationLog = AuditLog.Create(userId, mId, newQuestionList[0].GetType().ToString(),
                                                      JsonConvert.SerializeObject(newQuestionList), EntityAction.Add);

                    await _db.AuditLogCollection.InsertOneAsync(creationLog);
                }
                else
                {
                    var question = await _db.QuestionDraftCollection
                                   .AsQueryable()
                                   .Where(x => x.Id == ObjectId.Parse(request.Id))
                                   .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                    if (question == null)
                    {
                        return(Result.Fail <Contract>("Questão não Encontrada"));
                    }

                    var oldQuestionList = new List <QuestionDraft>
                    {
                        question
                    };
                    var oldValues = JsonConvert.SerializeObject(oldQuestionList);

                    question.ModuleId  = newQuestion.ModuleId;
                    question.SubjectId = newQuestion.SubjectId;
                    question.Concepts  = newQuestion.Concepts;
                    question.Answers   = newQuestion.Answers;
                    question.Duration  = newQuestion.Duration;
                    question.Level     = newQuestion.Level;
                    question.Text      = newQuestion.Text;
                    question.UpdatedAt = DateTimeOffset.UtcNow;

                    await _db.QuestionDraftCollection.ReplaceOneAsync(t =>
                                                                      t.Id == question.Id, question,
                                                                      cancellationToken : cancellationToken
                                                                      );

                    var changeLog = AuditLog.Create(userId, mId, newQuestionList[0].GetType().ToString(),
                                                    JsonConvert.SerializeObject(newQuestionList), EntityAction.Update, oldValues);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                return(Result.Ok(request));
            }
Exemplo n.º 18
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId = ObjectId.Parse(request.UserId);
                var modId  = ObjectId.Parse(request.ModuleId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == modId || x.ModuleId == modId
                                        )
                                    )
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                var results = request.Requirements.Select(x =>
                                                          Requirement.Create(
                                                              ObjectId.Parse(x.ModuleId),
                                                              x.Optional, x.Level, x.Percentage,
                                                              ProgressType.ModuleProgress
                                                              )
                                                          ).ToArray();

                var combinedResults = Result.Combine(results);

                if (combinedResults.IsFailure)
                {
                    return(Result.Fail(combinedResults.Error));
                }

                var newRequirements = results.Select(x => x.Data).ToList();

                if (module == null)
                {
                    var originalModule = await GetModule(request.ModuleId);

                    if (originalModule == null)
                    {
                        return(Result.Fail("Módulo não existe"));
                    }

                    module = await CreateModuleDraft(
                        request, originalModule, newRequirements, cancellationToken
                        );

                    var newValues = new List <ModuleDraft>
                    {
                        module
                    };

                    var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newValues), EntityAction.Add);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }
                else
                {
                    var oldValues = JsonConvert.SerializeObject(new List <ModuleDraft>
                    {
                        module
                    });

                    module.Requirements = newRequirements;
                    await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                                                                    t.Id == module.Id, module,
                                                                    cancellationToken : cancellationToken
                                                                    );

                    var newDraftList = new List <ModuleDraft>
                    {
                        module
                    };

                    var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                return(Result.Ok());
            }
Exemplo n.º 19
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole != "Admin" && request.UserRole != "Author")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId  = ObjectId.Parse(request.UserId);
                var draftId = ObjectId.Parse(request.ModuleId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == draftId || x.ModuleId == draftId
                                        )
                                    )
                             .FirstOrDefaultAsync();

                if (module == null)
                {
                    return(Result.Fail("Rascunho de Módulo não encontrado"));
                }


                if (module.CreatedBy != userId)
                {
                    return(Result.Fail("Você não tem permissão de excluir o módulo selecionado."));
                }

                if (request.UserRole == "Student")
                {
                    if (!ModuleDraft.IsInstructor(module, userId).Data)
                    {
                        return(Result.Fail("Acesso Negado"));
                    }
                }

                module.DeletedBy = ObjectId.Parse(request.UserId);
                module.DeletedAt = DateTimeOffset.Now;

                await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                                                                t.Id == module.Id, module,
                                                                cancellationToken : cancellationToken
                                                                );

                var oldDraftList = new List <ModuleDraft>
                {
                    module
                };

                var changeLog = AuditLog.Create(userId, draftId, module.GetType().ToString(),
                                                "", EntityAction.Delete, JsonConvert.SerializeObject(oldDraftList));

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                var questionDrafts = await _db.QuestionDraftCollection.AsQueryable()
                                     .Where(d => d.ModuleId == module.ModuleId && !d.DraftPublished)
                                     .ToListAsync();

                if (questionDrafts.Count > 0)
                {
                    var update = Builders <QuestionDraft> .Update
                                 .Set(d => d.DeletedAt, DateTimeOffset.Now)
                                 .Set(d => d.DeletedBy, ObjectId.Parse(request.UserId));

                    var ids = questionDrafts.Select(x => x.Id).ToArray();

                    await _db.QuestionDraftCollection.UpdateManyAsync(x =>
                                                                      ids.Contains(x.Id), update,
                                                                      cancellationToken : cancellationToken
                                                                      );
                }

                return(Result.Ok());
            }
Exemplo n.º 20
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var userId = ObjectId.Parse(request.UserId);
                var modId  = ObjectId.Parse(request.ModuleId);

                var module = await _db.ModuleDraftCollection.AsQueryable()
                             .Where(x => (
                                        x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                        ) && !x.DraftPublished && (
                                        x.Id == modId || x.ModuleId == modId
                                        )
                                    )
                             .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    var originalModule = await GetModule(request.ModuleId);

                    if (originalModule == null)
                    {
                        return(Result.Fail("Módulo não existe"));
                    }

                    module = await CreateModuleDraft(
                        request, originalModule, cancellationToken
                        );
                }

                var oldValues = JsonConvert.SerializeObject(new List <ModuleDraft>
                {
                    module
                });

                if (request.DeleteNonExistent)
                {
                    var existingIds = from o in request.SupportMaterials
                                      where !string.IsNullOrEmpty(o.Id)
                                      select ObjectId.Parse(o.Id);

                    var include = from c in module.SupportMaterials
                                  where existingIds.Contains(c.Id)
                                  select c;

                    module.SupportMaterials = include.ToList();
                }

                foreach (var requestObj in request.SupportMaterials)
                {
                    SupportMaterial newObject = null;
                    if (string.IsNullOrEmpty(requestObj.Id))
                    {
                        var result = Create(
                            requestObj.Title,
                            requestObj.Description,
                            requestObj.DownloadLink,
                            (SupportMaterialTypeEnum)requestObj.Type
                            );

                        if (result.IsFailure)
                        {
                            return(Result.Fail(result.Error));
                        }

                        newObject           = result.Data;
                        newObject.UpdatedAt = DateTimeOffset.UtcNow;
                        module.SupportMaterials.Add(newObject);
                    }
                    else
                    {
                        newObject = module.SupportMaterials.FirstOrDefault(x => x.Id == ObjectId.Parse(requestObj.Id));
                        if (newObject == null)
                        {
                            return(Result.Fail($"Material de suporte não encontrado"));
                        }

                        newObject.Title        = requestObj.Title;
                        newObject.Description  = requestObj.Description;
                        newObject.DownloadLink = requestObj.DownloadLink;
                    }
                }

                await _db.ModuleDraftCollection.ReplaceOneAsync(t =>
                                                                t.Id == module.Id, module,
                                                                cancellationToken : cancellationToken
                                                                );

                var newDraftList = new List <ModuleDraft>
                {
                    module
                };

                var changeLog = AuditLog.Create(userId, module.Id, module.GetType().ToString(),
                                                JsonConvert.SerializeObject(newDraftList), EntityAction.Update, oldValues);

                await _db.AuditLogCollection.InsertOneAsync(changeLog);

                return(Result.Ok());
            }
Exemplo n.º 21
0
            public async Task <Result <Contract> > Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail <Contract>("Acesso Negado"));
                }

                var evId = ObjectId.Parse(request.Id);

                var dbEvent = await _db.EventDraftCollection.AsQueryable()
                              .Where(x => (
                                         x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                         ) && !x.DraftPublished && (
                                         x.Id == evId || x.EventId == evId
                                         )
                                     )
                              .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                Duration duration = null;

                if (request.Duration.HasValue)
                {
                    var durationResult = Duration.Create(request.Duration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    duration = durationResult.Data;
                }

                Duration videoDuration = null;

                if (request.VideoDuration.HasValue)
                {
                    var durationResult = Duration.Create(request.VideoDuration.Value);
                    if (durationResult.IsFailure)
                    {
                        return(Result.Fail <Contract>(durationResult.Error));
                    }

                    videoDuration = durationResult.Data;
                }

                ObjectId instructorId = String.IsNullOrEmpty(request.InstructorId) ?
                                        ObjectId.Empty : ObjectId.Parse(request.InstructorId);

                var tutorsIds = request.TutorsIds != null?
                                request.TutorsIds.Select(x => ObjectId.Parse(x)).ToList() :
                                    new List <ObjectId>();

                var eventResult = Event.Create(
                    request.Title,
                    request.Excerpt,
                    request.ImageUrl,
                    instructorId,
                    request.Instructor,
                    request.InstructorMiniBio,
                    request.InstructorImageUrl,
                    request.Tags,
                    request.VideoUrl,
                    request.VideoDuration,
                    request.Duration,
                    request.CertificateUrl,
                    tutorsIds,
                    request.StoreUrl,
                    request.ForceProblemStatement
                    );

                if (eventResult.IsFailure)
                {
                    return(Result.Fail <Contract>(eventResult.Error));
                }

                var newEvent = eventResult.Data;

                newEvent.PrepQuizQuestionList = new List <PrepQuizQuestion>();

                if (request.PrepQuizQuestionList != null && request.PrepQuizQuestionList.Count > 0)
                {
                    var questions = request.PrepQuizQuestionList.Select(x => x.Question).ToArray();

                    for (int i = 0; i < request.PrepQuizQuestionList.Count; i++)
                    {
                        var prepQuizResult = PrepQuizQuestion.Create(request.PrepQuizQuestionList[i].Question, request.PrepQuizQuestionList[i].FileAsAnswer, questions);
                        if (prepQuizResult.IsFailure)
                        {
                            return(Result.Fail <Contract>(prepQuizResult.Error));
                        }
                        newEvent.PrepQuizQuestionList.Add(prepQuizResult.Data);
                    }
                }

                var oldEventList = JsonConvert.SerializeObject(new List <EventDraft>
                {
                    dbEvent
                });

                if (dbEvent == null)
                {
                    var originalEvent = await GetEvent(request.Id);

                    if (originalEvent == null)
                    {
                        return(Result.Fail <Contract>("Evento não existe"));
                    }

                    dbEvent = await CreateEventDraft(
                        request, originalEvent, duration, videoDuration, cancellationToken
                        );
                }
                else
                {
                    dbEvent.Title              = newEvent.Title;
                    dbEvent.Excerpt            = newEvent.Excerpt;
                    dbEvent.ImageUrl           = newEvent.ImageUrl;
                    dbEvent.InstructorId       = newEvent.InstructorId;
                    dbEvent.Instructor         = newEvent.Instructor;
                    dbEvent.InstructorMiniBio  = newEvent.InstructorMiniBio;
                    dbEvent.InstructorImageUrl = newEvent.InstructorImageUrl;
                    dbEvent.Tags                  = newEvent.Tags;
                    dbEvent.VideoUrl              = newEvent.VideoUrl;
                    dbEvent.VideoDuration         = newEvent.VideoDuration;
                    dbEvent.Duration              = newEvent.Duration;
                    dbEvent.PrepQuiz              = newEvent.PrepQuiz;
                    dbEvent.CertificateUrl        = newEvent.CertificateUrl;
                    dbEvent.TutorsIds             = newEvent.TutorsIds;
                    dbEvent.StoreUrl              = newEvent.StoreUrl;
                    dbEvent.CreateInEcommerce     = request.CreateInEcommerce.HasValue ? request.CreateInEcommerce.Value : false;
                    dbEvent.EcommerceId           = request.EcommerceId;
                    dbEvent.ForceProblemStatement = request.ForceProblemStatement;
                    dbEvent.PrepQuizQuestionList  = newEvent.PrepQuizQuestionList;

                    await _db.EventDraftCollection.ReplaceOneAsync(t =>
                                                                   t.Id == dbEvent.Id, dbEvent,
                                                                   cancellationToken : cancellationToken
                                                                   );

                    var newEventList = new List <EventDraft>
                    {
                        dbEvent
                    };

                    var changeLog = AuditLog.Create(ObjectId.Parse(request.UserId), dbEvent.Id, dbEvent.GetType().ToString(),
                                                    JsonConvert.SerializeObject(newEventList), EntityAction.Update, oldEventList);

                    await _db.AuditLogCollection.InsertOneAsync(changeLog);
                }

                return(Result.Ok(request));
            }
Exemplo n.º 22
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                if (request.UserRole == "Secretary")
                {
                    return(Result.Fail("Acesso Negado"));
                }

                var moduleId = ObjectId.Parse(request.ModuleId);
                var module   = await _db.ModuleDraftCollection.AsQueryable()
                               .Where(x => (
                                          x.DeletedAt == null || x.DeletedAt == DateTimeOffset.MinValue
                                          ) && !x.DraftPublished && (
                                          x.Id == moduleId || x.ModuleId == moduleId
                                          )
                                      )
                               .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (module == null)
                {
                    var originalModule = await GetModule(request.ModuleId);

                    if (originalModule == null)
                    {
                        return(Result.Fail("Módulo não existe"));
                    }

                    module = await CreateModuleDraft(
                        request, originalModule, cancellationToken
                        );
                }

                var subjectConceptDictionary = new Dictionary <string, List <string> >();

                foreach (var subject in module.Subjects)
                {
                    var subjectConcepts = subject.Concepts.Select(x => x.Name).ToList();
                    subjectConceptDictionary.Add(subject.Id.ToString(), subjectConcepts);
                }

                var questions = new List <QuestionDraft>();

                request.File = request.File.Substring(request.File.IndexOf(",", StringComparison.Ordinal) + 1);
                Byte[] bytes = Convert.FromBase64String(request.File);
                using (Stream stream = new MemoryStream(bytes))
                {
                    using (var xlPackage = new ExcelPackage(stream))
                    {
                        var baseWorksheet = xlPackage.Workbook.Worksheets[0];
                        var currentLine   = 2;

                        while (baseWorksheet.Cells[currentLine, 1].Value != null)
                        {
                            /*
                             *  IDExterno Assunto
                             *  ID Nível
                             *  Descrição Questão
                             *  Tempo médio de Resposta em minutos
                             *  Resposta 1
                             *  Valor Resposta 1
                             *  Conceitos certos Resposta 1
                             *  Resposta 2
                             *  Valor Resposta 2
                             *  Conceitos certos Resposta 2
                             *  Resposta 3
                             *  Valor Resposta 3
                             *  Conceitos certos Resposta 3
                             *  Resposta 4
                             *  Valor Resposta 4
                             *  Conceitos certos Resposta 4
                             *  Resposta 5
                             *  Valor Resposta 5
                             *  Conceitos certos Resposta 5
                             */

                            var subjectId = baseWorksheet.Cells[currentLine, 1].Value.ToString();

                            if (!subjectConceptDictionary.ContainsKey(subjectId))
                            {
                                return(Result.Fail <bool>("Assunto não encontrado"));
                            }
                            var subjectConcepts =
                                subjectConceptDictionary[subjectId];

                            var quest = new AddOrModifyQuestionCommand.Contract();
                            if (!int.TryParse(baseWorksheet.Cells[currentLine, 2].Value.ToString(), out int level))
                            {
                                var availableLevels = Level.GetLevels().Data.Select(x => x.Id.ToString())
                                                      .Aggregate((x, y) => x + "," + y);
                                return(Result.Fail <bool>(
                                           $"Não foi possível definir o nível de dificuldade da pergunta da linha {currentLine}. Valores possíveis são ({availableLevels})"));
                            }
                            quest.Level = level;

                            quest.Text = baseWorksheet.Cells[currentLine, 3].Value?.ToString();
                            if (quest.Text == null || quest.Text.Length < 10)
                            {
                                return(Result.Fail <bool>(
                                           $"Texto da pergunta da linha {currentLine} não pode ser menor que 10 caracteres"));
                            }

                            var durationStr = baseWorksheet.Cells[currentLine, 4].Value?.ToString();
                            if (durationStr != null && int.TryParse(durationStr, out int duration))
                            {
                                quest.Duration = duration;
                            }

                            if (baseWorksheet.Cells[currentLine, 5].Value != null)
                            {
                                var answer1 =
                                    this.getAnswerFromWorksheet(baseWorksheet, currentLine, 5, "Resposta 1");
                                if (answer1.IsFailure)
                                {
                                    return(Result.Fail <bool>(answer1.Error));
                                }
                                quest.Answers.Add(answer1.Data);
                            }

                            if (baseWorksheet.Cells[currentLine, 8].Value != null)
                            {
                                var answer2 =
                                    this.getAnswerFromWorksheet(baseWorksheet, currentLine, 8, "Resposta 2");
                                if (answer2.IsFailure)
                                {
                                    return(Result.Fail <bool>(answer2.Error));
                                }
                                quest.Answers.Add(answer2.Data);
                            }

                            if (baseWorksheet.Cells[currentLine, 11].Value != null)
                            {
                                var answer3 =
                                    this.getAnswerFromWorksheet(baseWorksheet, currentLine, 11, "Resposta 3");
                                if (answer3.IsFailure)
                                {
                                    return(Result.Fail <bool>(answer3.Error));
                                }
                                quest.Answers.Add(answer3.Data);
                            }

                            if (baseWorksheet.Cells[currentLine, 14].Value != null)
                            {
                                var answer4 =
                                    this.getAnswerFromWorksheet(baseWorksheet, currentLine, 14, "Resposta 4");
                                if (answer4.IsFailure)
                                {
                                    return(Result.Fail <bool>(answer4.Error));
                                }
                                quest.Answers.Add(answer4.Data);
                            }

                            if (baseWorksheet.Cells[currentLine, 17].Value != null)
                            {
                                var answer5 =
                                    this.getAnswerFromWorksheet(baseWorksheet, currentLine, 17, "Resposta 5");
                                if (answer5.IsFailure)
                                {
                                    return(Result.Fail <bool>(answer5.Error));
                                }
                                quest.Answers.Add(answer5.Data);
                            }

                            var concepts = quest.Answers.SelectMany(x => x.Concepts).Select(x => x.Concept).Distinct().ToList();
                            quest.Concepts = concepts.ToArray();

                            var notContainedConcepts = concepts.Where(x => !subjectConcepts.Contains(x)).ToList();
                            if (notContainedConcepts.Any())
                            {
                                return(Result.Fail <bool>($"Os conceitos ({notContainedConcepts.Aggregate((x, y) => x + "," + y)}) das repostas da linha {currentLine} não estão contidos no assunto"));
                            }

                            // Colocando os conceitos errados da pergunta
                            foreach (var answer in quest.Answers)
                            {
                                var answerConcepts     = answer.Concepts.Select(x => x.Concept);
                                var notPresentConcepts = concepts.Where(x => !answerConcepts.Contains(x)).Select(
                                    x => new AddOrModifyQuestionCommand.ContractAnswerConcept()
                                {
                                    Concept = x.Trim(),
                                    IsRight = false
                                });
                                answer.Concepts.AddRange(notPresentConcepts);
                            }

                            var answers = quest.Answers.Select(x => new Answer(x.Description, x.Points,
                                                                               x.Concepts.Select(y => new AnswerConcept(y.Concept, y.IsRight)).ToList())).ToList();

                            var newObject = QuestionDraft.Create(
                                module.Id, quest.Text, quest.Level,
                                quest.Duration, quest.Concepts, answers,
                                ObjectId.Parse(request.ModuleId), ObjectId.Parse(subjectId)
                                );

                            if (newObject.IsFailure)
                            {
                                return(Result.Fail <bool>($"Erro na linha {currentLine}: {newObject.Error}"));
                            }

                            questions.Add(newObject.Data);

                            currentLine++;
                        }
                    }
                }

                if (!request.AddQuestions)
                {
                    var baseQuestionDraftCollection = await _db.QuestionDraftCollection
                                                      .AsQueryable()
                                                      .Where(x =>
                                                             x.DraftId == module.Id
                                                             )
                                                      .ToListAsync();

                    await _db.QuestionDraftCollection.DeleteManyAsync(x =>
                                                                      x.DraftId == module.Id,
                                                                      cancellationToken : cancellationToken
                                                                      );

                    var deleteLog = AuditLog.Create(ObjectId.Parse(request.UserId), moduleId, baseQuestionDraftCollection.GetType().ToString(),
                                                    JsonConvert.SerializeObject(baseQuestionDraftCollection), EntityAction.Delete);

                    await _db.AuditLogCollection.InsertOneAsync(deleteLog);
                }

                await _db.QuestionDraftCollection.InsertManyAsync(
                    questions, cancellationToken : cancellationToken
                    );

                var creationLog = AuditLog.Create(ObjectId.Parse(request.UserId), moduleId, questions[0].GetType().ToString(),
                                                  JsonConvert.SerializeObject(questions), EntityAction.Add);

                await _db.AuditLogCollection.InsertOneAsync(creationLog);

                return(Result.Ok());
            }