コード例 #1
0
        /// <summary>
        /// Получить все договоры и доп. соглашения на завершении, где Я ответственный.
        /// </summary>
        /// <param name="query">Запрос виджета.</param>
        /// <param name="needAutomaticRenewal">Признак "С пролонгацией".</param>
        /// <param name="substitution">Параметр "Учитывать замещения".</param>
        /// <param name="show">Параметр "Показывать".</param>
        /// <returns>Список договоров и доп. соглашений на завершении.</returns>
        public IQueryable <Sungero.Contracts.IContractualDocument> GetMyExpiringSoonContracts(IQueryable <Sungero.Contracts.IContractualDocument> query,
                                                                                              bool?needAutomaticRenewal,
                                                                                              bool substitution,
                                                                                              Enumeration show)
        {
            var today    = Calendar.UserToday;
            var lastDate = today.AddDays(14);

            // Если показывать надо не все Договоры, то дофильтровываем по ответственному.
            if (show != Sungero.ContractsUI.Widgets.MyContracts.Show.All)
            {
                var currentEmployee      = Employees.Current;
                var responsibleEmployees = new List <IUser>();
                if (currentEmployee != null)
                {
                    responsibleEmployees.Add(currentEmployee);
                }

                var employeeDepartment = currentEmployee != null ? currentEmployee.Department : null;

                // Учитывать замещения, если выставлен соответствующий параметр.
                if (substitution)
                {
                    var substitutions = Substitutions.ActiveSubstitutedUsersWithoutSystem;
                    responsibleEmployees.AddRange(substitutions);
                }

                // Если выбрано значение параметра "Договоры подразделения", то добавляем к списку ответственных всех сотрудников подразделения.
                if (show == Sungero.ContractsUI.Widgets.MyContracts.Show.Department)
                {
                    var departmentsEmployees = Company.Employees.GetAll(e => Equals(e.Department, employeeDepartment));
                    responsibleEmployees.AddRange(departmentsEmployees);
                }

                query = query.Where(cd => responsibleEmployees.Contains(cd.ResponsibleEmployee));
            }
            query = query
                    .Where(q => ContractBases.Is(q) || SupAgreements.Is(q))
                    .Where(q => q.LifeCycleState == Sungero.Contracts.SupAgreement.LifeCycleState.Active);

            query = query.Where(q => q.ValidTill.HasValue)
                    .Where(q => (ContractBases.Is(q) && today.AddDays(ContractBases.As(q).DaysToFinishWorks ?? 14) >= q.ValidTill) ||
                           (SupAgreements.Is(q) && q.ValidTill.Value <= lastDate))
                    .Where(q => SupAgreements.Is(q) || ContractBases.Is(q) && (ContractBases.As(q).DaysToFinishWorks == null ||
                                                                               ContractBases.As(q).DaysToFinishWorks <= Docflow.PublicConstants.Module.MaxDaysToFinish));

            // Признак с автопролонгацией у договоров.
            if (needAutomaticRenewal.HasValue)
            {
                query = query.Where(q => ContractBases.Is(q) &&
                                    ContractBases.As(q).IsAutomaticRenewal.HasValue&&
                                    ContractBases.As(q).IsAutomaticRenewal.Value == needAutomaticRenewal.Value);
            }

            return(query);
        }
