Exemple #1
0
        /// <summary>
        /// Создать задачу на обработку приглашения к эл. обмену от контрагента.
        /// </summary>
        /// <param name="counterparty">Контрагент.</param>
        /// <param name="box">Абонентский ящик.</param>
        /// <param name="organizationId">Ид контрагента в сервисе обмена.</param>
        /// <param name="comment">Комментарий приглашения.</param>
        /// <returns>Задача на обработку приглашения к эл. обмену от контрагента.</returns>
        public static IIncomingInvitationTask Create(Parties.ICounterparty counterparty, IBusinessUnitBox box, string organizationId, string comment)
        {
            var counterpartyBox = counterparty.ExchangeBoxes.Where(x => Equals(x.OrganizationId, organizationId)).Select(o => o.CounterpartyBox).FirstOrDefault();
            var invitationTask  = IncomingInvitationTasks.Create();
            var subject         = IncomingInvitationTasks.Resources.TaskSubjectFormat(counterparty.Name, box.BusinessUnit.Name, box.ExchangeService.Name);

            invitationTask.Subject    = Exchange.PublicFunctions.Module.CutText(subject, invitationTask.Info.Properties.Subject.Length);
            invitationTask.ActiveText = IncomingInvitationTasks.Resources.TaskActiveTextFormat(counterparty.Name, box.BusinessUnit.Name, box.ExchangeService.Name);

            if (!string.IsNullOrWhiteSpace(counterpartyBox))
            {
                invitationTask.ActiveText += Environment.NewLine;
                invitationTask.ActiveText += Environment.NewLine;
                invitationTask.ActiveText += IncomingInvitationTasks.Resources.CounterpartyBox;
                invitationTask.ActiveText += Environment.NewLine + counterpartyBox;
            }

            if (!string.IsNullOrWhiteSpace(comment))
            {
                invitationTask.ActiveText += Environment.NewLine;
                invitationTask.ActiveText += Environment.NewLine;
                invitationTask.ActiveText += IncomingInvitationTasks.Resources.AssignmentComment;
                invitationTask.ActiveText += Environment.NewLine + comment;
            }
            invitationTask.Box          = box;
            invitationTask.Counterparty = counterparty;
            invitationTask.Assignee     = box.Responsible;
            invitationTask.MaxDeadline  = Calendar.Now.AddWorkingDays(invitationTask.Assignee, 2);
            invitationTask.Attachments.Add(counterparty);
            invitationTask.OrganizationId = organizationId;
            invitationTask.Save();
            invitationTask.Start();
            return(invitationTask);
        }
Exemple #2
0
        /// <summary>
        /// Проверка возможности отправить приглашение контрагенту хоть через один ящик.
        /// </summary>
        /// <param name="counterparty">Контрагент.</param>
        /// <returns>Список сервисов, способных отправить приглашение.</returns>
        /// <remarks>Только полное совпадение по ИНН и КПП.</remarks>
        public static List <Structures.Counterparty.AllowedBoxes> CanSendInvitation(Parties.ICounterparty counterparty)
        {
            var boxes = ExchangeCore.PublicFunctions.BusinessUnitBox.Remote.GetConnectedBoxes().ToList();

            // Если контрагент является копией какой-либо НОР, то ящики этой НОР убираем из списка.
            var parentBusinessUnit = Sungero.Company.BusinessUnits.GetAll(b => Equals(b.Company, counterparty)).FirstOrDefault();

            if (parentBusinessUnit != null)
            {
                boxes = boxes.Where(b => !Equals(b.BusinessUnit, parentBusinessUnit)).ToList();
            }

            var allowedServices = new List <Structures.Counterparty.AllowedBoxes>();

            foreach (var box in boxes)
            {
                var organizations = ExchangeCore.PublicFunctions.BusinessUnitBox.Remote.CanSendInvitationFrom(box, counterparty);

                if (organizations.Any())
                {
                    allowedServices.Add(Structures.Counterparty.AllowedBoxes.Create(box, organizations));
                }
            }
            return(allowedServices);
        }
Exemple #3
0
 public static IQueryable <IOfficialDocument> GetOfficialCorrespondenceWithCounterparty(
     Parties.ICounterparty counterparty, DateTime?periodBegin, DateTime?periodEnd)
 {
     return(OfficialDocuments.GetAll()
            .Where(l => l.RegistrationState == Docflow.OfficialDocument.RegistrationState.Reserved ||
                   l.RegistrationState == Docflow.OfficialDocument.RegistrationState.Registered)
            .Where(l => periodBegin == null || l.RegistrationDate >= periodBegin)
            .Where(l => periodEnd == null || l.RegistrationDate <= periodEnd)
            .Where(l => (IncomingDocumentBases.Is(l) && Equals(IncomingDocumentBases.As(l).Correspondent, counterparty)) ||
                   (OutgoingDocumentBases.Is(l) && OutgoingDocumentBases.As(l).Addressees.Select(x => x.Correspondent).Any(y => Equals(y, counterparty)))));
 }
