Beispiel #1
0
        public static string SendAmendmentRequest(List <Docflow.IOfficialDocument> documents, Parties.ICounterparty receiver, string note, bool throwError,
                                                  ExchangeCore.IBoxBase box, ICertificate certificate, bool isInvoiceAmendmentRequest)
        {
            if (!documents.Any())
            {
                return(string.Empty);
            }

            var error       = Resources.AmendmentRequestError;
            var serviceDocs = new List <Structures.Module.ReglamentDocumentWithCertificate>();

            try
            {
                serviceDocs.AddRange(Functions.Module.Remote.GenerateAmendmentRequestDocuments(documents.ToList(), box, note, throwError, certificate, isInvoiceAmendmentRequest));
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(ex.Message);
            }

            if (!serviceDocs.Any())
            {
                return(Resources.AllAnswersIsAlreadySent);
            }

            try
            {
                var signs = ExternalSignatures.Sign(certificate, serviceDocs.ToDictionary(d => d.ParentDocumentId, d => d.Content));

                foreach (var doc in serviceDocs)
                {
                    doc.Signature = signs[doc.ParentDocumentId];
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(Resources.DocumentEndorseError);
            }

            try
            {
                var serviceCounterpartyId = string.Empty;
                var externalDocumentInfo  = Functions.ExchangeDocumentInfo.Remote.GetIncomingExDocumentInfo(documents.FirstOrDefault());
                if (externalDocumentInfo != null)
                {
                    serviceCounterpartyId = externalDocumentInfo.ServiceCounterpartyId;
                }

                Functions.Module.Remote.SendAmendmentRequest(serviceDocs, receiver, box, note);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(error, ex);
                return(string.Format("{0}: {1}", error, ex.Message.ToString().ToLower()));
            }

            return(string.Empty);
        }
Beispiel #2
0
        /// <summary>
        /// Получить сертификат сервиса обмена для текущего сотрудника, используя системный диалог выбора сертификата.
        /// </summary>
        /// <param name="box">Абонентский ящик.</param>
        /// <param name="employee">Сотрудник.</param>
        /// <returns>Сертификат.</returns>
        public static ICertificate GetCurrentUserExchangeCertificate(ExchangeCore.IBoxBase box, Company.IEmployee employee)
        {
            var businessUnitBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
            var certificates    = businessUnitBox.HasExchangeServiceCertificates == true
        ? businessUnitBox.ExchangeServiceCertificates.Where(x => Equals(x.Certificate.Owner, employee) && x.Certificate.Enabled == true).Select(x => x.Certificate)
        : Certificates.GetAllCached().Where(x => Equals(x.Owner, employee) && x.Enabled == true).AsEnumerable();

            certificates = certificates.GroupBy(x => x.Thumbprint).Select(x => x.First());

            if (certificates.Count() > 1)
            {
                return(certificates.ShowSelectCertificate());
            }

            return(certificates.FirstOrDefault());
        }
Beispiel #3
0
 public virtual ICertificate GetUserExchangeCertificate(ExchangeCore.IBoxBase box, Company.IEmployee employee)
 {
     return(GetCurrentUserExchangeCertificate(box, employee));
 }
Beispiel #4
0
        public virtual string SendDeliveryConfirmation(ExchangeCore.IBoxBase box,
                                                       ICertificate certificate,
                                                       bool bulkMode)
        {
            var partSize         = 25;
            var skip             = 0;
            var isSendJobEnabled = PublicFunctions.Module.Remote.IsJobEnabled(PublicConstants.Module.SendSignedReceiptNotificationsId);
            var rootBox          = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);
            var documentInfos    = Functions.Module.Remote.GetDocumentInfosWithoutReceiptNotificationPart(rootBox, skip, partSize, false);

            if (!documentInfos.Any())
            {
                return(string.Empty);
            }

            if (certificate == null)
            {
                certificate = Functions.Module.GetCurrentUserExchangeCertificate(box, Company.Employees.Current);
            }

            var isJobEnabled = PublicFunctions.Module.Remote.IsJobEnabled(Constants.Module.CreateReceiptNotifications);

            // Если в системе настроена автоматическая схема работы с иопами, и выбранный сертификат не попадает под неё - не делаем ничего.
            if (!bulkMode &&
                rootBox.CertificateReceiptNotifications != null &&
                !Equals(rootBox.CertificateReceiptNotifications, certificate) &&
                isJobEnabled)
            {
                return(string.Empty);
            }

            while (documentInfos.Any())
            {
                // Если bulkMode выключен - разрешаем только один прогон.
                if (!bulkMode && skip >= partSize)
                {
                    break;
                }

                var serviceDocs = new List <Structures.Module.ReglamentDocumentWithCertificate>();
                var error       = Resources.DeliveryConfirmationError;
                try
                {
                    serviceDocs = Functions.Module.Remote.GetGeneratedDeliveryConfirmationDocuments(documentInfos, rootBox, certificate, bulkMode);

                    // Если снаружи пришел параметр, что генерировать не надо, но сгенерированных совсем нет - генерируем хотя бы одну пачку ИОП.
                    // Так на небольших объемах спасаемся от лишней задачки на отправку ИОП.
                    if (!bulkMode && (!serviceDocs.Any() || !isJobEnabled))
                    {
                        serviceDocs = Functions.Module.Remote.GetGeneratedDeliveryConfirmationDocuments(documentInfos, rootBox, certificate, true);
                    }

                    // Проставляем NotRequired в двух случаях:
                    // 1. Это массовая обработка и ИОПы не сгенерировались.
                    // 2. Это единичная обработка, ФП отключен, а ИОПы пытались генерироваться, но не сгенерировались.
                    var documentsToFix = documentInfos.Where(x => !serviceDocs.Any(s => Equals(s.LinkedDocument, x.Document))).ToList();
                    if (documentsToFix.Any() && (bulkMode == true || !bulkMode && !isJobEnabled))
                    {
                        Functions.Module.Remote.FixReceiptNotification(documentsToFix, string.Empty);
                    }

                    if (!serviceDocs.Any())
                    {
                        skip         += partSize;
                        documentInfos = Functions.Module.Remote.GetDocumentInfosWithoutReceiptNotificationPart(rootBox, skip, partSize, false);
                        continue;
                    }
                    var documentsToSign = serviceDocs.Where(d => d.Signature == null).ToList();

                    try
                    {
                        Logger.DebugFormat("Try sign {0} documents", documentsToSign.Count());
                        var signs = ExternalSignatures.Sign(certificate, documentsToSign.ToDictionary(d => d.ParentDocumentId, d => d.Content));
                        Logger.DebugFormat("Sign {0} documents", signs.Count());
                        foreach (var document in documentsToSign)
                        {
                            Logger.DebugFormat("Get signatory for parent document id {0}", document.ParentDocumentId);
                            document.Signature = signs[document.ParentDocumentId];
                            Logger.Debug(string.Format("Sign receipt notification with ExchangeDocumentInfoId = {0}, DocumentType = {1}, ServiceCounterpartyId = {2}," +
                                                       " ParentDocumentId = {3} LinkedDocumentId = {4}, ServiceMessageId = {5}",
                                                       document.Info.Id, document.ReglamentDocumentType, document.ServiceCounterpartyId, document.ParentDocumentId,
                                                       document.LinkedDocument.Id, document.ServiceMessageId));
                        }

                        if (isSendJobEnabled)
                        {
                            Functions.Module.Remote.SaveDeliveryConfirmationSigns(documentsToSign);
                        }
                    }
                    catch (Sungero.Domain.Shared.Exceptions.EntitySigningException ex)
                    {
                        Logger.ErrorFormat(error, ex);
                        return(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat(error, ex);
                        return(Resources.DocumentEndorseError);
                    }

                    if (!isSendJobEnabled)
                    {
                        Functions.Module.Remote.SendDeliveryConfirmation(serviceDocs, rootBox);
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat(error, ex);
                    return(string.Format("{0}: {1}", error, ex.Message.ToString().ToLower()));
                }

                skip         += partSize;
                documentInfos = Functions.Module.Remote.GetDocumentInfosWithoutReceiptNotificationPart(rootBox, skip, partSize, false);
            }

            return(string.Empty);
        }
Beispiel #5
0
        public static IExchangeDocumentInfo GetExDocumentInfoByExternalId(ExchangeCore.IBoxBase box, string serviceId)
        {
            var rootBox = ExchangeCore.PublicFunctions.BoxBase.GetRootBox(box);

            return(ExchangeDocumentInfos.GetAll().OrderByDescending(x => x.Id).FirstOrDefault(x => Equals(x.RootBox, rootBox) && x.ServiceDocumentId == serviceId));
        }