public async Task SendMessage_ShouldReturnForbiddenResult_WhenUserTriesMessagingHimself() { // Arrange SendMessageBody body = new SendMessageBody { RecipientId = 1, HtmlContent = "hello world" }; _mediatorMock .Setup(m => m.Send(It.IsAny <RecipientExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _mediatorMock .Setup(m => m.Send(It.IsAny <IsOwnRecipientQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); MessageController controller = new MessageController(null, _mediatorMock.Object); // Act ActionResult <ChatMessageResource> response = await controller.SendMessage(body); // Assert ObjectResult result = Assert.IsType <ObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status403Forbidden, error.StatusCode); }
public async Task SendMessage_ShouldReturnNotFoundResult_WhenRecipientDoesNotExist() { // Arrange SendMessageBody body = new SendMessageBody { RecipientId = 4314, HtmlContent = "hello world" }; _mediatorMock .Setup(m => m.Send(It.IsAny <RecipientExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); MessageController controller = new MessageController(null, _mediatorMock.Object); // Act ActionResult <ChatMessageResource> response = await controller.SendMessage(body); // Assert NotFoundObjectResult result = Assert.IsType <NotFoundObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.NotNull(error); Assert.Equal(StatusCodes.Status404NotFound, error.StatusCode); }
public async Task SendMessage_ShouldReturnBadRequestResult_WhenModelValidationFails() { // Arrange SendMessageBody body = new SendMessageBody(); MessageController controller = new MessageController(null, null); controller.ModelState.AddModelError("", ""); // Act ActionResult <ChatMessageResource> response = await controller.SendMessage(body); // Assert Assert.IsType <BadRequestObjectResult>(response.Result); }
public async Task SendMessage_ShouldReturnCreatedResult_WhenMessageHasBeenSent() { // Arrange SendMessageBody body = new SendMessageBody { RecipientId = 1, ParentId = 1, HtmlContent = "hello world" }; _mediatorMock .Setup(m => m.Send(It.IsAny <RecipientExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _mediatorMock .Setup(m => m.Send(It.IsAny <IsOwnRecipientQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); _mediatorMock .Setup(m => m.Send(It.IsAny <MessageExistsQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _mediatorMock .Setup(m => m.Send(It.IsAny <CanAccessMessageQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(true); _mediatorMock .Setup(m => m.Send(It.IsAny <SendMessageCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new ChatMessageResource()); MessageController controller = new MessageController(_mapperMock, _mediatorMock.Object); // Act ActionResult <ChatMessageResource> response = await controller.SendMessage(body); // Assert Assert.IsType <CreatedAtActionResult>(response.Result); }
public async Task <IActionResult> SendMessage(int barcode, bool isFromRequest) { int? protectionDocTypeId = null; int? docBarcode = null; string file = string.Empty; string typeNameRu = string.Empty; Attachment attachment = new Attachment(); var document = await _executor.GetQuery <GetDocumentByBarcodeQuery>() .Process(d => d.ExecuteAsync(barcode)); int?answerDocId = null; if (document.IncomingAnswerId.HasValue) { var documentAnswer = await _executor.GetQuery <GetDocumentByIdQuery>().Process(d => d.ExecuteAsync(document.IncomingAnswerId.Value)); answerDocId = documentAnswer.Barcode; } var docType = document.Type.ExternalId ?? document.TypeId; if (document.Requests.Count != 0) { var request = await _executor.GetQuery <GetRequestByDocumentIdQuery>().Process(d => d.ExecuteAsync(document.Id)); if (isFromRequest && request == null) { throw new NotSupportedException("Прикрепленная заявка не найдена"); } protectionDocTypeId = request?.ProtectionDocType.ExternalId ?? request?.ProtectionDocType.Id; docBarcode = request?.Barcode; } if (document.Contracts.Count != 0) { var contract = await _executor.GetQuery <GetContractByDocumentIdQuery>().Process(d => d.ExecuteAsync(document.Id)); if (isFromRequest && contract == null) { throw new NotSupportedException("Прикрепленный договор не найден"); } protectionDocTypeId = contract?.ProtectionDocType.ExternalId ?? contract?.ProtectionDocType.Id; docBarcode = contract?.Barcode; } if (document.ProtectionDocs.Count != 0) { var protectionDoc = await _executor.GetQuery <GetProtectionDocByDocumentIdQuery>().Process(d => d.ExecuteAsync(document.Id)); if (isFromRequest && protectionDoc == null) { throw new NotSupportedException("Прикрепленный договор не найден"); } protectionDocTypeId = protectionDoc?.Request.ProtectionDocType.ExternalId ?? protectionDoc?.Request.ProtectionDocType.Id; docBarcode = protectionDoc?.Request?.Barcode; } if (!document.MainAttachmentId.HasValue && document.WasScanned) { throw new NotSupportedException("Файл у документа не найден"); } if (document.MainAttachmentId.HasValue) { attachment = await _executor.GetQuery <GetAttachmentQuery>().Process(d => d.ExecuteAsync(document.MainAttachmentId.Value)); var bytes = await _executor.GetQuery <GetAttachmentFileQuery>().Process(d => d.Execute(attachment.Id)); file = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); } var input = await _executor.GetQuery <GetDocumentUserInputByDocumentIdQuery>().Process(q => q.ExecuteAsync(document.Id)); if (input != null && !document.WasScanned && !document.MainAttachmentId.HasValue) { var dto = JsonConvert.DeserializeObject <UserInputDto>(input.UserInput); var documentGenerator = _templateGeneratorFactory.Create(dto.Code); var generatedFile = documentGenerator.Process(new Dictionary <string, object> { { "UserId", NiisAmbientContext.Current.User.Identity.UserId }, { "RequestId", dto.OwnerId }, { "DocumentId", document.Id }, { "UserInputFields", dto.Fields }, { "SelectedRequestIds", dto.SelectedRequestIds }, { "PageCount", dto.PageCount }, { "OwnerType", dto.OwnerType }, { "Index", dto.Index } }); var bytes = generatedFile.File; file = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); typeNameRu = document?.Type?.NameRu + ".pdf"; } var sendMessageBody = new SendMessageBody { Input = new SendMessage { DocumentId = docBarcode, PatentTypeId = protectionDocTypeId, AnswerDocId = answerDocId, MessageInfo = new MessageInfo { Id = docType, DocumentId = document.Barcode, DocNumber = document.OutgoingNumber, DocDate = document.DateCreate.ToString("dd-MM-yyyy") }, File = new Domain.Intergrations.File { Name = attachment?.ValidName ?? typeNameRu, Content = file } } }; var result = _lkIntergarionHelper.CallWebService(sendMessageBody, SoapActions.SendMessage); return(Ok(result)); }
public async Task <ActionResult <ChatMessageResource> > SendMessage([FromBody] SendMessageBody body, CancellationToken cancellationToken = default) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Check if recipient exists RecipientExistsQuery recipientExistsQuery = new RecipientExistsQuery { RecipientId = body.RecipientId }; bool recipientExists = await _mediator.Send(recipientExistsQuery, cancellationToken); if (!recipientExists) { return(NotFound(new ErrorResource { StatusCode = StatusCodes.Status404NotFound, Message = $"Recipient with ID '{body.RecipientId}' does not exist" })); } // Check if the the user wants to message himself IsOwnRecipientQuery isOwnRecipientQuery = new IsOwnRecipientQuery { RecipientId = body.RecipientId }; bool isOwnRecipient = await _mediator.Send(isOwnRecipientQuery, cancellationToken); if (isOwnRecipient) { return(StatusCode(StatusCodes.Status403Forbidden, new ErrorResource { StatusCode = StatusCodes.Status403Forbidden, Message = "You cannot write messages to yourself" })); } if (body.ParentId != null) { // Check if parent message exists MessageExistsQuery parentMessageExistsQuery = new MessageExistsQuery { MessageId = body.ParentId.Value }; bool parentMessageExists = await _mediator.Send(parentMessageExistsQuery, cancellationToken); if (!parentMessageExists) { return(NotFound(new ErrorResource { StatusCode = StatusCodes.Status404NotFound, Message = $"Parent message with ID '{body.ParentId}' does not exist" })); } // Check if the user should have access to the parent message CanAccessMessageQuery canAccessParentMessageQuery = new CanAccessMessageQuery { MessageId = body.ParentId.Value }; bool canAccessParentMessage = await _mediator.Send(canAccessParentMessageQuery, cancellationToken); if (!canAccessParentMessage) { return(StatusCode(StatusCodes.Status403Forbidden, new ErrorResource { StatusCode = StatusCodes.Status403Forbidden, Message = "You cannot answer messages from a foreign chat" })); } } // Send message to their recipients SendMessageCommand sendMessageCommand = _mapper.Map <SendMessageBody, SendMessageCommand>(body); ChatMessageResource message = await _mediator.Send(sendMessageCommand, cancellationToken); return(CreatedAtAction(nameof(GetMessageById), new { messageId = message.MessageId }, message)); }