Exemple #1
0
        /// <summary>
        /// Проверить акт на дубли.
        /// </summary>
        /// <param name="contractStatement">Акт.</param>
        /// <param name="businessUnit">НОР.</param>
        /// <param name="registrationNumber">Рег. номер.</param>
        /// <param name="registrationDate">Дата регистрации.</param>
        /// <param name="counterparty">Контрагент.</param>
        /// <param name="leadingDocument">Ведущий документ.</param>
        /// <returns>Признак дублей.</returns>
        public static bool HaveDuplicates(IContractStatement contractStatement,
                                          Sungero.Company.IBusinessUnit businessUnit,
                                          string registrationNumber,
                                          DateTime?registrationDate,
                                          Sungero.Parties.ICounterparty counterparty,
                                          Docflow.IOfficialDocument leadingDocument)
        {
            if (contractStatement == null ||
                businessUnit == null ||
                string.IsNullOrWhiteSpace(registrationNumber) ||
                registrationDate == null ||
                counterparty == null ||
                leadingDocument == null)
            {
                return(false);
            }

            return(Functions.ContractStatement.Remote.GetDuplicates(contractStatement,
                                                                    businessUnit,
                                                                    registrationNumber,
                                                                    registrationDate,
                                                                    counterparty,
                                                                    leadingDocument)
                   .Any());
        }
 public static void FillContractFromLeadingDocument(Docflow.IOfficialDocument convertedDoc,
                                                    Docflow.IContractualDocumentBase contract)
 {
     if (ContractualDocuments.Is(contract) && IncomingInvoices.Is(convertedDoc))
     {
         IncomingInvoices.As(convertedDoc).Contract = ContractualDocuments.As(contract);
     }
 }
Exemple #3
0
 public static bool IsDocumentVersionReaded(Docflow.IOfficialDocument document, int version)
 {
     return(document.History.GetAll()
            .Where(x => x.VersionNumber == version &&
                   Equals(Users.Current, x.User) &&
                   x.Action == Sungero.CoreEntities.History.Action.Read &&
                   x.Operation == Content.DocumentHistory.Operation.ReadVerBody).Any());
 }
Exemple #4
0
 public static IExchangeDocumentInfo GetIncomingExDocumentInfo(Docflow.IOfficialDocument document)
 {
     if (document.Versions.Any())
     {
         var incomingVersion = document.Versions.OrderBy(v => v.Number).First();
         return(GetAllExDocumentInfos(document).FirstOrDefault(x => x.VersionId == incomingVersion.Id &&
                                                               x.MessageType == MessageType.Incoming));
     }
     return(ExchangeDocumentInfos.Null);
 }
Exemple #5
0
        private static bool IsLocked(Docflow.IOfficialDocument document, CommonLibrary.BaseInputDialogEventArgs x)
        {
            var lockInfo = document != null?Locks.GetLockInfo(document) : null;

            if (lockInfo != null && lockInfo.IsLockedByOther)
            {
                x.AddError(lockInfo.LockedMessage);
                return(true);
            }
            return(false);
        }
Exemple #6
0
        public static bool IsDocumentVersionSignatureValid(Docflow.IOfficialDocument document, int version)
        {
            var documentVersion = document.Versions.FirstOrDefault(x => x.Number == version);

            // Проверяем только согласующую и утверждающую подпись. Не согласовано = отсутствие подписи.
            var signatures           = Signatures.Get(documentVersion).Where(x => x.SignatureType != SignatureType.NotEndorsing);
            var hasAnySignature      = signatures.Any();
            var hasAnyValidSignature = signatures.Any(x => x.IsValid && !x.ValidationErrors.Any());

            return(!hasAnySignature || hasAnyValidSignature);
        }
Exemple #7
0
        public static bool LastVersionSended(Docflow.IOfficialDocument document, ExchangeCore.IBusinessUnitBox box, Parties.ICounterparty counterparty)
        {
            if (document == null || counterparty == null || box == null || !document.HasVersions)
            {
                return(false);
            }

            return(GetAllExDocumentInfos(document)
                   .Any(x =>
                        x.VersionId == document.LastVersion.Id &&
                        x.MessageType == MessageType.Outgoing &&
                        Equals(x.Counterparty, counterparty) &&
                        Equals(x.Box, box)));
        }
Exemple #8
0
        /// <summary>
        /// Проверка, входит ли документ в список редактируемых форматов.
        /// </summary>
        /// <param name="document">Документ.</param>
        /// <returns>True, если входит, иначе False.</returns>
        public virtual bool IsEditableDocumentFormat(Docflow.IOfficialDocument document)
        {
            var whiteList = new List <string>()
            {
                "doc", "docx", "xls", "xlsx", "rtf", "odt", "ods", "txt"
            };

            if (document.AssociatedApplication == null)
            {
                return(false);
            }

            return(whiteList.Contains(document.AssociatedApplication.Extension.ToLower()));
        }