Exemple #4
0
 public static IQueryable <IIncomingLetter> GetDuplicates(IIncomingLetter letter,
                                                          Docflow.IDocumentKind documentKind,
                                                          Company.IBusinessUnit businessUnit,
                                                          string inNumber,
                                                          DateTime?dated,
                                                          Parties.ICounterparty correspondent)
 {
     return(IncomingLetters.GetAll()
            .Where(l => documentKind != null && Equals(documentKind, l.DocumentKind))
            .Where(l => dated.HasValue && dated == l.Dated)
            .Where(l => businessUnit != null && Equals(businessUnit, l.BusinessUnit))
            .Where(l => !string.IsNullOrWhiteSpace(inNumber) && inNumber == l.InNumber)
            .Where(l => correspondent != null && Equals(correspondent, l.Correspondent))
            .Where(l => !Equals(letter, l)));
 }
Exemple #5
0
 public static IQueryable <IIncomingInvoice> GetDuplicates(IIncomingInvoice incomingInvoice,
                                                           Sungero.Docflow.IDocumentKind documentKind,
                                                           string number,
                                                           DateTime?date,
                                                           double?totalAmount,
                                                           Commons.ICurrency currency,
                                                           Parties.ICounterparty counterparty)
 {
     return(IncomingInvoices.GetAll()
            .Where(i => i.DocumentKind.Equals(documentKind))
            .Where(i => i.Number == number)
            .Where(i => i.Date == date)
            .Where(i => i.TotalAmount == totalAmount)
            .Where(i => i.Currency.Equals(currency))
            .Where(i => i.Counterparty.Equals(counterparty))
            .Where(i => !Equals(i, incomingInvoice)));
 }
Exemple #6
0
        /// <summary>
        /// Проверить письмо на дубликаты.
        /// </summary>
        /// <param name="letter">Входящее письмо.</param>
        /// <param name="documentKind">Вид документа.</param>
        /// <param name="businessUnit">Наша организация.</param>
        /// <param name="correspondentNumber">Номер корреспондента.</param>
        /// <param name="dated">Дата письма.</param>
        /// <param name="correspondent">Корреспондент.</param>
        /// <returns>True, если дубликаты имеются, иначе - false.</returns>
        public static bool HaveDuplicates(IIncomingLetter letter,
                                          Sungero.Docflow.IDocumentKind documentKind,
                                          Company.IBusinessUnit businessUnit,
                                          string correspondentNumber,
                                          DateTime?dated,
                                          Parties.ICounterparty correspondent)
        {
            if (documentKind == null ||
                businessUnit == null ||
                string.IsNullOrEmpty(correspondentNumber) ||
                !dated.HasValue ||
                correspondent == null)
            {
                return(false);
            }

            return(Functions.IncomingLetter.Remote.GetDuplicates(letter, documentKind, businessUnit, correspondentNumber, dated, correspondent).Any());
        }
Exemple #7
0
        /// <summary>
        /// Проверить дубли входящего счета.
        /// </summary>
        /// <param name="incomingInvoice">Счет для проверки.</param>
        /// <param name="documentKind">Вид счета.</param>
        /// <param name="number">Номер счета.</param>
        /// <param name="date">Дата счета.</param>
        /// <param name="totalAmount">Сумма счета.</param>
        /// <param name="currency">Валюта счета.</param>
        /// <param name="counterparty">Контрагент счета.</param>
        /// <returns>True, если дубликаты имеются, иначе - false.</returns>
        public static bool HaveDuplicates(IIncomingInvoice incomingInvoice,
                                          Sungero.Docflow.IDocumentKind documentKind,
                                          string number,
                                          DateTime?date,
                                          double?totalAmount,
                                          Commons.ICurrency currency,
                                          Parties.ICounterparty counterparty)
        {
            if (documentKind == null ||
                string.IsNullOrWhiteSpace(number) ||
                date == null ||
                totalAmount == null ||
                currency == null ||
                counterparty == null)
            {
                return(false);
            }

            return(Functions.IncomingInvoice.Remote.GetDuplicates(incomingInvoice, documentKind, number, (DateTime)date, (double)totalAmount, currency, counterparty).Any());
        }