コード例 #2
0
        public virtual IQueryable <Sungero.Docflow.IOfficialDocument> ContractsAtContractorsDataQuery(IQueryable <Sungero.Docflow.IOfficialDocument> query)
        {
            var documents = Docflow.OfficialDocuments.GetAll().Where(c => c.IsHeldByCounterParty.Value &&
                                                                     (ContractBases.Is(c) || SupAgreements.Is(c) ||
                                                                      FinancialArchive.ContractStatements.Is(c) || FinancialArchive.Waybills.Is(c) ||
                                                                      FinancialArchive.UniversalTransferDocuments.Is(c)));

            if (_filter == null)
            {
                return(documents);
            }

            #region Фильтры

            // Фильтр "Вид документа".
            if (_filter.DocumentKind != null)
            {
                documents = documents.Where(c => Equals(c.DocumentKind, _filter.DocumentKind));
            }

            // Фильтр "Категория".
            if (_filter.Category != null)
            {
                documents = documents.Where(c => !ContractBases.Is(c) || (ContractBases.Is(c) && Equals(c.DocumentGroup, _filter.Category)));
            }

            // Фильтр "Контрагент".
            if (_filter.Contractor != null)
            {
                documents = documents.Where(c => (Docflow.ContractualDocumentBases.Is(c) && Equals(Docflow.ContractualDocumentBases.As(c).Counterparty, _filter.Contractor)) ||
                                            (Docflow.AccountingDocumentBases.Is(c) && Equals(Docflow.AccountingDocumentBases.As(c).Counterparty, _filter.Contractor)));
            }

            // Фильтр "Наша организация".
            if (_filter.BusinessUnit != null)
            {
                documents = documents.Where(c => Equals(c.BusinessUnit, _filter.BusinessUnit));
            }

            // Фильтр "Ответственный за возврат".
            if (_filter.Responsible != null)
            {
                documents = documents.Where(c => Equals(c.ResponsibleForReturnEmployee, _filter.Responsible));
            }

            // Фильтр "Только просроченные".
            if (_filter.OnlyOverdue)
            {
                var today = Calendar.UserToday;
                documents = documents.Where(c => c.ScheduledReturnDateFromCounterparty < today);
            }

            #endregion

            return(documents);
        }