Exemple #9
0
 public static IQueryable <IContractStatement> GetDuplicates(IContractStatement contractStatement,
                                                             Sungero.Company.IBusinessUnit businessUnit,
                                                             string registrationNumber,
                                                             DateTime?registrationDate,
                                                             Sungero.Parties.ICounterparty counterparty,
                                                             Docflow.IOfficialDocument leadingDocument)
 {
     return(ContractStatements.GetAll()
            .Where(l => Equals(contractStatement.DocumentKind, l.DocumentKind))
            .Where(l => Equals(businessUnit, l.BusinessUnit))
            .Where(l => registrationDate == l.RegistrationDate)
            .Where(l => registrationNumber == l.RegistrationNumber)
            .Where(l => Equals(counterparty, l.Counterparty))
            .Where(l => Equals(leadingDocument, l.LeadingDocument))
            .Where(l => !Equals(contractStatement, l)));
 }
Exemple #10
0
        public static List <Parties.ICounterparty> GetDocumentCounterparties(Docflow.IOfficialDocument document)
        {
            if (Docflow.PublicFunctions.OfficialDocument.Remote.CanSendAnswer(document))
            {
                var info = GetIncomingExDocumentInfo(document);
                if (info != null)
                {
                    return new List <Parties.ICounterparty>()
                           {
                               info.Counterparty
                           }
                }
                ;
            }

            return(Docflow.PublicFunctions.OfficialDocument.GetCounterparties(document));
        }
Exemple #11
0
        public static bool LastVersionSended(Docflow.IOfficialDocument document)
        {
            if (document == null || !document.HasVersions)
            {
                return(false);
            }

            var documentSent  = new Enumeration(Constants.Module.Exchange.SendDocument);
            var answerSent    = new Enumeration(Constants.Module.Exchange.SendAnswer);
            var versionNumber = document.LastVersion.Number;

            if (Docflow.AccountingDocumentBases.Is(document) && Docflow.AccountingDocumentBases.As(document).IsFormalized == true)
            {
                return(document.History.GetAll().Any(h => (h.Operation == documentSent || h.Operation == answerSent)));
            }
            return(document.History.GetAll().Any(h => (h.Operation == documentSent || h.Operation == answerSent) && h.VersionNumber == versionNumber));
        }
Exemple #12
0
        /// <summary>
        /// Попытаться отказать контрагенту по первой версии, когда отправляем вторую.
        /// </summary>
        /// <param name="document">Документ.</param>
        /// <param name="party">Контрагент.</param>
        /// <param name="box">Ящик.</param>
        /// <param name="certificate">Сертификат.</param>
        private static void TryRejectCounterpartyVersion(Docflow.IOfficialDocument document, Parties.ICounterparty party,
                                                         ExchangeCore.IBusinessUnitBox box, ICertificate certificate)
        {
            try
            {
                if (document.Versions.Count < 2)
                {
                    return;
                }

                if (certificate != null)
                {
                    SendAmendmentRequest(new List <Docflow.IOfficialDocument>()
                    {
                        document
                    }, party, string.Empty, false, box, certificate, false);
                }
            }
            catch (Exception)
            {
                // Мягкая попытка отправки, не удалось - и не надо.
            }
        }
Exemple #13
0
        public static IExchangeDocumentInfo GetLastDocumentInfo(Docflow.IOfficialDocument document)
        {
            if (document.Versions.Any())
            {
                var infos = GetAllExDocumentInfos(document).ToList();
                if (!infos.Any())
                {
                    return(null);
                }

                // Сортируем версии по номеру.
                var versions = document.Versions.OrderByDescending(s => s.Number).ToList();
                foreach (var version in versions)
                {
                    // Возвращаем версию, по которой последней создана информация.
                    var versionInfo = infos.OrderByDescending(i => i.MessageDate).FirstOrDefault(i => i.VersionId == version.Id);
                    if (versionInfo != null)
                    {
                        return(versionInfo);
                    }
                }
            }
            return(null);
        }
