Пример #1
0
 public MessagePatchToPost PatchTorg12(ReceiptAttachment receipattachment)
 {
     return(new MessagePatchToPost {
         BoxId = BoxId,
         MessageId = Entity.DocumentInfo.MessageId,
         XmlTorg12BuyerTitles = { receipattachment }
     });
 }
        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);
            }
        }
Пример #3
0
        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}");
        }
Пример #4
0
        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);
            }
        }