コード例 #3
0
 public static IQueryable <IContractBase> GetDuplicates(IContractBase contract,
                                                        Sungero.Company.IBusinessUnit businessUnit,
                                                        string registrationNumber,
                                                        DateTime?registrationDate,
                                                        Sungero.Parties.ICounterparty counterparty)
 {
     return(ContractBases.GetAll()
            .Where(l => Equals(contract.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(contract, l)));
 }
コード例 #4
0
        /// <summary>
        /// Получить все договоры и доп. соглашения в стадии согласования, где Я ответственный.
        /// </summary>
        /// <param name="query">Запрос виджета.</param>
        /// <param name="substitution">Параметр "Учитывать замещения".</param>
        /// <param name="show">Параметр "Показывать".</param>
        /// <returns>Список договоров и доп. соглашений.</returns>
        public IQueryable <Sungero.Contracts.IContractualDocument> GetMyContractualDocuments(IQueryable <Sungero.Contracts.IContractualDocument> query,
                                                                                             bool substitution,
                                                                                             Enumeration show)
        {
            query = query.Where(cd => ContractBases.Is(cd) || SupAgreements.Is(cd));

            // Проверить статус жизненного цикла.
            query = query.Where(cd => cd.LifeCycleState == Docflow.OfficialDocument.LifeCycleState.Draft)
                    .Where(cd => cd.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.OnApproval ||
                           cd.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.OnRework ||
                           cd.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.PendingSign ||
                           cd.InternalApprovalState == Docflow.OfficialDocument.InternalApprovalState.Signed ||
                           cd.ExternalApprovalState == Docflow.OfficialDocument.ExternalApprovalState.OnApproval);

            // Если показывать надо не все Договоры, то дофильтровываем по ответственному.
            if (show != Sungero.ContractsUI.Widgets.MyContracts.Show.All)
            {
                var currentEmployee      = Company.Employees.Current;
                var responsibleEmployees = new List <IUser>();
                if (currentEmployee != null)
                {
                    responsibleEmployees.Add(currentEmployee);
                }

                var employeeDepartment = currentEmployee != null ? currentEmployee.Department : null;

                // Учитывать замещения, если выставлен соответствующий параметр.
                if (substitution)
                {
                    var substitutions = Substitutions.ActiveSubstitutedUsersWithoutSystem;
                    responsibleEmployees.AddRange(substitutions);
                }

                // Если выбрано значение параметра "Договоры подразделения", то добавляем к списку ответственных всех сотрудников подразделения.
                if (show == Sungero.ContractsUI.Widgets.MyContracts.Show.Department)
                {
                    var departmentsEmployees = Company.Employees.GetAll(e => Equals(e.Department, employeeDepartment));
                    responsibleEmployees.AddRange(departmentsEmployees);
                }

                query = query.Where(cd => responsibleEmployees.Contains(cd.ResponsibleEmployee));
            }

            return(query);
        }
コード例 #5
0
        public override void LeadingDocumentChanged(Sungero.Docflow.Shared.OfficialDocumentLeadingDocumentChangedEventArgs e)
        {
            base.LeadingDocumentChanged(e);

            if (Equals(e.NewValue, e.OldValue))
            {
                return;
            }

            if (e.NewValue != null)
            {
                var contract = ContractBases.As(e.NewValue);
                _obj.Counterparty = contract.Counterparty;
                _obj.BusinessUnit = contract.BusinessUnit;

                Docflow.PublicFunctions.OfficialDocument.CopyProjects(e.NewValue, _obj);
            }

            FillName();
            _obj.Relations.AddFromOrUpdate(Constants.Module.SupAgreementRelationName, e.OldValue, e.NewValue);
        }
コード例 #6
0
ファイル: ModuleJobs.cs プロジェクト: sknabniai/karbase
        /// <summary>
        /// Агент рассылки уведомления об окончании срока действия договоров.
        /// </summary>
        public virtual void SendNotificationForExpiringContracts()
        {
            var command = Queries.Module.CreateTableForExpiringContracts;

            Sungero.Docflow.PublicFunctions.Module.ExecuteSQLCommand(command);

            var notifyParams = Docflow.PublicFunctions.Module.GetDefaultExpiringDocsNotificationParams(Constants.Module.NotificationDatabaseKey,
                                                                                                       Constants.Module.ExpiringContractTableName);

            var alreadySentDocs = Docflow.PublicFunctions.Module.GetDocumentsWithSendedTask(notifyParams.ExpiringDocTableName);

            var contractIds = ContractBases.GetAll()
                              .Where(c => !alreadySentDocs.Contains(c.Id))
                              .Where(c => c.LifeCycleState == Sungero.Contracts.ContractBase.LifeCycleState.Active ||
                                     c.LifeCycleState == Sungero.Contracts.ContractBase.LifeCycleState.Draft)
                              .Where(c => c.ResponsibleEmployee != null || c.Author != null)
                              .Where(c => notifyParams.LastNotificationReserve.AddDays(c.DaysToFinishWorks.HasValue ? c.DaysToFinishWorks.Value : 0) < c.ValidTill &&
                                     c.ValidTill <= notifyParams.TodayReserve.AddDays(c.DaysToFinishWorks.HasValue ? c.DaysToFinishWorks.Value : 0))
                              .Where(c => c.DaysToFinishWorks == null || c.DaysToFinishWorks <= Docflow.PublicConstants.Module.MaxDaysToFinish)
                              .Select(c => c.Id)
                              .ToList();

            Logger.DebugFormat("Contracts to send notification count = {0}.", contractIds.Count());

            for (int i = 0; i < contractIds.Count(); i = i + notifyParams.BatchCount)
            {
                var result = Transactions.Execute(
                    () =>
                {
                    var contractsPart = ContractBases.GetAll(c => contractIds.Contains(c.Id)).Skip(i).Take(notifyParams.BatchCount).ToList();
                    contractsPart     = contractsPart.Where(c => notifyParams.LastNotification.ToUserTime(c.ResponsibleEmployee ?? c.Author).AddDays(c.DaysToFinishWorks.HasValue ? c.DaysToFinishWorks.Value : 0) < c.ValidTill &&
                                                            c.ValidTill <= Calendar.GetUserToday(c.ResponsibleEmployee ?? c.Author).AddDays(c.DaysToFinishWorks.HasValue ? c.DaysToFinishWorks.Value : 0))
                                        .ToList();

                    if (!contractsPart.Any())
                    {
                        return;
                    }

                    Docflow.PublicFunctions.Module.ClearIdsFromExpiringDocsTable(notifyParams.ExpiringDocTableName,
                                                                                 contractsPart.Select(x => x.Id).ToList());
                    Docflow.PublicFunctions.Module.AddExpiringDocumentsToTable(notifyParams.ExpiringDocTableName,
                                                                               contractsPart.Select(x => x.Id).ToList());

                    foreach (var contract in contractsPart)
                    {
                        var subject = Docflow.PublicFunctions.Module.TrimQuotes(
                            contract.IsAutomaticRenewal == true ?
                            Resources.AutomaticRenewalContractExpiresFormat(contract.DisplayValue) :
                            Resources.ExpiringContractsSubjectFormat(contract.DisplayValue));

                        if (subject.Length > Workflow.SimpleTasks.Info.Properties.Subject.Length)
                        {
                            subject = subject.Substring(0, Workflow.SimpleTasks.Info.Properties.Subject.Length);
                        }

                        var activeText = Docflow.PublicFunctions.Module.TrimQuotes(
                            contract.IsAutomaticRenewal == true ?
                            Resources.ExpiringContractsRenewalTextFormat(contract.ValidTill.Value.ToShortDateString(), contract.DisplayValue) :
                            Resources.ExpiringContractsTextFormat(contract.ValidTill.Value.ToShortDateString(), contract.DisplayValue));

                        var performers = Functions.Module.GetNotificationPerformers(contract);
                        performers     = performers.Where(p => p != null).Distinct().ToList();

                        var attachments = new List <IElectronicDocument>();
                        attachments.Add(contract);
                        var related = contract.Relations.GetRelated(Constants.Module.SupAgreementRelationName).ToList();
                        attachments.AddRange(related);

                        notifyParams.TaskParams.Document    = contract;
                        notifyParams.TaskParams.Subject     = subject;
                        notifyParams.TaskParams.ActiveText  = activeText;
                        notifyParams.TaskParams.Performers  = performers;
                        notifyParams.TaskParams.Attachments = attachments;
                        Docflow.PublicFunctions.Module.TrySendExpiringDocNotifications(notifyParams);
                    }
                });
            }

            if (Docflow.PublicFunctions.Module.IsAllNotificationsStarted(notifyParams.ExpiringDocTableName))
            {
                Docflow.PublicFunctions.Module.UpdateLastNotificationDate(notifyParams);
                Docflow.PublicFunctions.Module.ClearExpiringTable(notifyParams.ExpiringDocTableName, false);
            }
        }
コード例 #7
0
        public virtual IQueryable <Sungero.Contracts.IContractualDocument> ExpiringSoonContractsDataQuery(IQueryable <Sungero.Contracts.IContractualDocument> query)
        {
            // Документ действующий и осталось 14 (либо указанное в договоре число) дней до окончания документа.
            var today     = Calendar.UserToday;
            var documents = query.Where(d => d.LifeCycleState == Sungero.Docflow.OfficialDocument.LifeCycleState.Active)
                            .Where(d => SupAgreements.Is(d) || ContractBases.Is(d) && (ContractBases.As(d).DaysToFinishWorks == null ||
                                                                                       ContractBases.As(d).DaysToFinishWorks <= Docflow.PublicConstants.Module.MaxDaysToFinish))
                            .Where(d => (ContractBases.Is(d) && today.AddDays(ContractBases.As(d).DaysToFinishWorks ?? 14) >= d.ValidTill) ||
                                   (SupAgreements.Is(d) && today.AddDays(14) >= d.ValidTill));

            if (_filter == null)
            {
                return(documents);
            }

            #region Фильтры

            // Фильтр "Вид документа".
            if (_filter.DocumentKind != null)
            {
                documents = documents.Where(d => Equals(d.DocumentKind, _filter.DocumentKind));
            }

            // Фильтр "Категория".
            if (_filter.Category != null)
            {
                documents = documents.Where(d => ContractBases.Is(d) && Equals(d.DocumentGroup, _filter.Category));
            }

            // Фильтр "Контрагент".
            if (_filter.Contractor != null)
            {
                documents = documents.Where(d => Equals(d.Counterparty, _filter.Contractor));
            }

            // Фильтр "Наша организация".
            if (_filter.BusinessUnit != null)
            {
                documents = documents.Where(d => Equals(d.BusinessUnit, _filter.BusinessUnit));
            }

            // Фильтр "Ответственный".
            if (_filter.Responsible != null)
            {
                documents = documents.Where(d => Equals(d.ResponsibleEmployee, _filter.Responsible));
            }

            // Фильтр по типу документа
            if (_filter.Contracts && !_filter.SupAgreements)
            {
                return(documents.Where(d => ContractBases.Is(d)));
            }
            if (_filter.SupAgreements && !_filter.Contracts)
            {
                return(documents.Where(d => SupAgreements.Is(d)));
            }

            #endregion

            return(documents);
        }
コード例 #8
0
        public virtual IQueryable <Sungero.Contracts.IContractualDocument> ContractsHistoryDataQuery(IQueryable <Sungero.Contracts.IContractualDocument> query)
        {
            var documents = query.Where(d => ContractBases.Is(d) || SupAgreements.Is(d));

            if (_filter == null)
            {
                return(documents);
            }

            #region Фильтр по состоянию и датам

            DateTime beginPeriod = Calendar.SqlMinValue;
            DateTime endPeriod   = Calendar.UserToday.EndOfDay().FromUserTime();

            if (_filter.Last30days)
            {
                beginPeriod = Docflow.PublicFunctions.Module.Remote.GetTenantDateTimeFromUserDay(Calendar.UserToday.AddDays(-30));
            }

            if (_filter.Last365days)
            {
                beginPeriod = Docflow.PublicFunctions.Module.Remote.GetTenantDateTimeFromUserDay(Calendar.UserToday.AddDays(-365));
            }

            if (_filter.ManualPeriod)
            {
                if (_filter.DateRangeFrom.HasValue)
                {
                    beginPeriod = Docflow.PublicFunctions.Module.Remote.GetTenantDateTimeFromUserDay(_filter.DateRangeFrom.Value);
                }

                endPeriod = _filter.DateRangeTo.HasValue ? _filter.DateRangeTo.Value.EndOfDay().FromUserTime() : Calendar.SqlMaxValue;
            }

            Enumeration?operation       = null;
            var         lifeCycleStates = new List <Enumeration>();

            if (_filter.Concluded)
            {
                operation = new Enumeration("SetToActive");
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Active);
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Closed);
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Terminated);
            }

            if (_filter.Executed)
            {
                operation = new Enumeration("SetToClosed");
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Closed);
            }

            if (_filter.Terminated)
            {
                operation = new Enumeration("SetToTerminated");
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Terminated);
            }

            if (_filter.Cancelled)
            {
                operation = new Enumeration("SetToObsolete");
                lifeCycleStates.Add(Sungero.Contracts.ContractBase.LifeCycleState.Obsolete);
            }

            // Использовать можно только один WhereDocumentHistory, т.к. это отдельный подзапрос (+join).
            documents = documents.Where(d => d.LifeCycleState.HasValue && lifeCycleStates.Contains(d.LifeCycleState.Value))
                        .WhereDocumentHistory(h => h.Operation == operation && h.HistoryDate.Between(beginPeriod, endPeriod));

            #endregion

            #region Фильтры по полям навигации

            // Фильтр "Вид документа".
            if (_filter.DocumentKind != null)
            {
                documents = documents.Where(c => Equals(c.DocumentKind, _filter.DocumentKind));
            }

            // Фильтр "Категория".
            if (_filter.Category != null)
            {
                documents = documents.Where(c => Equals(c.DocumentGroup, _filter.Category));
            }

            // Фильтр "Наша организация".
            if (_filter.BusinessUnit != null)
            {
                documents = documents.Where(c => Equals(c.BusinessUnit, _filter.BusinessUnit));
            }

            // Фильтр "Ответственный".
            if (_filter.Responsible != null)
            {
                documents = documents.Where(c => Equals(c.ResponsibleEmployee, _filter.Responsible));
            }

            #endregion

            #region Фильтр по типу документа

            if (_filter.SupAgreements || _filter.Contracts)
            {
                documents = documents.Where(d => _filter.Contracts && ContractBases.Is(d) || _filter.SupAgreements && SupAgreements.Is(d));
            }

            #endregion

            return(documents);
        }