Exemple #14
0
        public virtual bool NeedShowSignRecommendation(bool isElectronicAcquaintance, Docflow.IOfficialDocument document)
        {
            // Проверка актуальна только для черновиков и электронного ознакомления.
            var isDraft = _obj.Status.Value == Status.Draft;

            if (!isDraft || !isElectronicAcquaintance)
            {
                return(false);
            }

            // Нет тела - проверка не нужна.
            if (document == null || !document.HasVersions)
            {
                return(false);
            }

            // Проверить подпись только по белому списку.
            var inWhiteList           = this.IsEditableDocumentFormat(document);
            var hasApprovalSignatures = Signatures.Get(document.LastVersion).Any(x => x.SignatureType == SignatureType.Approval);

            return(!hasApprovalSignatures && inWhiteList);
        }
Exemple #15
0
 /// <summary>
 /// Получить все записи информации о документе обмена.
 /// </summary>
 /// <param name="document">Документ.</param>
 /// <returns>Записи информации.</returns>
 public static IQueryable <IExchangeDocumentInfo> GetAllExDocumentInfos(Docflow.IOfficialDocument document)
 {
     return(ExchangeDocumentInfos.GetAll(x => Equals(x.Document, document)));
 }
Exemple #16
0
        /// <summary>
        /// Отправка ответа контрагенту.
        /// </summary>
        /// <param name="document">Документ, по которому требуется отправка ответа.</param>
        /// <param name="documentInfo">Информация о документе, связанная с коммуникацией с контрагентом.</param>
        /// <param name="addenda">Приложения.</param>
        public static void SendAnswerToCounterparty(Docflow.IOfficialDocument document, Sungero.Exchange.Structures.Module.SendToCounterpartyInfo documentInfo, List <Docflow.IOfficialDocument> addenda)
        {
            var dialog = Dialogs.CreateInputDialog(Resources.SendAnswerToCounterpartyDialogTitle);

            dialog.HelpCode = Constants.Module.HelpCodes.SendAnswerOnDocument;

            var positiveResult         = Resources.SendCounterpartyPositiveResult;
            var amendmentResult        = Resources.SendCounterpartyNegativeResult;
            var invoiceAmendmentResult = Resources.SendCounterpartyRejectResult;

            var allowedResults = new List <string>();

            if (documentInfo.CanSendSignAsAnswer)
            {
                allowedResults.Add(positiveResult);
            }
            if (documentInfo.CanSendInvoiceAmendmentRequestAsAnswer)
            {
                allowedResults.Add(invoiceAmendmentResult);
            }
            if (documentInfo.CanSendAmendmentRequestAsAnswer)
            {
                allowedResults.Add(amendmentResult);
            }

            var formParams  = ((Domain.Shared.IExtendedEntity)document).Params;
            var signAndSend = formParams.ContainsKey(Exchange.PublicConstants.Module.DefaultSignResult) &&
                              (bool)formParams[Exchange.PublicConstants.Module.DefaultSignResult];
            var defaultSignResult = documentInfo.IsSignedByUs || signAndSend == true?
                                    allowedResults.FirstOrDefault() : allowedResults.LastOrDefault();

            var signResult = dialog.AddSelect(Resources.SendCounterpartyResult, true, defaultSignResult)
                             .From(allowedResults.ToArray());

            var counterparty = dialog.AddSelect(Resources.SendCounterpartyReceiver, true, documentInfo.DefaultCounterparty);

            counterparty.IsEnabled = false;

            var box = dialog.AddSelect(Resources.SendCounterpartySender, true, documentInfo.DefaultBox);

            box.IsEnabled = false;

            var users = new List <Sungero.CoreEntities.IUser>();

            if (documentInfo.Certificates.Certificates != null)
            {
                users = documentInfo.Certificates.Certificates.Select(c => c.Owner).ToList();
            }

            var signatureOwner = dialog.AddSelect(Docflow.OfficialDocuments.Info.Properties.OurSignatory.LocalizedName, false, users.FirstOrDefault())
                                 .From(users);

            signatureOwner.IsEnabled = documentInfo.IsSignedByUs;

            var allowedAddenda         = documentInfo.Addenda.Select(a => a.Addendum).ToList();
            var defaultSelectedAddenda = addenda.Intersect(allowedAddenda).ToArray();
            var selectedAddenda        = dialog.AddSelectMany(Resources.SendCounterpartyAddenda, false, defaultSelectedAddenda)
                                         .From(allowedAddenda);

            selectedAddenda.IsEnabled = documentInfo.HasAddendaToSend;

            var comment = dialog.AddMultilineString(Resources.SendCounterpartyComment, false);

            comment.IsEnabled = defaultSignResult != positiveResult;

            var sendButton = dialog.Buttons.AddCustom(Resources.SendCounterpartySendButton);

            dialog.Buttons.Default = sendButton;
            dialog.Buttons.AddCancel();

            var currentUserSelectedCertificate = Certificates.Null;

            if (!documentInfo.IsSignedByUs && !documentInfo.Certificates.MyCertificates.Any())
            {
                Dialogs.NotifyMessage(Resources.NotificationNoCertificates);
                return;
            }

            signResult.SetOnValueChanged(x =>
            {
                if (x.NewValue != x.OldValue)
                {
                    if (x.NewValue != positiveResult)
                    {
                        signatureOwner.Value     = null;
                        signatureOwner.IsEnabled = false;

                        comment.IsEnabled = true;
                    }
                    else
                    {
                        signatureOwner.Value     = users.FirstOrDefault();
                        signatureOwner.IsEnabled = documentInfo.IsSignedByUs;
                        comment.Value            = string.Empty;

                        comment.IsEnabled = false;
                    }
                }
            });

            dialog.SetOnButtonClick(x =>
            {
                if (x.Button == sendButton && x.IsValid)
                {
                    var hasExchangeWithCounterparty = counterparty.Value.ExchangeBoxes
                                                      .Any(c => Equals(c.Box, box.Value) &&
                                                           Equals(c.Status, Parties.CounterpartyExchangeBoxes.Status.Active) &&
                                                           c.IsDefault == true);
                    if (!hasExchangeWithCounterparty)
                    {
                        x.AddError(Exchange.Resources.NoExchangeThroughThisService);
                        return;
                    }

                    if (IsLocked(document, x))
                    {
                        return;
                    }

                    if (comment.Value != null && comment.Value.Length > 1000)
                    {
                        x.AddError(Exchange.ExchangeDocumentProcessingAssignments.Resources.TextOverlong, comment);
                        return;
                    }

                    if (signResult.Value == Resources.SendCounterpartyPositiveResult)
                    {
                        #region Отправка подписи

                        if (signatureOwner.Value == null && documentInfo.IsSignedByUs && !documentInfo.Certificates.CanSign)
                        {
                            x.AddError(Resources.SendCounterpartyCertificateNotSelected);
                            return;
                        }

                        var noSign = signatureOwner.Value == null;
                        if (noSign)
                        {
                            if (!documentInfo.Certificates.CanSign)
                            {
                                x.AddError(Resources.NotificationNoCertificates);
                                return;
                            }

                            var signDialog  = Dialogs.CreateTaskDialog(Resources.SendCounterpartySignAndSendQuestion);
                            var signButtons = signDialog.Buttons.AddCustom(Resources.SendCounterpartySignAndSendButton);
                            signDialog.Buttons.AddCancel();

                            if (signDialog.Show() == signButtons)
                            {
                                try
                                {
                                    if (IsLocked(document, x))
                                    {
                                        return;
                                    }

                                    currentUserSelectedCertificate = GetCurrentUserExchangeCertificate(box.Value, Company.Employees.Current);

                                    List <Docflow.IOfficialDocument> lockedDocuments = new List <Docflow.IOfficialDocument>();
                                    foreach (Docflow.IOfficialDocument docAddendum in selectedAddenda.Value)
                                    {
                                        if (docAddendum.LastVersion != null)
                                        {
                                            var bodyAddendum     = docAddendum.LastVersion.PublicBody;
                                            var lockInfoAddendum = Locks.GetLockInfo(bodyAddendum);
                                            if (lockInfoAddendum != null)
                                            {
                                                if (lockInfoAddendum.IsLockedByOther)
                                                {
                                                    x.AddError(lockInfoAddendum.LockedMessage);
                                                    return;
                                                }
                                                else if (!lockInfoAddendum.IsLocked)
                                                {
                                                    Locks.TryLock(bodyAddendum);
                                                    lockedDocuments.Add(docAddendum);
                                                }
                                            }
                                        }
                                    }

                                    if (currentUserSelectedCertificate == null || !Docflow.PublicFunctions.Module
                                        .ApproveWithAddenda(document, selectedAddenda.Value.ToList(), currentUserSelectedCertificate, null, true, true, string.Empty))
                                    {
                                        UnlockAddenda(lockedDocuments);
                                        x.AddError(Resources.NotificationNoCertificates);
                                        return;
                                    }
                                    UnlockAddenda(lockedDocuments);

                                    signatureOwner.Value      = Users.Current;
                                    documentInfo.Certificates = Functions.Module.Remote.GetDocumentCertificatesToBox(document, box.Value);
                                }
                                catch (Exception ex)
                                {
                                    x.AddError(ex.Message);
                                    return;
                                }
                            }
                            else
                            {
                                return;
                            }
                        }

                        try
                        {
                            var certificate = signatureOwner.Value == null ? null :
                                              documentInfo.Certificates.Certificates.Single(c => Equals(c.Owner, signatureOwner.Value));

                            var documentsToSend = new List <Docflow.IOfficialDocument>()
                            {
                                document
                            };
                            documentsToSend.AddRange(selectedAddenda.Value);
                            Functions.Module.Remote.SendAnswers(documentsToSend, counterparty.Value, box.Value, certificate, false);
                            if (Equals(certificate.Owner, Company.Employees.Current))
                            {
                                Functions.Module.SendDeliveryConfirmation(box.Value, certificate, false);
                            }
                            else
                            {
                                Functions.Module.SendDeliveryConfirmation(box.Value, null, false);
                            }
                        }
                        catch (AppliedCodeException ex)
                        {
                            x.AddError(ex.Message);
                            return;
                        }
                        catch (Exception ex)
                        {
                            Logger.ErrorFormat("Error sending sign: ", ex);
                            x.AddError(Resources.ErrorWhileSendingSignToCounterparty);
                            return;
                        }

                        Dialogs.NotifyMessage(Resources.SendAnswerCounterpartySuccessfully);

                        #endregion
                    }
                    else
                    {
                        #region Отправка отказа в подписании

                        currentUserSelectedCertificate = GetCurrentUserExchangeCertificate(box.Value, Company.Employees.Current);

                        if (currentUserSelectedCertificate != null)
                        {
                            var documents = selectedAddenda.Value.ToList();
                            documents.Add(document);

                            var error = SendAmendmentRequest(documents, counterparty.Value, comment.Value, false, box.Value, currentUserSelectedCertificate, signResult.Value == invoiceAmendmentResult);
                            Functions.Module.SendDeliveryConfirmation(box.Value, currentUserSelectedCertificate, false);
                            if (!string.IsNullOrWhiteSpace(error))
                            {
                                x.AddError(error);
                            }
                            else
                            {
                                Dialogs.NotifyMessage(Resources.SendAnswerCounterpartySuccessfully);
                            }
                        }
                        else
                        {
                            x.AddError(Resources.RejectCertificateNotFound);
                        }

                        #endregion
                    }
                }
            });
            dialog.Show();
        }
