private void ProcessMessage(Message msg) { var patch = new MessagePatchToPost { BoxId = ConsoleContext.CurrentBoxId, MessageId = msg.MessageId, }; var attachments = msg.Entities.Where(e => e.EntityType == EntityType.Attachment && e.AttachmentType != AttachmentType.AttachmentComment).ToArray(); var signatures = attachments .Where(e => IsNeedSendSignature(msg, e) && AskAboutSignatureSending(e)) .Select(e => GenerateRequestedSignature(msg.MessageId, e)); patch.Signatures.AddRange(signatures); var receipts = attachments .Where(e => IsNeedSendReceipt(msg, e) && AskAboutReceiptSending(e)) .Select(e => GenerateNewReceipt(msg.MessageId, e)); patch.Receipts.AddRange(receipts); var correctionRequests = attachments .Where(e => IsNeedSendCorrectionRequest(msg, e) && AskAboutCorrectionRequestSending(e)) .Select(e => GenerateNewCorrectionRequest(msg.MessageId, e)); patch.CorrectionRequests.AddRange(correctionRequests); if (patch.CorrectionRequests.Count > 0 || patch.Receipts.Count > 0 || patch.Signatures.Count > 0) { var sentPatch = ConsoleContext.DiadocApi.PostMessagePatch(ConsoleContext.CurrentToken, patch); System.Console.WriteLine("Было отправлено следующее сообщение:"); sentPatch.WriteToConsole(); } }
public Task <MessagePatch> PostMessagePatchAsync(string authToken, MessagePatchToPost patch, string operationId = null) { var qsb = new PathAndQueryBuilder("/V3/PostMessagePatch"); qsb.AddParameter("operationId", operationId); return(PerformHttpRequestAsync <MessagePatchToPost, MessagePatch>(authToken, qsb.BuildPathAndQuery(), patch)); }
public MessagePatchToPost Patch(params ReceiptAttachment[] receipattachments) { var msg = new MessagePatchToPost { BoxId = BoxId, MessageId = Entity.DocumentInfo.MessageId }; msg.Receipts.AddRange(receipattachments); return(msg); }
public MessagePatch PostMessagePatch(string authToken, MessagePatchToPost patch, string operationId = null) { if (authToken == null) { throw new ArgumentNullException("authToken"); } if (patch == null) { throw new ArgumentNullException("patch"); } return(diadocHttpApi.PostMessagePatch(authToken, patch, operationId)); }
public void OutBoundInvoices(List <Message> msgs) { var invoicesReq = msgs.Where(x => x.Entities[0].AttachmentType == AttachmentType.Invoice); foreach (var msg in invoicesReq) { Entity invoice = msg.Entities.FirstOrDefault(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.Invoice && i.DocumentInfo.RevocationStatus == RevocationStatus.RevocationStatusNone); if (invoice == null) { continue; } Entity invoiceReciept = msg.Entities.FirstOrDefault(i => i.ParentEntityId == invoice.EntityId && i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.InvoiceConfirmation); GeneratedFile invoiceReceipt = api.GenerateInvoiceDocumentReceiptXml( token, box.BoxId, invoice.DocumentInfo.MessageId, invoiceReciept.EntityId, signers.First()); SignedContent signContentInvoiceReciept = new SignedContent(); signContentInvoiceReciept.Content = invoiceReceipt.Content; signContentInvoiceReciept.SignWithTestSignature = true; ReceiptAttachment receiptInvoice = new ReceiptAttachment { ParentEntityId = invoiceReciept.EntityId, SignedContent = signContentInvoiceReciept }; var patch = new MessagePatchToPost { BoxId = box.BoxId, MessageId = invoice.DocumentInfo.MessageId }; patch.AddReceipt(receiptInvoice); api.PostMessagePatch(token, patch); Thread.Sleep(1000); } }
public void Revocation(Message revocation) { RevocationRequestInfo revinfo = new RevocationRequestInfo(); revinfo.Comment = "АННУЛИРОВНИЕ"; revinfo.Signer = signers.First(); var document = revocation.Entities.First(); MessagePatchToPost patch = new MessagePatchToPost() { BoxId = box.BoxId, MessageId = revocation.MessageId }; GeneratedFile revocationXml = api.GenerateRevocationRequestXml( token, box.BoxId, revocation.MessageId, document.EntityId, revinfo); SignedContent revocSignContent = new SignedContent(); revocSignContent.Content = revocationXml.Content; revocSignContent.SignWithTestSignature = true; RevocationRequestAttachment revattch = new RevocationRequestAttachment(); revattch.ParentEntityId = document.EntityId; revattch.SignedContent = revocSignContent; patch.AddRevocationRequestAttachment(revattch); api.PostMessagePatch(token, patch); }
public MessagePatch PostMessagePatch(string authToken, MessagePatchToPost patch, string operationId = null) { var queryString = string.Format("/V3/PostMessagePatch?operationId={0}", operationId); return(PerformHttpRequest <MessagePatchToPost, MessagePatch>(authToken, queryString, patch)); }
public static void RunSample() { Console.WriteLine("Пример добавления извещения о получении к документу"); Console.WriteLine("==================================================="); // Для использования API Диадока требуются: // 1. Крипто-API, предоставляемое операционной системой. Для систем на ОС Windows используйте класс WinApiCrypt. // 2. Экземпляр класса DiadocApi, проксирующий работу с Диадоком. var crypt = new WinApiCrypt(); var diadocApi = new DiadocApi( Constants.DefaultClientId, Constants.DefaultApiUrl, crypt); // Авторизуемся в Диадоке. В этом примере используем авторизацию через логин-пароль: var authToken = diadocApi.Authenticate(Constants.DefaultLogin, Constants.DefaultPassword); // Также можно использовать авторизацию по сертификату, она описана в примере Authenticate.cs // Поищем в ящике документы, для которых нужно создать и подписать извещение о получении (он же ИоП). // Это можно сделать несколькими способами. Один из вариантов — через фильтрацию методом GetDocuments var documentList = diadocApi.GetDocuments( authToken, new DocumentsFilter { // Если вы успешно выполняли пример из PostUniversalTransferDocument820.cs, // в качестве ящика можно подставить ящик получателя BoxId = BoxId, FilterCategory = "Any.InboundHaveToCreateReceipt" // этот фильтр читается так: входящий документ любого типа, для которого нужно создать ИоП (на любую сущность) }); // В зависимости от документооборота, ИоПы могут быть и на другие сущности: // например, при работе с счетом-фактурой требуется отправить ИоП на подтверждение оператора ЭДО. // Подробнее о всех сущностях можно прочитать в документации: // http://api-docs.diadoc.ru/ru/latest/http/GenerateReceiptXml.html // http://api-docs.diadoc.ru/ru/latest/howto/example_receive_invoice.html // Поэтому для примера из выборки возьмём первый подходящий документ, для которого нет ИоПа только к титулу отправителя: string messageId = null; string documentId = null; foreach (var document in documentList.Documents) { var message = diadocApi.GetMessage(authToken, BoxId, document.MessageId); if (!HasReceiptForAttachment(message, document.EntityId)) { messageId = document.MessageId; documentId = document.EntityId; break; } } if (messageId == null && documentId == null) { Console.WriteLine("Подходящих документов нет, завершаем работу примера."); return; } Console.WriteLine($"Берём документ с идентификаторами MessageId={messageId}, EntityId={documentId}"); // Теперь приступим к созданию самого извещения о получении. // Это — технологический документ в формате XML. // Самый простой способ получить его: использовать соответствующий метод генерации Console.WriteLine("Создаём извещение о получении..."); var generatedReceipt = diadocApi.GenerateReceiptXml( authToken, BoxId, messageId, documentId, // здесь указываем идентификатор титула, т.к. мы создаём ИоП именно к нему new Signer { SignerDetails = new SignerDetails { FirstName = "Иван", Patronymic = "Иванович", Surname = "Иванов", Inn = "7750370238", JobTitle = "директор" } }); Console.WriteLine("Извещение о получении сгенерировано."); // ИоП, как и любой документ, также должен быть подписан. Создаём к нему подпись Console.WriteLine("Создаём подпись..."); var content = generatedReceipt.Content; var certificate = new X509Certificate2(File.ReadAllBytes(Constants.CertificatePath)); var signature = crypt.Sign(content, certificate.RawData); Console.WriteLine("Создана подпись к извещению о получении."); // Теперь мы готовы к отправке ИоПа. Делается это через метод PostMessagePatch var messagePatchToPost = new MessagePatchToPost { BoxId = BoxId, MessageId = messageId }; var receiptAttachment = new ReceiptAttachment { ParentEntityId = documentId, // наш ИоП будет относиться к документу, поэтому явно показываем, к какой сущности мы создаем ИоП SignedContent = new SignedContent { Content = content, Signature = signature } }; messagePatchToPost.Receipts.Add(receiptAttachment); var response = diadocApi.PostMessagePatch(authToken, messagePatchToPost); Console.WriteLine("Извещение о получении было успешно загружено."); var receipt = response.Entities.First( e => e.ParentEntityId == documentId && (e.AttachmentType == AttachmentType.Receipt || e.AttachmentType == AttachmentType.InvoiceReceipt)); Console.WriteLine($"Идентификатор: {receipt.EntityId}"); }
public async Task Save() { try { BeginAction(); MessagePatchToPost patch = null; Signer signer = GetSigner(); if (ReqRevocationSign) { Entity revocReq = Payload.Message.Entities.FirstOrDefault(x => x.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.RevocationRequest); patch = Payload.Patch(); DocumentSignature acceptSignature = new DocumentSignature(); acceptSignature.IsApprovementSignature = true; acceptSignature.ParentEntityId = revocReq.EntityId; byte[] sign = null; if (!TrySign(revocReq.Content.Data, out sign)) { throw new Exception("Ошибка подписи документа TrySign"); } if (Settings.Value.DebugUseTestSign) { acceptSignature.SignWithTestSignature = true; } acceptSignature.Signature = sign; patch.AddSignature(acceptSignature); await Async(x => Payload.Api.PostMessagePatch(x, patch)); } else { if (Payload.Entity.AttachmentType == AttachmentType.Nonformalized) { patch = Payload.Patch(); byte[] sign = null; if (!TrySign(Payload.Entity.Content.Data, out sign)) { throw new Exception("Ошибка подписи документа TrySign"); } var signature = new DocumentSignature { ParentEntityId = Payload.Entity.EntityId, Signature = sign }; if (Settings.Value.DebugUseTestSign) { signature.SignWithTestSignature = true; } patch.AddSignature(signature); await Async(x => Payload.Api.PostMessagePatch(x, patch)); } else if (Payload.Entity.AttachmentType == AttachmentType.XmlTorg12) { if (SaveData.Value) { SignTorg12Autosave autosave = new SignTorg12Autosave(); autosave.SignerJobTitle = RcvJobTitle.Value; if (LikeReciever.Value) { autosave.LikeReciever = true; } else { autosave.AcptFirstName = AcptFirstName.Value; autosave.AcptSurename = AcptSurename.Value; autosave.AcptPatronimic = AcptPatronimic.Value; autosave.AcptJobTitle = AcptJobTitle.Value; } if (ByAttorney.Value) { autosave.ByAttorney = true; autosave.AtrNum = AtrNum.Value; autosave.AtrDate = AtrDate.Value.Value; autosave.AtrOrganization = AtrOrganization.Value; autosave.AtrJobTitle = AtrJobTitle.Value; autosave.AtrSurename = AtrSurename.Value; autosave.AtrFirstName = AtrFirstName.Value; autosave.AtrPatronymic = AtrPatronymic.Value; autosave.AtrAddInfo = AtrAddInfo.Value; } autosave.Comment = Comment.Value; Session.Save(autosave); for (int i = autosave_max - 1; i < SavedData.Value.Count; i++) { Session.Delete(SavedData.Value[i]); } } Official recived = GetRevicedOfficial(); Official accepted = GetAcceptetOfficial(); Attorney attorney = GetAttorney(); var inf = new Torg12BuyerTitleInfo() { ReceivedBy = recived, //лицо, получившее груз signer AcceptedBy = accepted, //лицо, принявшее груз Attorney = attorney, AdditionalInfo = Comment, ShipmentReceiptDate = RcvDate.Value.ToString("dd.MM.yyyy"), Signer = signer }; GeneratedFile torg12XmlForBuyer = await Async((x) => Payload.Api.GenerateTorg12XmlForBuyer( x, inf, Payload.BoxId, Payload.Entity.DocumentInfo.MessageId, Payload.Entity.DocumentInfo.EntityId)); SignedContent signContent = new SignedContent(); signContent.Content = torg12XmlForBuyer.Content; if (!TrySign(signContent)) { throw new Exception("Ошибка подписи документа TrySign"); } ReceiptAttachment receipt = new ReceiptAttachment { ParentEntityId = Payload.Entity.DocumentInfo.EntityId, SignedContent = signContent }; patch = Payload.PatchTorg12(receipt); await Async(x => Payload.Api.PostMessagePatch(x, patch)); Log.Info($"Документ {patch.MessageId} успешно подписан"); } else if (Payload.Entity.AttachmentType == AttachmentType.Invoice) { Entity invoice = Payload.Message.Entities.First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.Invoice); GeneratedFile invoiceReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml( x, Payload.BoxId, Payload.Entity.DocumentInfo.MessageId, invoice.EntityId, signer)); SignedContent signContentInvoiceReciept = new SignedContent(); signContentInvoiceReciept.Content = invoiceReceipt.Content; if (!TrySign(signContentInvoiceReciept)) { throw new Exception("Ошибка подписи документа TrySign"); } ReceiptAttachment receiptInvoice = new ReceiptAttachment { ParentEntityId = invoice.EntityId, SignedContent = signContentInvoiceReciept }; Entity invoiceConfirmation = Payload.Message.Entities.OrderBy(x => x.CreationTime).First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.InvoiceConfirmation); GeneratedFile invoiceConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml( x, Payload.BoxId, Payload.Entity.DocumentInfo.MessageId, invoiceConfirmation.EntityId, signer)); SignedContent signContentInvoiceConfirmationReciept = new SignedContent(); signContentInvoiceConfirmationReciept.Content = invoiceReceipt.Content; if (!TrySign(signContentInvoiceConfirmationReciept)) { throw new Exception("Ошибка подписи документа TrySign"); } ReceiptAttachment invoiceConfirmationreceipt = new ReceiptAttachment { ParentEntityId = invoiceConfirmation.EntityId, SignedContent = signContentInvoiceConfirmationReciept }; patch = Payload.Patch(receiptInvoice, invoiceConfirmationreceipt); await Async(x => Payload.Api.PostMessagePatch(x, patch)); Log.Info($"Документ {patch.MessageId} receiptInvoice, invoiceConfirmationreceipt отправлены"); Entity invoiceDateConfirmation = await Async((x) => { Message msg = null; Entity dateConfirm = null; int breaker = 0; do { msg = Payload.Api.GetMessage(Payload.Token, Payload.BoxId, Payload.Entity.DocumentInfo.MessageId, Payload.Entity.EntityId); dateConfirm = GetDateConfirmationStep7(msg); breaker++; TaskEx.Delay(500).Wait(); }while (dateConfirm == null && breaker < 10); if (dateConfirm == null) { throw new TimeoutException("Превышено время ожидания ответа, попробуйте повторить позднее."); } LastPatchStamp = msg.LastPatchTimestamp; return(dateConfirm); }); GeneratedFile invoiceOperConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml( x, Payload.BoxId, Payload.Entity.DocumentInfo.MessageId, invoiceDateConfirmation.EntityId, signer)); SignedContent signContentOperInvoiceConfrmReciept = new SignedContent(); signContentOperInvoiceConfrmReciept.Content = invoiceOperConfirmationReceipt.Content; if (!TrySign(signContentOperInvoiceConfrmReciept)) { throw new Exception("Ошибка подписи документа TrySign"); } ReceiptAttachment receipt = new ReceiptAttachment { ParentEntityId = invoiceDateConfirmation.EntityId, SignedContent = signContentOperInvoiceConfrmReciept }; patch = Payload.Patch(receipt); await Async(x => Payload.Api.PostMessagePatch(x, patch)); Log.Info($"Документ {patch.MessageId} invoiceDateConfirmation отправлен"); } } await EndAction(); } catch (Exception e) { var error = ErrorHelper.TranslateException(e) ?? "Не удалось выполнить операцию, попробуйте повторить позднее."; Manager.Warning(error); Log.Error(error, e); await EndAction(false); } }