コード例 #9
0
        public virtual IQueryable <Sungero.Contracts.IContractualDocument> ContractsListDataQuery(IQueryable <Sungero.Contracts.IContractualDocument> query)
        {
            if (_filter == null)
            {
                return(query.Where(d => ContractBases.Is(d) || SupAgreements.Is(d)));
            }

            #region Фильтры

            // Фильтр по состоянию.
            var statuses = new List <Enumeration>();
            if (_filter.Draft)
            {
                statuses.Add(Sungero.Contracts.ContractBase.LifeCycleState.Draft);
            }
            if (_filter.Active)
            {
                statuses.Add(Sungero.Contracts.ContractBase.LifeCycleState.Active);
            }
            if (_filter.Executed)
            {
                statuses.Add(Sungero.Contracts.ContractBase.LifeCycleState.Closed);
            }
            if (_filter.Terminated)
            {
                statuses.Add(Sungero.Contracts.ContractBase.LifeCycleState.Terminated);
            }
            if (_filter.Cancelled)
            {
                statuses.Add(Sungero.Contracts.ContractBase.LifeCycleState.Obsolete);
            }

            // Фильтр по состоянию.
            if (statuses.Any())
            {
                query = query.Where(q => q.LifeCycleState != null && statuses.Contains(q.LifeCycleState.Value));
            }

            // Фильтр "Вид документа".
            if (_filter.DocumentKind != null)
            {
                query = query.Where(c => Equals(c.DocumentKind, _filter.DocumentKind));
            }

            // Фильтр "Категория".
            if (_filter.Category != null)
            {
                query = query.Where(c => ContractBases.Is(c) && Equals(c.DocumentGroup, _filter.Category));
            }

            // Фильтр "Контрагент".
            if (_filter.Contractor != null)
            {
                query = query.Where(c => Equals(c.Counterparty, _filter.Contractor));
            }

            // Фильтр "Наша организация".
            if (_filter.BusinessUnit != null)
            {
                query = query.Where(c => Equals(c.BusinessUnit, _filter.BusinessUnit));
            }

            // Фильтр "Подразделение".
            if (_filter.Department != null)
            {
                query = query.Where(c => Equals(c.Department, _filter.Department));
            }

            #region Фильтрация по дате договора

            var beginDate = Calendar.UserToday.AddDays(-30);
            var endDate   = Calendar.UserToday;

            if (_filter.Last365days)
            {
                beginDate = Calendar.UserToday.AddDays(-365);
            }

            if (_filter.ManualPeriod)
            {
                beginDate = _filter.DateRangeFrom ?? Calendar.SqlMinValue;
                endDate   = _filter.DateRangeTo ?? Calendar.SqlMaxValue;
            }

            var serverPeriodBegin = Equals(Calendar.SqlMinValue, beginDate) ? beginDate : Docflow.PublicFunctions.Module.Remote.GetTenantDateTimeFromUserDay(beginDate);
            var serverPeriodEnd   = Equals(Calendar.SqlMaxValue, endDate) ? endDate : endDate.EndOfDay().FromUserTime();
            var clientPeriodEnd   = !Equals(Calendar.SqlMaxValue, endDate) ? endDate.AddDays(1) : Calendar.SqlMaxValue;
            query = query.Where(j => (j.DocumentDate.Between(serverPeriodBegin, serverPeriodEnd) ||
                                      j.DocumentDate == beginDate) && j.DocumentDate != clientPeriodEnd);

            #endregion

            // Фильтр по типу документа
            if (_filter.Contracts != _filter.SupAgreements)
            {
                if (_filter.Contracts)
                {
                    query = query.Where(d => ContractBases.Is(d));
                }

                if (_filter.SupAgreements)
                {
                    query = query.Where(d => SupAgreements.Is(d));
                }
            }
            else
            {
                query = query.Where(d => ContractBases.Is(d) || SupAgreements.Is(d));
            }

            #endregion

            return(query);
        }