Exemple #17
0
 public static IExchangeDocumentInfo GetExDocumentInfoFromVersion(Docflow.IOfficialDocument document, int versionId)
 {
     return(GetAllExDocumentInfos(document).Where(e => e.VersionId == versionId).OrderByDescending(e => e.MessageDate).FirstOrDefault());
 }
Exemple #18
0
        /// <summary>
        /// Отправка последней версии документа контрагенту.
        /// </summary>
        /// <param name="document">Документ для отправки.</param>
        /// <param name="documentInfo">Информация о документе, связанная с коммуникацией с контрагентом.</param>
        /// <param name="service">Сервис обмена.</param>
        /// <param name="addenda">Приложения.</param>
        public static void SendDocumentToCounterparty(Docflow.IOfficialDocument document,
                                                      Sungero.Exchange.Structures.Module.SendToCounterpartyInfo documentInfo,
                                                      ExchangeCore.IExchangeService service,
                                                      List <Docflow.IOfficialDocument> addenda)
        {
            if (!documentInfo.CanApprove && !documentInfo.HasApprovalSignature)
            {
                Dialogs.NotifyMessage(Resources.SendCounterpartyNotApproved);
                return;
            }

            var dialog = Dialogs.CreateInputDialog(Resources.SendCounterpartyDialogTitle);

            dialog.HelpCode = Constants.Module.HelpCodes.SendDocument;

            var counterparty = dialog.AddSelect(Resources.SendCounterpartyReceiver, true, documentInfo.DefaultCounterparty)
                               .From(documentInfo.Counterparties)
                               .Where(x => x.Status == CoreEntities.DatabookEntry.Status.Active);

            var defaultBox = documentInfo.Boxes.FirstOrDefault(x => Equals(x.ExchangeService, service)) ?? documentInfo.DefaultBox;

            var box = dialog.AddSelect(Resources.SendCounterpartySender, true, defaultBox)
                      .From(documentInfo.Boxes)
                      .Where(x => x.Status == CoreEntities.DatabookEntry.Status.Active);

            box.IsEnabled = !(Docflow.AccountingDocumentBases.Is(document) && Docflow.AccountingDocumentBases.As(document).IsFormalized == true);
            var users = documentInfo.Certificates.Certificates.Select(c => c.Owner).ToList();

            var signatureOwner = dialog.AddSelect(Docflow.OfficialDocuments.Info.Properties.OurSignatory.LocalizedName, false, users.FirstOrDefault())
                                 .From(users);

            signatureOwner.IsEnabled = documentInfo.IsSignedByUs;

            var allowedAddenda         = documentInfo.Addenda.Select(a => a.Addendum).ToList();
            var defaultSelectedAddenda = addenda.Intersect(allowedAddenda).ToArray();
            var selectedAddenda        = dialog.AddSelectMany(Resources.SendCounterpartyAddenda, false, defaultSelectedAddenda)
                                         .From(allowedAddenda);

            selectedAddenda.IsEnabled = documentInfo.HasAddendaToSend;

            var needSign = dialog.AddBoolean(Resources.SendCounterpartyNeedSign, false);

            if (Docflow.AccountingDocumentBases.Is(document) && Docflow.AccountingDocumentBases.As(document).IsFormalized == true)
            {
                var accDocument               = Docflow.AccountingDocumentBases.As(document);
                var isSF                      = accDocument.FormalizedFunction == Docflow.AccountingDocumentBase.FormalizedFunction.Schf;
                var isWaybill                 = FinancialArchive.Waybills.Is(document);
                var isContractStatement       = FinancialArchive.ContractStatements.Is(document);
                var isUPD                     = FinancialArchive.UniversalTransferDocuments.Is(document);
                var isDiadoc                  = accDocument.BusinessUnitBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc;
                var isDiadocUPD               = isUPD && isDiadoc;
                var isDiadocContractStatement = isContractStatement && isDiadoc;
                needSign.Value     = isWaybill || isUPD || isContractStatement;
                needSign.IsEnabled = !(isWaybill || isSF || isDiadocUPD || isDiadocContractStatement);
            }
            else
            {
                needSign.Value = Docflow.ContractualDocumentBases.Is(document);
            }

            var comment = dialog.AddMultilineString(Resources.SendCounterpartyComment, false);

            var sendButton = dialog.Buttons.AddCustom(Resources.SendCounterpartySendButton);

            dialog.Buttons.Default = sendButton;
            dialog.Buttons.AddCancel();

            dialog.SetOnRefresh(x =>
            {
                if (x.IsValid && documentInfo.Certificates.CanSign && signatureOwner.Value == null)
                {
                    x.AddInformation(Resources.SendCounterpartySignAndSendHint);
                }

                if (selectedAddenda.Value != null)
                {
                    var exchangeDocumentsSize = selectedAddenda.Value.Select(s => s.LastVersion.Body.Size).Sum() + document.LastVersion.Body.Size;
                    if (exchangeDocumentsSize >= Constants.Module.ExchangeDocumentMaxSize)
                    {
                        x.AddError(Resources.AddendaOversized);
                    }
                }
                if (counterparty.Value != null)
                {
                    var boxes = counterparty.Value.ExchangeBoxes.Where(b => b.Box.Status == ExchangeCore.BusinessUnitBox.Status.Active &&
                                                                       b.Box.ConnectionStatus == ExchangeCore.BusinessUnitBox.ConnectionStatus.Connected &&
                                                                       b.Status == Parties.CounterpartyExchangeBoxes.Status.Active && b.IsDefault == true);
                    if (!boxes.Any())
                    {
                        x.AddError(Resources.BoxesNotFound);
                    }
                }
            });

            counterparty.SetOnValueChanged(x =>
            {
                if (x.NewValue != x.OldValue)
                {
                    var newCounterpartyList = documentInfo.Counterparties;
                    if (x.NewValue != null)
                    {
                        newCounterpartyList = documentInfo.Counterparties.Where(c => c.Equals(x.NewValue)).ToList();
                    }

                    documentInfo.Boxes = Functions.Module.Remote.GetConnectedExchangeBoxesToCounterparty(document, newCounterpartyList);
                    box = box.From(documentInfo.Boxes);

                    // Если ящик не был выбран или был выбран ящик, через который нет обмена с выбранным контрагентом, или был выбран ящик, отличный от Synerdocs,
                    // заполнить поле первым подходящим ящиком.
                    if (box.Value == null || !documentInfo.Boxes.Contains(box.Value) || box.Value.ExchangeService.ExchangeProvider != ExchangeCore.ExchangeService.ExchangeProvider.Synerdocs)
                    {
                        box.Value = documentInfo.Boxes.FirstOrDefault();
                    }
                }
            });

            box.SetOnValueChanged(x =>
            {
                if (x.NewValue != x.OldValue)
                {
                    if (x.NewValue != null)
                    {
                        documentInfo.Certificates = Functions.Module.Remote.GetDocumentCertificatesToBox(document, x.NewValue);
                        documentInfo.IsSignedByUs = documentInfo.Certificates.Certificates.Any();
                    }
                    else
                    {
                        documentInfo.Certificates = Structures.Module.DocumentCertificatesInfo
                                                    .Create(new List <ICertificate>(), false, new List <ICertificate>());
                        documentInfo.IsSignedByUs = false;
                    }

                    users                    = documentInfo.Certificates.Certificates.Select(c => c.Owner).ToList();
                    signatureOwner           = signatureOwner.From(users);
                    signatureOwner.Value     = users.FirstOrDefault();
                    signatureOwner.IsEnabled = documentInfo.IsSignedByUs;
                }
            });

            dialog.SetOnButtonClick(x =>
            {
                if (x.Button == sendButton && x.IsValid)
                {
                    var hasExchangeWithCounterparty = counterparty.Value.ExchangeBoxes
                                                      .Any(c => Equals(c.Box, box.Value) &&
                                                           Equals(c.Status, Parties.CounterpartyExchangeBoxes.Status.Active) &&
                                                           c.IsDefault == true);
                    if (!hasExchangeWithCounterparty)
                    {
                        x.AddError(Exchange.Resources.NoExchangeThroughThisService);
                        return;
                    }

                    if (signatureOwner.Value == null && documentInfo.IsSignedByUs && !documentInfo.Certificates.CanSign)
                    {
                        x.AddError(Resources.SendCounterpartyCertificateNotSelected);
                        return;
                    }

                    if (IsLocked(document, x))
                    {
                        return;
                    }

                    foreach (var addendumDocument in selectedAddenda.Value)
                    {
                        if (IsLocked(addendumDocument, x))
                        {
                            return;
                        }
                    }

                    if (Functions.ExchangeDocumentInfo.Remote.LastVersionSended(document, box.Value, counterparty.Value))
                    {
                        x.AddError(Resources.DocumentIsAlreadySentToCounterparty);
                        return;
                    }

                    var noSign      = signatureOwner.Value == null;
                    var certificate = documentInfo.Certificates.Certificates.FirstOrDefault(c => Equals(c.Owner, signatureOwner.Value));
                    ICertificate certificateToRejectFirstVersion = null;

                    if (noSign)
                    {
                        if (!documentInfo.Certificates.CanSign)
                        {
                            if (selectedAddenda.Value.Any())
                            {
                                x.AddError(Resources.SendCounterpartyWithAddendaWhenDocumentNotSigned);
                            }
                            else
                            {
                                x.AddError(Resources.SendCounterpartyCanNotSign);
                            }
                            return;
                        }

                        var signDialog  = Dialogs.CreateTaskDialog(Resources.SendCounterpartySignAndSendQuestion);
                        var signButtons = signDialog.Buttons.AddCustom(Resources.SendCounterpartySignAndSendButton);
                        signDialog.Buttons.AddCancel();

                        if (signDialog.Show() == signButtons)
                        {
                            try
                            {
                                if (IsLocked(document, x))
                                {
                                    return;
                                }

                                certificate = GetCurrentUserExchangeCertificate(box.Value, Company.Employees.Current);

                                certificateToRejectFirstVersion = certificate;

                                var selectedAddendaList = new List <Docflow.IOfficialDocument>();
                                if (selectedAddenda.Value != null)
                                {
                                    selectedAddendaList = selectedAddenda.Value.ToList();
                                }

                                if (certificate == null || !Docflow.PublicFunctions.Module
                                    .ApproveWithAddenda(document, selectedAddendaList, certificate, null, true, true, string.Empty))
                                {
                                    x.AddError(Resources.SendCounterpartyCanNotSign);
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                x.AddError(ex.Message);
                                return;
                            }
                        }
                        else
                        {
                            return;
                        }
                    }

                    try
                    {
                        Functions.Module.Remote.SendDocuments(document, selectedAddenda.Value.ToList(), counterparty.Value, box.Value,
                                                              certificate, needSign.Value.Value, comment.Value);
                        if (Equals(certificate.Owner, Company.Employees.Current))
                        {
                            Functions.Module.SendDeliveryConfirmation(box.Value, certificate, false);
                        }
                        else
                        {
                            Functions.Module.SendDeliveryConfirmation(box.Value, null, false);
                        }
                    }
                    catch (AppliedCodeException ex)
                    {
                        x.AddError(ex.Message);
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Error sending document: ", ex);
                        x.AddError(Resources.ErrorWhileSendingDocToCounterparty);
                        return;
                    }

                    if (documentInfo.NeedRejectFirstVersion)
                    {
                        if (certificateToRejectFirstVersion == null)
                        {
                            certificateToRejectFirstVersion = GetCurrentUserExchangeCertificate(box.Value, Company.Employees.Current);
                        }

                        TryRejectCounterpartyVersion(document, counterparty.Value, box.Value, certificateToRejectFirstVersion);
                    }

                    var addendaToReject =
                        documentInfo.Addenda
                        .Where(a => a.NeedRejectFirstVersion)
                        .Select(a => a.Addendum)
                        .Where(a => selectedAddenda.Value.Contains(a))
                        .ToList();
                    foreach (var addendum in addendaToReject)
                    {
                        if (certificateToRejectFirstVersion == null)
                        {
                            certificateToRejectFirstVersion = GetCurrentUserExchangeCertificate(box.Value, Company.Employees.Current);
                        }

                        TryRejectCounterpartyVersion(addendum, counterparty.Value, box.Value, certificateToRejectFirstVersion);
                    }

                    Dialogs.NotifyMessage(Resources.SendCounterpartySuccessfully);
                }
            });
            dialog.Show();
        }
Exemple #19
0
        public static void SendResultToCounterparty(Docflow.IOfficialDocument document,
                                                    ExchangeCore.IExchangeService service,
                                                    List <Docflow.IOfficialDocument> addenda)
        {
            var isNonformalizedTaxInvoice = false;

            if (FinancialArchive.IncomingTaxInvoices.Is(document) || FinancialArchive.OutgoingTaxInvoices.Is(document))
            {
                isNonformalizedTaxInvoice = Docflow.AccountingDocumentBases.As(document).IsFormalized != true;
            }

            if (isNonformalizedTaxInvoice)
            {
                Dialogs.NotifyMessage(Resources.NonFormalizedTaxInvoiceSendingError);
                return;
            }

            var lockInfo = document != null?Locks.GetLockInfo(document) : null;

            if (lockInfo != null && lockInfo.IsLockedByOther)
            {
                Dialogs.NotifyMessage(lockInfo.LockedMessage);
                return;
            }

            var documentInfo = Functions.Module.Remote.GetInfoForSendToCounterparty(document);

            if (documentInfo.HasError)
            {
                Dialogs.NotifyMessage(documentInfo.Error);
                return;
            }

            if (documentInfo.AnswerIsSent)
            {
                Dialogs.NotifyMessage(Resources.AnswerIsAlreadySent);
                return;
            }

            if (document.LastVersion.Body.Size >= Constants.Module.ExchangeDocumentMaxSize)
            {
                Dialogs.NotifyMessage(Resources.DocumentOversized);
                return;
            }
            var isForcedLocked = false;

            if (!lockInfo.IsLocked)
            {
                isForcedLocked = Locks.TryLock(document);
            }
            if (!lockInfo.IsLocked && !isForcedLocked)
            {
                var lockInfoError = document != null?Locks.GetLockInfo(document) : null;

                Dialogs.NotifyMessage(lockInfoError.LockedMessage);
                return;
            }

            if (documentInfo.IsSignedByCounterparty)
            {
                SendAnswerToCounterparty(document, documentInfo, addenda);
            }
            else
            {
                SendDocumentToCounterparty(document, documentInfo, service, addenda);
            }

            if (isForcedLocked)
            {
                Locks.Unlock(document);
            }
        }
Exemple #20
0
 /// <summary>
 /// Проверить документ на вхождение в обязательную группу вложений.
 /// </summary>
 /// <param name="document">Документ.</param>
 /// <returns>True, если документ обязателен.</returns>
 public virtual bool DocumentInRequredGroup(Docflow.IOfficialDocument document)
 {
     return(_obj.DocumentsGroup.OfficialDocuments.Any(d => Equals(d, document)));
 }
Exemple #21
0
 /// <summary>
 /// Проверить, относится ли документ к счетам-фактурам или УПД.
 /// </summary>
 /// <param name="document">Документ.</param>
 /// <returns>Признак того, является ли документ счетом-фактурой или УПД.</returns>
 /// <remarks>По возможности надо пользоваться сервисными признаками, для накладных из Диадока - врёт.</remarks>
 public static bool IsInvoiceFlowDocument(Docflow.IOfficialDocument document)
 {
     return(FinancialArchive.UniversalTransferDocuments.Is(document) ||
            FinancialArchive.IncomingTaxInvoices.Is(document) ||
            FinancialArchive.OutgoingTaxInvoices.Is(document));
 }
Exemple #22
0
 public static void SendResultToCounterparty(Docflow.IOfficialDocument document)
 {
     SendResultToCounterparty(document, null, new List <Docflow.IOfficialDocument>());
 }