private void SaveDocumentInfo(FullDocumentInfo fullDocumentInfo) { if (!UserInput.ChooseYesNo("Сохранить информацию?")) return; var directoryPath = ChooseDirectory(); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); // сохраняем основной документ Console.Out.WriteLine("Сохранение документа '{0}'", fullDocumentInfo.Document.FileName); FileHelper.WriteAllBytes(directoryPath, fullDocumentInfo.Document.FileName, GetDocumentContent(fullDocumentInfo.Document)); // сохраняем карточку, если есть if (fullDocumentInfo.Document.Card != null) { var cardFileName = Path.GetFileNameWithoutExtension(fullDocumentInfo.Document.FileName) + ".card.xml"; Console.Out.WriteLine("Сохранение карточки документа '{0}'", cardFileName); FileHelper.WriteAllBytes(directoryPath, cardFileName, fullDocumentInfo.Document.Card); } // сохраняем подписи, если есть if (fullDocumentInfo.Signs != null) { foreach (var sign in fullDocumentInfo.Signs) { var signFileName = sign.Subject + ".sig"; Console.Out.WriteLine("Сохранение подписи '{0}'", signFileName); FileHelper.WriteAllBytes(directoryPath, signFileName, sign.Raw); } //Получение усовершенствованных подписей if (!UserInput.ChooseYesNo("Получить усовершенствованные подписи?")) return; foreach (var sign in fullDocumentInfo.Signs) { var signFileName = sign.Subject + ".sig"; Console.Out.WriteLine("Получение усовершенствованной подписи для '{0}'", signFileName); EnhancedSign enhancedSign; try { enhancedSign = _context.ServiceClient.GetEnhancedSignById(_context.CurrentBox, sign.Id); } catch (Exception exc) { Console.Error.WriteLine(exc.Message); continue; } if (enhancedSign.CreateStatus == EnhancedSignCreateStatus.Failed) Console.Out.WriteLine("Не удалось создать усовершенствованную подпись для {0}: {1}", signFileName, enhancedSign.FailedInfo.Message); else if (enhancedSign.CreateStatus == EnhancedSignCreateStatus.InProgress) Console.Out.WriteLine( "Усовершенствованная подпись для {0} еще не создана, запросите еще раз {1}", signFileName, enhancedSign.CreateTime.ToString("dd.MM.yyyy hh:mm:ss UTC")); else { var enhancedSignFileName = sign.Subject + ".enhanced.sig"; Console.Out.WriteLine("Сохранение усовершенствованной подписи '{0}'", enhancedSignFileName); FileHelper.WriteAllBytes(directoryPath, enhancedSignFileName, enhancedSign.Raw); } } // TODO сохранить служебные документы и подписи к ним } }
private X509Certificate2 CheckSignAndGetCertificate(FullDocumentInfo documentInfo, Sign sign) { var document = documentInfo.Document; if (document.NeedReceipt && IsNoticeRequired(documentInfo)) { UserInput.Warning("Не удалось проверить подпись документа т.к. на него запрошено УОП"); return null; } var contentInfo = new ContentInfo(GetDocumentContent(document)); var signedCms = new SignedCms(contentInfo, true); try { // проверям подпись (действительность сервтификата не проверям для простоты) signedCms.Decode(sign.Raw); signedCms.CheckSignature(true); } catch (CryptographicException) { UserInput.Error("Подпись на документ {0} недействительна", document.Id); return null; } var certificate = signedCms.Certificates[0]; return certificate; }
private void ProcessServiceInvoiceConfirmation(Message message, FullDocumentInfo documentInfo) { var document = documentInfo.Document; if (document.NoticeRequired) { Console.Out.WriteLine("Генерируются извещения о получении подтверждения"); var noticeMessage = _context.MessageFactory.CreateInvoiceReceipt(message, document, _context.Certificate); SendServiceDocument(noticeMessage, "Отправлено извещение о получении подтверждения"); } else { UserInput.Information("Извещение о получении подтверждения уже было отправлено"); } }
/// <summary> /// Обработать требуемую подпись для документа /// </summary> /// <param name="message">Сообщение с докуметом</param> /// <param name="documentInfo">Полная информация о документе</param> private void ProcessUntypedDocument(Message message, FullDocumentInfo documentInfo) { ProcessRequiredNotice(message, documentInfo); ProcessRequiredSign(message, documentInfo); }
private void ProcessRequiredSign(Message message, FullDocumentInfo documentInfo) { // если ожидается подпись то подписываем или отказываем в подписи if (IsSignRequired(documentInfo)) { var document = documentInfo.Document; var certificate = _context.Certificate; if (UserInput.ChooseYesNo("Отправитель запросил подпись под документом. Подписать документ?")) { // отправляем подпись под документом EnsureDocumentContentLoaded(document); var signMessage = _context.MessageFactory.CreateSign(message, document, certificate); SendServiceDocument(signMessage, "Документ продписан"); } else { // генерируем СД УОУ var text = UserInput.ReadParameter("Текст уточнения:", string.Empty); var amendmentRequestMessage = _context.MessageFactory.CreateAmendmentRequest(message, document, text, certificate); SendServiceDocument(amendmentRequestMessage, "Отправлено уведомление об уточнении"); } } }
private void ProcessRevocationOffer(Message message, FullDocumentInfo documentInfo) { ProcessRequiredSign(message, documentInfo); }
private void ProcessInvoice(Message message, FullDocumentInfo documentInfo) { var document = documentInfo.Document; if (document.NoticeRequired) { Console.Out.WriteLine("Генерируются извещения о получении СФ"); var noticeMessage = _context.MessageFactory.CreateInvoiceReceipt(message, document, _context.Certificate); SendServiceDocument(noticeMessage, "Отправлено извещение о получении СФ отправлено"); } else { UserInput.Information("Извещение о получении СФ уже было отправлено"); } if (((InvoiceDocumentFlowStatus)documentInfo.Status).BuyerFlow == InvoiceFlowStatus.InvoiceRejected) { UserInput.Information("Уведомление об уточнении СФ уже было отправлено"); } else if (UserInput.ChooseYesNo("Запросить уточнение на счет-фактуру?")) { var text = UserInput.ReadParameter("Текст уточнения:", string.Empty); var invoiceAmendmentRequestMessage = _context.MessageFactory.GenerateInvoiceAmendmentRequest(message, document, text, _context.Certificate); SendServiceDocument(invoiceAmendmentRequestMessage, "Отправлено уведомление об уточнении СФ"); } }
private void ProcessRequiredNotice(Message message, FullDocumentInfo documentInfo) { // если требуется отправляем ИОП if (IsNoticeRequired(documentInfo)) { var document = documentInfo.Document; var certificate = _context.Certificate; if (document.NeedReceipt) { UserInput.Information("Отправитель запросил подтверждение получения документа"); if (!UserInput.ChooseYesNo("Отправить извещение о получении?")) return; } Console.Out.WriteLine("Отправляется извещение о получении"); var deliveryConfirmationMessage = _context.MessageFactory.CreateReceipt(message, document, certificate); SendServiceDocument(deliveryConfirmationMessage, "Извещение о получении отправлено"); } else { UserInput.Information("Извещение о получении уже было отправлено"); } }
private void PrintDocumentInfo(FullDocumentInfo fullDocumentInfo) { var document = fullDocumentInfo.Document; var documentType = (DocumentType)document.DocumentTypeEnum.Code; Console.Out.WriteLine(DocumentShortName(fullDocumentInfo)); PrintProperty("Id", document.Id); PrintProperty("Тип", documentType); if (fullDocumentInfo.Status != null) { if (documentType.In(DocumentType.Untyped, DocumentType.WaybillSeller, DocumentType.ActOfWorkSeller, DocumentType.RevocationOffer)) { PrintProperty("Подписание", ((UntypedDocumentFlowStatus)fullDocumentInfo.Status).SignStatus); } else if (documentType == DocumentType.Invoice) { var invoiceDocumentFlowStatus = (InvoiceDocumentFlowStatus)fullDocumentInfo.Status; PrintProperty("Номер", invoiceDocumentFlowStatus.Number); PrintProperty("От", invoiceDocumentFlowStatus.Date); PrintProperty("Сумма", invoiceDocumentFlowStatus.Total); PrintProperty("Статус покупателя", invoiceDocumentFlowStatus.BuyerFlow); PrintProperty("Статус продавца", invoiceDocumentFlowStatus.SellerFlow); } else { // для служебных документов печатаем ParentId PrintProperty("ParentDocumentId", fullDocumentInfo.Document.ParentDocumentId); } } if (fullDocumentInfo.Tags != null && fullDocumentInfo.Tags.Any()) { PrintProperty("Дополнительные статусы(тэги), кол-во", fullDocumentInfo.Tags.Count()); foreach (var tag in fullDocumentInfo.Tags) { PrintProperty("Логин пользователя, создавшего тэг", tag.Login); PrintProperty("Тип тэга", tag.TagType); PrintProperty("Комментарий", tag.Comment); PrintProperty("Дата создания", tag.CreateDate); } } if (fullDocumentInfo.Signs != null) foreach (var sign in fullDocumentInfo.Signs) { var certificate = CheckSignAndGetCertificate(fullDocumentInfo, sign); if (certificate != null) { PrintProperty("Подпись", certificate.GetNameInfo(X509NameType.SimpleName, false)); if (sign.TimeStamp != DateTime.MinValue) PrintProperty("Штамп времени", sign.TimeStamp); else PrintProperty("Штамп времени", "отсутствует"); } } PrintProperty("Имя файла", document.FileName); // PrintProperty("Размер", document.FileSize); if (documentType.In(DocumentType.Invoice, DocumentType.Untyped, DocumentType.WaybillSeller, DocumentType.ActOfWorkSeller, DocumentType.RevocationOffer)) { if (fullDocumentInfo.ServiceDocuments != null) { Console.Out.WriteLine("\tСлужeбные документы {0} шт.", fullDocumentInfo.ServiceDocuments.Length); foreach (var serviceDocument in fullDocumentInfo.ServiceDocuments) Console.Out.WriteLine("\t\t{0} {1}", serviceDocument.FileName, (DocumentType)serviceDocument.DocumentTypeEnum.Code); } if (fullDocumentInfo.RelatedDocuments != null) { Console.Out.WriteLine("\tСвязные документы {0} шт.", fullDocumentInfo.RelatedDocuments.Length); foreach (var relatedDocument in fullDocumentInfo.RelatedDocuments) Console.Out.WriteLine("\t\t{0} {1}", relatedDocument.FileName, (DocumentType)relatedDocument.DocumentTypeEnum.Code); } } }
private void ProcessFormalizedDocument(Message message, FullDocumentInfo documentInfo) { var document = documentInfo.Document; var certificate = _context.Certificate; // отправляем ИОП если требуется if (IsNoticeRequired(documentInfo)) { if (document.NeedReceipt) { UserInput.Information("Отправитель запросил подтверждение получения документа"); if (!UserInput.ChooseYesNo("Отправить извещение о получении?")) return; } Console.Out.WriteLine("Отправляется извещение о получении"); var deliveryConfirmationMessage = _context.MessageFactory.CreateReceipt(message, document, _context.Certificate); SendServiceDocument(deliveryConfirmationMessage, "Извещение о получении отправлено"); } else { UserInput.Information("Извещение о получении уже было отправлено"); } // если ожидается подпись то оформляем ответный титул и подписываем или отказываем в подписи if (IsSignRequired(documentInfo)) { if (UserInput.ChooseYesNo("Отправитель запросил подпись под документом. Подписать документ?")) { var documentType = (DocumentType)document.DocumentTypeEnum.Code; SendServiceDocument( CreateMessage( message.GetRecipientListForSender(_context.CurrentBox), documentType == DocumentType.ActOfWorkSeller, documentType == DocumentType.WaybillSeller, document.Id), "Документ подписан"); } else { // генерируем СД УОУ var text = UserInput.ReadParameter("Текст уточнения:", string.Empty); var amendmentRequestMessage = _context.MessageFactory.CreateAmendmentRequest(message, document, text, certificate); SendServiceDocument(amendmentRequestMessage, "Отправлено уведомление об уточнении"); } } }
private bool IsSignRequired(FullDocumentInfo documentInfo) { var untypedFlowStatus = documentInfo.Status as UntypedDocumentFlowStatus; if (untypedFlowStatus == null) return false; return untypedFlowStatus.SignStatus == DocumentSignStatus.WaitingForSign; }
private bool IsNoticeRequired(FullDocumentInfo documentInfo) { if (!documentInfo.Document.NoticeRequired) return false; var untypedFlowStatus = documentInfo.Status as UntypedDocumentFlowStatus; if (untypedFlowStatus == null) return false; return untypedFlowStatus.DeliveryStatus != DocumentDeliveryStatus.DeliveredToRecipient; }
private string DocumentShortName(FullDocumentInfo fullDocumentInfo) { var document = fullDocumentInfo.Document; var documentType = (DocumentType)document.DocumentTypeEnum.Code; switch (documentType) { case DocumentType.Invoice: var invoiceDocumentFlowStatus = (InvoiceDocumentFlowStatus)fullDocumentInfo.Status; return string.Format("Счет-фактура №{0} от {1}", invoiceDocumentFlowStatus.Number, invoiceDocumentFlowStatus.Date.ToString("dd/MM/yyyy")); case DocumentType.Untyped: return string.Format("{0}", document.FileName); default: return string.Format("{0}", documentType); } }
private void ProcessUntypedDocument(Message message, FullDocumentInfo documentInfo) { var document = documentInfo.Document; var certificate = context.Certificate; // если требуется отправляем ИОП if (IsNoticeRequired(documentInfo)) { if (document.NeedReceipt) { UserInput.Information("Отправитель запросил подтверждение получения документа"); if (!UserInput.ChooseYesNo("Отправить извещение о получении?")) return; } Console.Out.WriteLine("Отправляется извещение о получении"); var deliveryConfirmationMessage = context.MessageFactory.CreateReceipt(message, document, certificate); SendServiceDocument(deliveryConfirmationMessage, "Извещение о получении отправлено"); } else { UserInput.Information("Извещение о получении уже было отправлено"); } // если ожидается подпись то подписываем или отказываем в подписи if (IsSignRequired(documentInfo)) { if (UserInput.ChooseYesNo("Отправитель запросил подпись под документом. Подписать документ?")) { // отправляем подпись под документом EnsureDocumentContentLoaded(document); var signMessage = context.MessageFactory.CreateSign(message, document, certificate); SendServiceDocument(signMessage, "Документ продписан"); } else { // генерируем СД УОУ var text = UserInput.ReadParameter("Текст уточнения:", String.Empty); var amendmentRequestMessage = context.MessageFactory.CreateAmendmentRequest(message, document, text, certificate); SendServiceDocument(amendmentRequestMessage, "Отправлено уведомление об уточнении"); } } }
private void PrintDocumentInfo(FullDocumentInfo fullDocumentInfo) { var document = fullDocumentInfo.Document; Console.Out.WriteLine(DocumentShortName(fullDocumentInfo)); PrintProperty("Id", document.Id); PrintProperty("Тип", document.DocumentType); if (fullDocumentInfo.Status != null) { if (document.DocumentType == DocumentType.Untyped || document.DocumentType == DocumentType.WaybillSeller || document.DocumentType == DocumentType.ActOfWorkSeller) { PrintProperty("Подписание", ((UntypedDocumentFlowStatus)fullDocumentInfo.Status).SignStatus); } else if (document.DocumentType == DocumentType.Invoice) { var invoiceDocumentFlowStatus = (InvoiceDocumentFlowStatus)fullDocumentInfo.Status; PrintProperty("Номер", invoiceDocumentFlowStatus.Number); PrintProperty("От", invoiceDocumentFlowStatus.Date); PrintProperty("Сумма", invoiceDocumentFlowStatus.Total); PrintProperty("Статус покупателя", invoiceDocumentFlowStatus.BuyerFlow); PrintProperty("Статус продавца", invoiceDocumentFlowStatus.SellerFlow); } else { // для служебных документов печатаем ParentId PrintProperty("ParentDocumentId", fullDocumentInfo.Document.ParentDocumentId); } } if (fullDocumentInfo.Signs != null) foreach (var sign in fullDocumentInfo.Signs) { var certificate = CheckSignAndGetCertificate(fullDocumentInfo, sign); if (certificate != null) { PrintProperty("Подпись", certificate.GetNameInfo(X509NameType.SimpleName, false)); if (sign.TimeStamp != DateTime.MinValue) PrintProperty("Штамп времени", sign.TimeStamp); else PrintProperty("Штамп времени", "отсутствует"); } } PrintProperty("Имя файла", document.FileName); // PrintProperty("Размер", document.FileSize); if (document.DocumentType == DocumentType.Invoice || document.DocumentType == DocumentType.Untyped || document.DocumentType == DocumentType.WaybillSeller || document.DocumentType == DocumentType.ActOfWorkSeller) { if (fullDocumentInfo.ServiceDocuments != null) { Console.Out.WriteLine("\tСлужeбные документы {0} шт.", fullDocumentInfo.ServiceDocuments.Length); foreach (var serviceDocument in fullDocumentInfo.ServiceDocuments) Console.Out.WriteLine("\t\t{0} {1}", serviceDocument.FileName, serviceDocument.DocumentType); } if (fullDocumentInfo.RelatedDocuments != null) { Console.Out.WriteLine("\tСвязные документы {0} шт.", fullDocumentInfo.RelatedDocuments.Length); foreach (var relatedDocument in fullDocumentInfo.RelatedDocuments) Console.Out.WriteLine("\t\t{0} {1}", relatedDocument.FileName, relatedDocument.DocumentType); } } }