コード例 #10
0
        public virtual IQueryable <Sungero.Contracts.IContractualDocument> FinContractListDataQuery(IQueryable <Sungero.Contracts.IContractualDocument> query)
        {
            var documents = query.Where(x => x.LifeCycleState == Contracts.ContractBase.LifeCycleState.Terminated ||
                                        x.LifeCycleState == Contracts.ContractBase.LifeCycleState.Active ||
                                        x.LifeCycleState == Contracts.ContractBase.LifeCycleState.Closed);

            if (_filter == null)
            {
                return(documents);
            }

            #region Фильтры

            // Фильтр "Вид документа".
            if (_filter.DocumentKind != null)
            {
                documents = documents.Where(c => Equals(c.DocumentKind, _filter.DocumentKind));
            }

            // Фильтр "Категория".
            if (_filter.Category != null)
            {
                documents = documents.Where(c => Equals(c.DocumentGroup, _filter.Category));
            }

            // Фильтр "Контрагент".
            if (_filter.Contractor != null)
            {
                documents = documents.Where(c => Equals(c.Counterparty, _filter.Contractor));
            }

            // Фильтр "Наша организация".
            if (_filter.BusinessUnit != null)
            {
                documents = documents.Where(c => Equals(c.BusinessUnit, _filter.BusinessUnit));
            }

            // Фильтр "Подразделение".
            if (_filter.Department != null)
            {
                documents = documents.Where(c => Equals(c.Department, _filter.Department));
            }

            #region Фильтрация по дате договора

            DateTime?beginDate = null;
            DateTime?endDate   = null;
            var      today     = Calendar.UserToday;

            if (_filter.CurrentMonth)
            {
                beginDate = today.BeginningOfMonth();
                endDate   = today.EndOfMonth();
            }
            if (_filter.PreviousMonth)
            {
                beginDate = today.AddMonths(-1).BeginningOfMonth();
                endDate   = today.AddMonths(-1).EndOfMonth();
            }
            if (_filter.CurrentQuarter)
            {
                beginDate = Docflow.PublicFunctions.AccountingDocumentBase.BeginningOfQuarter(today);
                endDate   = Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(today);
            }
            if (_filter.PreviousQuarter)
            {
                beginDate = Docflow.PublicFunctions.AccountingDocumentBase.BeginningOfQuarter(today.AddMonths(-3));
                endDate   = Docflow.PublicFunctions.AccountingDocumentBase.EndOfQuarter(today.AddMonths(-3));
            }

            if (_filter.ManualPeriod)
            {
                if (_filter.DateRangeFrom.HasValue)
                {
                    beginDate = _filter.DateRangeFrom.Value;
                }
                if (_filter.DateRangeTo.HasValue)
                {
                    endDate = _filter.DateRangeTo.Value;
                }
            }

            if (beginDate != null)
            {
                documents = documents.Where(q => q.ValidTill != null && q.ValidTill >= beginDate ||
                                            q.ValidTill == null);
            }

            if (endDate != null)
            {
                documents = documents.Where(q => q.ValidFrom != null && q.ValidFrom <= endDate ||
                                            q.ValidFrom == null);
            }
            #endregion

            // Фильтр по типу документа
            if (_filter.Contracts && !_filter.SupAgreements)
            {
                return(documents.Where(d => ContractBases.Is(d)));
            }

            if (_filter.SupAgreements && !_filter.Contracts)
            {
                return(documents.Where(d => SupAgreements.Is(d)));
            }

            #endregion

            return(documents);
        }