/// <summary> /// Выполнение обработчика. /// </summary> /// <param name="material">Загруженный файл.</param> /// <returns>Созданный документ.</returns> public Document Execute(MaterialDetailDto material) { var newDocument = _mapper.Map <MaterialDetailDto, Document>(material); Executor .GetHandler <GenerateBarcodeHandler>() .Process(handler => handler.Execute(newDocument)); newDocument.ReceiveTypeId = Executor .GetQuery <GetReceiveTypeByCodeQuery>() .Process(query => query.Execute(DicReceiveType.Codes.Courier)).Id; var user = Executor .GetQuery <GetUserByIdQuery>() .Process(query => query.Execute(NiisAmbientContext.Current.User.Identity.UserId)); newDocument.DepartmentId = user.DepartmentId; newDocument.DivisionId = user.Department.DivisionId; newDocument.DocumentType = Executor .GetQuery <GetDocumentTypeEnumByTypeIdQuery>() .Process(query => query.Execute(newDocument.TypeId)); var firstRequestOwnerId = material.Owners?.FirstOrDefault()?.OwnerId; if (firstRequestOwnerId != null) { var request = Executor .GetQuery <GetRequestByIdQuery>() .Process(q => q.Execute(firstRequestOwnerId.Value)); newDocument.AddresseeId = request.AddresseeId; } return(newDocument); }
/// <summary> /// Создает документ и возвращает его идентификатор. /// </summary> /// <param name="material">Материал.</param> /// <returns>Идентификатор созданного документа.</returns> private async Task <int> CreateDocumentAndGetId(MaterialDetailDto material) { Document newDocument = _executor .GetHandler <CreateDocumentFromUploadedFileHandler>() .Process(handler => handler.Execute(material)); DicDocumentStatus workStatus = _executor .GetQuery <GetDocumentStatusByCodeQuery>() .Process(query => query.Execute(DicDocumentStatusCodes.InWork)); newDocument.StatusId = workStatus.Id; int documentId = await _executor .GetCommand <CreateDocumentCommand>() .Process(command => command.ExecuteAsync(newDocument)); DocumentWorkflow initialWorkflow = await _executor .GetQuery <GetInitialDocumentWorkflowQuery>() .Process(query => query.ExecuteAsync(documentId, NiisAmbientContext.Current.User.Identity.UserId)); await _executor .GetCommand <ApplyDocumentWorkflowCommand>() .Process(command => command.ExecuteAsync(initialWorkflow)); if (newDocument.DocumentType == DocumentType.Incoming) { await _executor .GetHandler <GenerateDocumentIncomingNumberHandler>() .Process(c => c.ExecuteAsync(documentId)); } return(documentId); }
/// <summary> /// Кладет вложения в материалы. /// </summary> /// <param name="materials">Материалы с вложениями.</param> /// <returns>Материалы.</returns> public async Task <List <MaterialDetailDto> > AddAttachmentsToMaterials(IEnumerable <MaterialDetailDto> materials) { List <MaterialDetailDto> responseMaterials = new List <MaterialDetailDto>(); foreach (MaterialDetailDto material in materials) { Document documentWithAttachment = await _executor .GetHandler <AddMainAttachToDocumentHandler>() .Process(handler => handler.Execute(material)); MaterialDetailDto materialWithAttachment = _mapper.Map <MaterialDetailDto>(documentWithAttachment); //IList<MaterialWorkflowDto> materialWorkflows = await _autoRouteStageHelper.StartAutuRouteStage(documentWithAttachment.Id); //if (materialWorkflows != null) //{ // materialWithAttachment.WorkflowDtos = materialWorkflows.ToArray(); //} responseMaterials.Add(materialWithAttachment); } return(responseMaterials); }
public async Task <IActionResult> Replace([FromBody] MaterialDetailDto data) { var result = await _mediator.Send(new ReplaceAttachment.Command(data, User.Identity.GetUserId())); return(Ok(result)); }
public async Task <Document> Execute(MaterialDetailDto data) { using (var fileStream = System.IO.File.OpenRead(Path.Combine(Path.GetTempPath(), data.Attachment.TempName))) { if (!data.Id.HasValue) { throw new Exception("Document not Found"); } var document = await Executor.GetQuery <GetDocumentByIdQuery>().Process(q => q.ExecuteAsync(data.Id.Value)); if (document == null) { throw new Exception("Document not Found"); } var bucketName = "documents"; string extentionPath; switch (document.DocumentType) { case DocumentType.Incoming: extentionPath = "incoming"; break; case DocumentType.Outgoing: extentionPath = "outgoing"; break; case DocumentType.Internal: extentionPath = "internal"; break; case DocumentType.DocumentRequest: extentionPath = "documentRequest"; document.StatusId = Executor.GetQuery <GetDocumentStatusByCodeQuery>().Process(q => q.Execute(DicDocumentStatusCodes.Completed)).Id; break; default: extentionPath = "unknown"; break; } var fileName = $"{document.Barcode}_{document.Type.Code}{Path.GetExtension(data.Attachment.Name)}"; //var extentionPathResult = extentionPath != null ? $"{extentionPath}/" : string.Empty; //var originalName = $"current/{extentionPathResult}{document.Id}/{fileName}"; var extention = Path.GetExtension(fileName); var originalName = $"current/{extentionPath}/{document.Id}/{Guid.NewGuid().ToString()}{extention}"; var userId = NiisAmbientContext.Current.User.Identity.UserId; var newAttachment = data.Attachment.ContentType.Equals(ContentType.Pdf) ? _attachmentHelper.NewPdfObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, data.Attachment.IsMain, document.Id) : _attachmentHelper.NewFileObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, data.Attachment.IsMain, document.Id); // TODO: Transaction with complex logic //using (var transaction = _context.Database.BeginTransaction()) //{ try { await Executor.GetCommand <CreateAttachmentCommand>().Process(q => q.ExecuteAsync(newAttachment)); document.WasScanned = data.Attachment.WasScanned; if (data.Attachment.IsMain) { var oldAttachment = document.MainAttachment; document.MainAttachment = newAttachment; document.MainAttachmentId = newAttachment.Id; await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(document)); if (oldAttachment != null) { await Executor.GetCommand <DeleteAttachmentCommand>() .Process(q => q.ExecuteAsync(oldAttachment)); try { await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.ValidName); } catch (Exception exception) { var contextExceptionMessage = $"{Guid.NewGuid()}: {exception.Message}"; Log.Warning(exception, contextExceptionMessage); } } } else { var oldAttachment = document.AdditionalAttachments.FirstOrDefault(d => d.IsMain == false); if (oldAttachment != null) { await Executor.GetCommand <DeleteAttachmentCommand>() .Process(q => q.ExecuteAsync(oldAttachment)); try { await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.OriginalName); } catch (Exception exception) { var contextExceptionMessage = $"{Guid.NewGuid()}: {exception.Message}"; Log.Warning(exception, contextExceptionMessage); } } await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(document)); } await _fileStorage.AddAsync(newAttachment.BucketName, newAttachment.OriginalName, fileStream, newAttachment.ContentType); //transaction.Commit(); } catch { //todo: log exception throw; } // } return(document); } }
public async Task <IActionResult> CompleteRequest([FromBody] IntellectualPropertyScannerDto dto) { if (!dto.Id.HasValue) { var newRequest = Executor.GetHandler <CreateRequestFromUploadedFileHandler>() .Process(h => h.Execute(dto)); await Executor.GetCommand <CreateRequestCommand>() .Process(c => c.ExecuteAsync(newRequest)); var initialWorkflow = await Executor.GetQuery <GetInitialRequestWorkflowQuery>().Process(q => q.ExecuteAsync(newRequest, NiisAmbientContext.Current.User.Identity.UserId)); if (initialWorkflow != null) { await Executor.GetHandler <ProcessRequestWorkflowHandler>() .Process(h => h.Handle(initialWorkflow, newRequest)); } Executor.GetHandler <GenerateRequestIncomingNumberHandler>().Process(c => c.Execute(newRequest.Id)); await Executor.GetCommand <UpdateRequestCommand>().Process(c => c.ExecuteAsync(newRequest)); dto.Id = newRequest.Id; } //TODO! Перенести функционал в проект сканера, тот проект большой, долго разбираться, пока реализовал здесь var protectionDocType = Executor.GetQuery <GetDicProtectionDocTypeByIdQuery>() .Process(q => q.Execute(dto.ProtectionDocTypeId)); string documentTypeCode; switch (protectionDocType.Code) { case DicProtectionDocTypeCodes.RequestTypeTrademarkCode: documentTypeCode = DicDocumentTypeCodes.RequestForTrademark; break; case DicProtectionDocTypeCodes.ProtectionDocTypeInternationalTrademarkCode: documentTypeCode = DicDocumentTypeCodes.RequestForInternationalTrademark; break; case DicProtectionDocTypeCodes.RequestTypeIndustrialSampleCode: documentTypeCode = DicDocumentTypeCodes.RequestForIndustrialSample; break; case DicProtectionDocTypeCodes.RequestTypeInventionCode: documentTypeCode = DicDocumentTypeCodes.RequestForInvention; break; case DicProtectionDocTypeCodes.RequestTypeNameOfOriginCode: documentTypeCode = DicDocumentTypeCodes.RequestForNmpt; break; case DicProtectionDocTypeCodes.RequestTypeSelectionAchieveCode: documentTypeCode = DicDocumentTypeCodes.RequestForSelectiveAchievement; break; case DicProtectionDocTypeCodes.RequestTypeUsefulModelCode: documentTypeCode = DicDocumentTypeCodes.RequestForUsefulModel; break; default: throw new NotImplementedException(); } var dicDocumentType = Executor.GetQuery <GetDicDocumentTypeByCodeQuery>() .Process(q => q.Execute(documentTypeCode)); var requestDocuments = await Executor.GetQuery <GetDocumentsByRequestIdQuery>().Process(q => q.ExecuteAsync(dto.Id.Value)); var newDocument = requestDocuments.FirstOrDefault(d => d.TypeId == dicDocumentType.Id); if (newDocument == null) { var materialDto = new MaterialDetailDto { TypeId = dicDocumentType.Id, DocumentType = DocumentType.Incoming, Owners = new[] { new MaterialOwnerDto { OwnerType = Owner.Type.Request, OwnerId = dto.Id.Value, ProtectionDocTypeId = dto.ProtectionDocTypeId } }, WasScanned = true }; if (materialDto.DocumentType == DocumentType.DocumentRequest) { materialDto.StatusId = Executor.GetQuery <GetDocumentStatusByCodeQuery>().Process(q => q.Execute(DicDocumentStatusCodes.Completed)).Id; } newDocument = Executor.GetHandler <CreateDocumentFromUploadedFileHandler>() .Process(h => h.Execute(materialDto)); var docId = await Executor.GetCommand <CreateDocumentCommand>() .Process(c => c.ExecuteAsync(newDocument)); var initialWorkflow = await Executor.GetQuery <GetInitialDocumentWorkflowQuery>() .Process(q => q.ExecuteAsync(docId, NiisAmbientContext.Current.User.Identity.UserId)); await Executor.GetCommand <ApplyDocumentWorkflowCommand>().Process(c => c.ExecuteAsync(initialWorkflow)); if (newDocument.DocumentType == DocumentType.Incoming) { await Executor.GetHandler <GenerateDocumentIncomingNumberHandler>().Process(c => c.ExecuteAsync(docId)); } } if (newDocument.MainAttachmentId.HasValue) { newDocument.MainAttachment = null; newDocument.MainAttachmentId = null; await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(newDocument)); } var request = await Executor.GetHandler <AddMainAttachToRequestHandler>().Process(r => r.Execute(dto)); newDocument.MainAttachment = request.MainAttachment; newDocument.MainAttachmentId = request.MainAttachmentId; newDocument.AddresseeId = request.AddresseeId; await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(newDocument)); var requestDto = Mapper.Map <IntellectualPropertyDto>(request); return(Ok(requestDto)); }