Exemple #8
0
        /// <summary>
        /// Сгенерировать ФНС-ид (и связанные свойства) для документа.
        /// </summary>
        /// <param name="stream">Поток с XML в исходном виде.</param>
        /// <param name="rootBox">Ящик, через который будет отправлен документ.</param>
        /// <param name="counterparty">Контрагент.</param>
        /// <param name="formalizedServiceType">Тип документа (УПД, ДПТ, ДПРР).</param>
        /// <param name="isAdjustment">Корректировочный (важно только для УКД).</param>
        /// <returns>Сгенерированный XML новым потоком.</returns>
        private static System.IO.MemoryStream AddOrReplaceSellerTitleInfo(System.IO.MemoryStream stream, ExchangeCore.IBusinessUnitBox rootBox,
                                                                          Parties.ICounterparty counterparty, Sungero.Core.Enumeration formalizedServiceType,
                                                                          bool isAdjustment)
        {
            var counterpartyExchange = counterparty.ExchangeBoxes.SingleOrDefault(c => Equals(c.Box, rootBox));

            if (counterpartyExchange == null)
            {
                throw AppliedCodeException.Create(string.Format("Counterparty {0} must have exchange from box {1}", counterparty.Id, rootBox.Id));
            }

            var sellerTitleInfo = new FormalizeDocumentsParser.SellerTitleInfo();

            if (formalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GoodsTransfer)
            {
                sellerTitleInfo.DocumentType = FormalizeDocumentsParser.DocumentType.GoodsTransferDocument;
            }
            else if (formalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.WorksTransfer)
            {
                sellerTitleInfo.DocumentType = FormalizeDocumentsParser.DocumentType.WorksTransferDocument;
            }
            else if (formalizedServiceType == Docflow.AccountingDocumentBase.FormalizedServiceType.GeneralTransfer)
            {
                sellerTitleInfo.DocumentType = isAdjustment ? FormalizeDocumentsParser.DocumentType.UniversalCorrectionTransferDocument : FormalizeDocumentsParser.DocumentType.UniversalTransferDocument;
            }

            if (rootBox.ExchangeService.ExchangeProvider == ExchangeCore.ExchangeService.ExchangeProvider.Diadoc)
            {
                sellerTitleInfo.Operator = FormalizeDocumentsParser.SupportedEdoOperators.Diadoc;
            }
            else
            {
                sellerTitleInfo.Operator = FormalizeDocumentsParser.SupportedEdoOperators.Synerdocs;
            }
            sellerTitleInfo.Receiver = counterpartyExchange.FtsId;
            sellerTitleInfo.Sender   = rootBox.FtsId;
            return(sellerTitleInfo.AddOrReplaceToXml(stream));
        }
Exemple #9
0
        private static void FillBusinessUnitAndCounterparty(Docflow.IAccountingDocumentBase document,
                                                            FormalizeDocumentsParser.ISellerTitle sellerTitle,
                                                            bool requireFtsId)
        {
            ExchangeCore.IBusinessUnitBox box          = null;
            Parties.ICounterparty         counterparty = null;

            // Поиск по ФНС ИД.
            if (!string.IsNullOrWhiteSpace(sellerTitle.SenderId) || !string.IsNullOrWhiteSpace(sellerTitle.ReceiverId))
            {
                var exchangeProvider = GetExchangeService(sellerTitle);
                var boxes            = ExchangeCore.BusinessUnitBoxes.GetAll()
                                       .Where(b => b.ExchangeService.ExchangeProvider == exchangeProvider)
                                       .ToList();

                box = boxes.Where(b => b.FtsId == sellerTitle.SenderId).SingleOrDefault();
                if (box != null)
                {
                    counterparty = GetCounterparty(sellerTitle.ReceiverId, box);
                }
            }

            // Поиск по ИНН \ КПП.
            if (!requireFtsId && (box == null || counterparty == null))
            {
                var boxOnTin = GetBox(sellerTitle.Seller);
                if (boxOnTin != null)
                {
                    if (counterparty == null)
                    {
                        counterparty = GetCounterparty(sellerTitle.Buyer, boxOnTin, true);
                    }
                    if (box == null)
                    {
                        box = boxOnTin;
                    }
                }
            }

            // Если нашелся ящик - заполняем.
            if (box != null)
            {
                document.BusinessUnitBox = box;
                document.BusinessUnit    = box.BusinessUnit;
                document.Counterparty    = counterparty;
            }

            if (!requireFtsId && (box == null || counterparty == null))
            {
                // Ищем по ИНН \ КПП, не связываясь с МКДО.
                var unit = GetBusinessUnit(sellerTitle.Seller);
                if (unit != null)
                {
                    if (document.Counterparty == null)
                    {
                        document.Counterparty = GetCounterparty(sellerTitle.Buyer, null, false);
                    }
                    if (document.BusinessUnit == null)
                    {
                        document.BusinessUnit = unit;
                    }
                }
            }
        }
Exemple #10
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 #11
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);
        }
Exemple #12
0
        public static IQueryable <IContractualDocument> GetContractualDocsWithCounterparty(Parties.ICounterparty counterparty,
                                                                                           DateTime?dateFrom, DateTime?dateTo)
        {
            if (dateTo != null)
            {
                dateTo = dateTo.Value.AddDays(1);
            }

            return(ContractualDocuments.GetAll()
                   .Where(r => dateFrom == null || r.RegistrationDate >= dateFrom)
                   .Where(r => dateTo == null || r.RegistrationDate < dateTo)
                   .Where(r => r.Counterparty.Equals(counterparty)));
        }
Exemple #13
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)));
        }