Пример #1
0
 /// <summary>
 ///  Получить отфильтрованные виды документов.
 /// </summary>
 /// <param name="direction">Документопоток вида документа.</param>
 /// <returns>Виды документов.</returns>.
 public static List <IDocumentKind> GetFilteredDocumentKinds(Enumeration direction)
 {
     if (DocumentKinds.Info.IsCacheable)
     {
         if (direction == Docflow.DocumentKind.DocumentFlow.Incoming)
         {
             return(DocumentKinds.GetAllCached(d => d.DocumentFlow.Value == Docflow.DocumentKind.DocumentFlow.Incoming).ToList());
         }
         else if (direction == Docflow.DocumentKind.DocumentFlow.Outgoing)
         {
             return(DocumentKinds.GetAllCached(d => d.DocumentFlow.Value == Docflow.DocumentKind.DocumentFlow.Outgoing).ToList());
         }
         else if (direction == Docflow.DocumentKind.DocumentFlow.Inner)
         {
             return(DocumentKinds.GetAllCached(d => d.DocumentFlow.Value == Docflow.DocumentKind.DocumentFlow.Inner).ToList());
         }
         else if (direction == Docflow.DocumentKind.DocumentFlow.Contracts)
         {
             return(DocumentKinds.GetAllCached(d => d.DocumentFlow.Value == Docflow.DocumentKind.DocumentFlow.Contracts).ToList());
         }
         else
         {
             return(null);
         }
     }
     else
     {
         return(Functions.Module.Remote.GetFilteredDocumentKinds(direction));
     }
 }
        public static IDocumentKind GetNativeDocumentKind(Guid externalLink)
        {
            var link = Functions.Module.GetExternalLink(DocumentKind.ClassTypeGuid, externalLink);

            if (link == null)
            {
                return(null);
            }

            return(DocumentKinds.GetAll(r => r.Id == link.EntityId).SingleOrDefault());
        }
Пример #3
0
        /// <summary>
        /// Получить доступные виды документов.
        /// </summary>
        /// <returns>Виды документов.</returns>
        public virtual List <IDocumentKind> GetAvaliableDocumentKinds()
        {
            var availableDocumentKinds = new List <IDocumentKind>();

            if (_obj.DocumentKinds.Any())
            {
                availableDocumentKinds.AddRange(_obj.DocumentKinds.Select(d => d.DocumentKind));
            }
            else if (_obj.DocumentFlow != null)
            {
                availableDocumentKinds.AddRange(DocumentKinds.GetAllCached(k => Equals(k.DocumentFlow, _obj.DocumentFlow)).ToList());
            }

            return(availableDocumentKinds);
        }
        public static IQueryable <IDocumentKind> GetAvailableDocumentKinds(IOfficialDocument document)
        {
            var documentKinds = DocumentKinds.GetAll(r => r.Status == CoreEntities.DatabookEntry.Status.Active);

            var type = document.GetType();

            var typeProperty = type.GetProperty("TypeGuid");

            if (typeProperty != null)
            {
                var typeGuid = ((Guid)typeProperty.GetValue(document)).GetOriginalTypeGuid().ToString();
                documentKinds = documentKinds.Where(k => k.DocumentType.DocumentTypeGuid == typeGuid);
            }

            return(documentKinds);
        }
Пример #5
0
        public static IApprovalRule CreateDefaultInvoiceRule(string ruleName, List <Enumeration> stages)
        {
            var documentFlow = Docflow.ApprovalRuleBase.DocumentFlow.Incoming;

            var hasNotDefaultRule = ApprovalRuleBases.GetAll().Any(r => r.IsDefaultRule != true);
            var hasDefaultRule    = ApprovalRuleBases.GetAll().Any(r => r.DocumentFlow == documentFlow);

            if (hasNotDefaultRule || hasDefaultRule)
            {
                return(null);
            }

            var rule = Docflow.ApprovalRules.Create();

            rule.Status        = Sungero.Docflow.ApprovalRuleBase.Status.Active;
            rule.Name          = ruleName;
            rule.DocumentFlow  = documentFlow;
            rule.IsDefaultRule = true;
            rule.DocumentKinds.AddNew().DocumentKind = DocumentKinds.GetAll().Where(k => k.DocumentType.DocumentTypeGuid == IncomingInvoice.ClassTypeGuid.ToString()).FirstOrDefault();
            Docflow.PublicInitializationFunctions.Module.SetRuleStages(rule, stages);

            // Создать этап передачи счета в бухгалтерию.
            var stageName          = Sungero.Contracts.Resources.GiveInvoiceApprovalStageName;
            var stageAlreadyExists = Docflow.ApprovalStages.GetAll().Where(s => s.Name == stageName);

            var giveInvoiceStage = stageAlreadyExists.Any() ? stageAlreadyExists.FirstOrDefault() : ApprovalStages.Create();

            if (!stageAlreadyExists.Any())
            {
                giveInvoiceStage.StageType      = StageType.SimpleAgr;
                giveInvoiceStage.DeadlineInDays = 1;
                giveInvoiceStage.ApprovalRoles.AddNew().ApprovalRole = Docflow.PublicFunctions.ApprovalRoleBase.GetRole(Docflow.ApprovalRoleBase.Type.Initiator);
                giveInvoiceStage.Subject = Resources.GiveInAccountant;
                giveInvoiceStage.Name    = stageName;
                giveInvoiceStage.Save();
            }

            // Добавить этап передачи в правило.
            rule.Stages.AddNew().Stage = giveInvoiceStage;
            Docflow.PublicFunctions.ApprovalRuleBase.CreateAutoTransitions(rule);
            rule.Save();

            return(rule);
        }
Пример #6
0
        public virtual void NumberFormatItemsElementValueInput(Sungero.Presentation.EnumerationValueInputEventArgs e)
        {
            // Если новый элемент - код подразделения, то проверять, что у всех подразделений заполнены коды.
            if (e.NewValue == DocumentRegisterNumberFormatItems.Element.DepartmentCode &&
                Functions.DocumentRegister.Remote.HasDepartmentWithNullCode())
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillDepartmentCodes);
            }

            // Если новый элемент - код НОР, то проверять, что у всех НОР заполнены коды.
            if (e.NewValue == DocumentRegisterNumberFormatItems.Element.BUCode &&
                Functions.DocumentRegister.Remote.HasBusinessUnitWithNullCode())
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillBusinessUnitCodes);
            }

            // Если новый элемент - код вида документа, то проверять, что у всех видов документа заполнены коды.
            if (e.NewValue == DocumentRegisterNumberFormatItems.Element.DocKindCode &&
                DocumentKinds.GetAllCached()
                .Any(x => x.Status == CoreEntities.DatabookEntry.Status.Active && x.Code == null))
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillDocumentKindCodes);
            }
        }
Пример #7
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            RegistrationSettingReport.ReportDate = Calendar.UserToday;

            // Заполнить значения по умолчанию, если отчет вызван в невизуальном режиме.
            if (RegistrationSettingReport.FilterDepartmentsForBusinessUnits == null)
            {
                RegistrationSettingReport.FilterDepartmentsForBusinessUnits = true;
            }

            var filterDepartment = RegistrationSettingReport.FilterDepartmentsForBusinessUnits == true;

            #region Описание параметров

            if (RegistrationSettingReport.BusinessUnit != null)
            {
                RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.BusinessUnit, RegistrationSettingReport.BusinessUnit.Name);
            }

            if (!string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.DocumentFlow, RegistrationSettingReport.DirectionLabel);
            }

            RegistrationSettingReport.ParamsDescriprion += string.Format("{0}: {1} \n", Reports.Resources.RegistrationSettingReport.FilterDepartmentsForBusinessUnits,
                                                                         RegistrationSettingReport.FilterDepartmentsForBusinessUnits == true ? Reports.Resources.RegistrationSettingReport.Yes : Reports.Resources.RegistrationSettingReport.No);

            #endregion

            var sourceDataTableName = Constants.RegistrationSettingReport.SourceTableName;
            RegistrationSettingReport.SourceDataTableName = sourceDataTableName;
            var reportSessionId = System.Guid.NewGuid().ToString();
            RegistrationSettingReport.ReportSessionId = reportSessionId;

            var units = RegistrationSettingReport.BusinessUnit != null ?
                        new List <Company.IBusinessUnit>()
            {
                RegistrationSettingReport.BusinessUnit
            } :
            Company.BusinessUnits.GetAll().Where(u => u.Status == CoreEntities.DatabookEntry.Status.Active).ToList();

            var flows = new List <Enumeration>()
            {
                DocumentFlow.Incoming, DocumentFlow.Outgoing, DocumentFlow.Inner, DocumentFlow.Contracts
            };
            if (!string.IsNullOrWhiteSpace(RegistrationSettingReport.Direction))
            {
                flows = flows.Where(i => i.Value == RegistrationSettingReport.Direction).ToList();
            }

            var kinds = DocumentKinds.GetAll().Where(k => k.Status == CoreEntities.DatabookEntry.Status.Active &&
                                                     !Equals(k.NumberingType, DocumentKind.NumberingType.NotNumerable)).ToList();
            var settings    = RegistrationSettings.GetAll().Where(s => s.Status == CoreEntities.DatabookEntry.Status.Active && s.DocumentRegister.Status == CoreEntities.DatabookEntry.Status.Active).ToList();
            var departments = Company.Departments.GetAll().Where(d => d.Status == CoreEntities.DatabookEntry.Status.Active).OrderBy(d => d.Name).ToList();

            var separator             = ";" + System.Environment.NewLine;
            var allDepartmentString   = Reports.Resources.RegistrationSettingReport.AllDepartmentString;
            var otherDepartmentString = Reports.Resources.RegistrationSettingReport.OtherDepartmentString;
            // Строчки также используются в условной разметке для подсветки красным\курсивом.
            var settingNotFound  = Reports.Resources.RegistrationSettingReport.SettingNotFound;
            var defaultSetting   = Reports.Resources.RegistrationSettingReport.DefaultSetting;
            var registerNotFound = Reports.Resources.RegistrationSettingReport.RegisterNotFound;

            var tableData = new List <Structures.RegistrationSettingReport.TableLine>();

            foreach (var unit in units)
            {
                foreach (var flow in flows)
                {
                    foreach (var kind in kinds.Where(k => Equals(k.DocumentFlow, flow)))
                    {
                        var error       = Equals(kind.NumberingType, DocumentKind.NumberingType.Numerable) ? settingNotFound : defaultSetting;
                        var subSettings = settings.Where(s => Equals(s.DocumentFlow, flow) &&
                                                         (!s.BusinessUnits.Any() || s.BusinessUnits.Any(u => Equals(u.BusinessUnit, unit))) &&
                                                         s.DocumentKinds.Any(k => Equals(k.DocumentKind, kind)))
                                          .ToList();

                        foreach (var setting in subSettings)
                        {
                            var subDepartments = setting.Departments.Where(d => !filterDepartment || Equals(d.Department.BusinessUnit, unit)).ToList();
                            if (setting.Departments.Any() && !subDepartments.Any())
                            {
                                continue;
                            }

                            var department = !setting.Departments.Any() ? allDepartmentString : string.Join(separator, subDepartments.Select(d => d.Department.Name));
                            var example    = Functions.DocumentRegister.GetValueExample(setting.DocumentRegister);

                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit           = unit.Name;
                            line.DocumentFlow           = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex      = flows.IndexOf(flow);
                            line.DocumentKind           = kind.Name;
                            line.RegistrationSetting    = setting.Name;
                            line.RegistrationSettingUri = Hyperlinks.Get(setting);
                            line.Priority            = setting.Priority ?? 0;
                            line.Departments         = department;
                            line.SettingType         = GetSettingType(kind, setting);
                            line.DocumentRegister    = setting.DocumentRegister.Name;
                            line.DocumentRegisterUri = Hyperlinks.Get(setting.DocumentRegister);
                            line.NumberExample       = example;
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }

                        // Если настроек для вида не найдено.
                        if (!subSettings.Any() && kind.NumberingType == DocumentKind.NumberingType.Numerable)
                        {
                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = error;
                            line.Priority            = -1;
                            line.Departments         = allDepartmentString;
                            line.SettingType         = GetSettingType(kind, null);
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                            continue;
                        }

                        // Если есть хоть одна настройка для всех подразделений - идём дальше.
                        if (subSettings.Any(s => !s.Departments.Any()))
                        {
                            continue;
                        }
                        // Если нет подразделений без настроек - идем дальше
                        var allDeparmentInUnit = departments.Where(d => Equals(d.BusinessUnit, unit)).ToList();
                        var settingDepartments = subSettings.SelectMany(s => s.Departments).Select(s => s.Department).ToList();
                        if (!allDeparmentInUnit.Except(settingDepartments).Any())
                        {
                            continue;
                        }

                        var allDepartments = filterDepartment ?
                                             departments.Where(d => Equals(d.BusinessUnit, unit)).ToList() :
                                             departments;
                        var registers       = new List <IDocumentRegister>();
                        var firstDepartment = allDepartments.Except(settingDepartments).FirstOrDefault();
                        if (firstDepartment != null)
                        {
                            registers.AddRange(Functions.DocumentRegister.GetDocumentRegistersByParams(kind, unit, firstDepartment, SettingType.Registration, false));
                        }
                        registers = registers.Distinct().ToList();
                        var regDepartment = allDepartments.Any(d => settingDepartments.Contains(d)) ? otherDepartmentString : allDepartmentString;

                        if (!registers.Any())
                        {
                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = registerNotFound;
                            line.Priority            = -1;
                            line.Departments         = regDepartment;
                            line.SettingType         = GetSettingType(kind, null);
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }

                        foreach (var register in registers)
                        {
                            var example = Functions.DocumentRegister.GetValueExample(register);

                            var line = Structures.RegistrationSettingReport.TableLine.Create();
                            line.BusinessUnit        = unit.Name;
                            line.DocumentFlow        = GetDocumentFlowName(flow);
                            line.DocumentFlowIndex   = flows.IndexOf(flow);
                            line.DocumentKind        = kind.Name;
                            line.RegistrationSetting = error;
                            line.Priority            = 0;
                            line.Departments         = regDepartment;
                            line.DocumentRegister    = register.Name;
                            line.DocumentRegisterUri = Hyperlinks.Get(register);
                            line.SettingType         = GetSettingType(kind, null);
                            line.NumberExample       = example;
                            line.ReportSessionId     = reportSessionId;

                            tableData.Add(line);
                        }
                    }
                }
            }

            // Полная сортировка данных.
            tableData = tableData
                        .OrderBy(t => t.BusinessUnit)
                        .ThenBy(t => t.DocumentFlowIndex)
                        .ThenBy(t => t.DocumentKind)
                        .ThenByDescending(t => t.Priority)
                        .ThenBy(t => t.Departments)
                        .ToList();

            for (var i = 0; i < tableData.Count; i++)
            {
                tableData[i].Id = i;
            }

            Functions.Module.WriteStructuresToTable(RegistrationSettingReport.SourceDataTableName, tableData);
        }
Пример #8
0
        public override void Refresh(Sungero.Presentation.FormRefreshEventArgs e)
        {
            Functions.DocumentRegister.SetRequiredProperties(_obj);
            if (!e.IsValid)
            {
                return;
            }

            if (_obj.AccessRights.CanUpdate())
            {
                var isNotUsed = _obj.State.IsInserted || !Functions.Module.CalculateParams(e, _obj.RegistrationGroup, false, false, true, false, _obj);
                _obj.State.Properties.RegistrationGroup.IsEnabled = isNotUsed && _obj.RegisterType != RegisterType.Numbering;
                _obj.State.Properties.RegisterType.IsEnabled      = isNotUsed;
                _obj.State.Properties.DocumentFlow.IsEnabled      = isNotUsed;

                var hasDocuments = !_obj.State.IsInserted && Functions.Module.CalculateParams(e, _obj.RegistrationGroup, false, false, false, true, _obj);
                _obj.State.Properties.NumberingPeriod.IsEnabled  = !hasDocuments;
                _obj.State.Properties.NumberingSection.IsEnabled = !hasDocuments;

                if (hasDocuments)
                {
                    e.AddInformation(DocumentRegisters.Resources.SectionsDisabled, DocumentRegisters.Info.Actions.ShowRegisteredDocuments);
                }
            }

            if (_obj.AccessRights.CanUpdate() && !_obj.State.IsInserted && _obj.RegistrationGroup != null &&
                !Functions.Module.CalculateParams(e, _obj.RegistrationGroup, true, true, false, false, null))
            {
                foreach (var property in _obj.State.Properties)
                {
                    property.IsEnabled = false;
                }
            }

            // Проверить наличие разреза по ведущему документу, если он использован в номере.
            if (_obj.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.LeadingNumber) &&
                _obj.NumberingSection != DocumentRegister.NumberingSection.LeadingDocument)
            {
                e.AddWarning(DocumentRegisters.Resources.ForDocumentNumberMustAttendSection);
            }

            // Если в формате номера есть код подразделения, то проверять, что у всех подразделений заполнены коды.
            if (_obj.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.DepartmentCode) &&
                Functions.DocumentRegister.Remote.HasDepartmentWithNullCode())
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillDepartmentCodes);
            }

            // Если в формате номера есть код НОР, то проверять, что у всех НОР заполнены коды.
            if (_obj.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.BUCode) &&
                Functions.DocumentRegister.Remote.HasBusinessUnitWithNullCode())
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillBusinessUnitCodes);
            }

            // Если в формате номера есть код вида документа, то проверять, что у всех видов документа заполнены коды.
            if (_obj.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.DocKindCode) &&
                DocumentKinds.GetAllCached()
                .Any(x => x.Status == CoreEntities.DatabookEntry.Status.Active && x.Code == null))
            {
                e.AddWarning(DocumentRegisters.Resources.NeedFillDocumentKindCodes);
            }
        }
        public static IQueryable <IDocumentKind> GetDocumentKinds()
        {
            var approvalAction = Functions.Module.GetSendAction(OfficialDocuments.Info.Actions.SendForApproval);

            return(DocumentKinds.GetAll().Where(k => k.Status == Docflow.DocumentKind.Status.Active && k.AvailableActions.Any(a => a.Action == approvalAction)));
        }
Пример #10
0
        public override void Refresh(Sungero.Presentation.FormRefreshEventArgs e)
        {
            if (!e.IsValid)
            {
                return;
            }

            _obj.State.Properties.DocumentRegister.IsEnabled = _obj.DocumentFlow != null;
            _obj.State.Properties.DocumentKinds.IsEnabled    = _obj.DocumentFlow != null;

            if (_obj.AccessRights.CanUpdate() && !_obj.State.IsInserted &&
                _obj.DocumentRegister != null && _obj.DocumentRegister.RegistrationGroup != null &&
                !Functions.Module.CalculateParams(e, _obj.DocumentRegister.RegistrationGroup, true, true, false, false, null))
            {
                foreach (var property in _obj.State.Properties)
                {
                    property.IsEnabled = false;
                }
            }

            var register = _obj.DocumentRegister;

            // Если в формате номера в журнале есть код подразделения, то проверять, что у всех указанных в настройке подразделений заполнены коды.
            if (register != null)
            {
                if (register.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.DepartmentCode))
                {
                    var hasDepartmentsWithoutCode = _obj.Departments.Any() ?
                                                    _obj.Departments.Select(x => x.Department).Any(x => x.Code == null) :
                                                    Functions.DocumentRegister.Remote.HasDepartmentWithNullCode();

                    if (hasDepartmentsWithoutCode)
                    {
                        e.AddWarning(DocumentRegisters.Resources.NeedFillDepartmentCodes, _obj.Info.Actions.ShowDepartments);
                    }
                }

                // Если в формате номера в журнале есть код НОР, то проверять, что у всех указанных в настройке НОР заполнены коды.
                if (register.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.BUCode))
                {
                    var hasBusinessUnitsWithoutCode = _obj.BusinessUnits.Any() ?
                                                      _obj.BusinessUnits.Select(x => x.BusinessUnit).Any(x => x.Code == null) :
                                                      Functions.DocumentRegister.Remote.HasBusinessUnitWithNullCode();

                    if (hasBusinessUnitsWithoutCode)
                    {
                        e.AddWarning(DocumentRegisters.Resources.NeedFillBusinessUnitCodes, _obj.Info.Actions.ShowBusinessUnits);
                    }
                }

                // Если в формате номера в журнале есть код вида документа, то проверять, что у всех указанных в настройке видов документа заполнены коды.
                if (register.NumberFormatItems.Any(f => f.Element == DocumentRegisterNumberFormatItems.Element.DocKindCode))
                {
                    var registrationSettingDocumentKinds = _obj.DocumentKinds.Any() ? _obj.DocumentKinds.Select(x => x.DocumentKind) : DocumentKinds.GetAllCached();
                    var documentKindsWithoutCode         = registrationSettingDocumentKinds.Where(x => x.Code == null);

                    if (documentKindsWithoutCode.Any())
                    {
                        e.AddWarning(DocumentRegisters.Resources.NeedFillDocumentKindCodes, _obj.Info.Actions.ShowDocumentKinds);
                    }
                }
            }
        }
Пример #11
0
        public override void BeforeExecute(Sungero.Reporting.Server.BeforeExecuteEventArgs e)
        {
            #region Параметры

            var reportSessionId = System.Guid.NewGuid().ToString();
            ApprovalRulesConsolidatedReport.ReportSessionId = reportSessionId;
            var includeSubsidiary  = ApprovalRulesConsolidatedReport.IncludeSubsidiary == true;
            var filterDepartment   = ApprovalRulesConsolidatedReport.Department;
            var filterBusinessUnit = ApprovalRulesConsolidatedReport.BusinessUnit;
            var filterDepartmentsForBusinessUnits = ApprovalRulesConsolidatedReport.FilterDepartmentsForBusinessUnits == true;
            var filterDocumentFlow = ApprovalRulesConsolidatedReport.DocumentFlow;
            var filterDocumentKind = ApprovalRulesConsolidatedReport.DocumentKind;
            var filterCategory     = ApprovalRulesConsolidatedReport.Category;

            #endregion

            #region Подготовка начальных данных

            var localizedValueCash = new Dictionary <Sungero.Core.Enumeration, string>();
            localizedValueCash[ApprovalRuleBase.Status.Active] = ApprovalRuleBases.Info.Properties.Status.GetLocalizedValue(ApprovalRuleBase.Status.Active);
            localizedValueCash[ApprovalRuleBase.Status.Draft]  = ApprovalRuleBases.Info.Properties.Status.GetLocalizedValue(ApprovalRuleBase.Status.Draft);

            var documentFlows = new List <Enumeration>()
            {
                ApprovalRuleBase.DocumentFlow.Incoming,
                ApprovalRuleBase.DocumentFlow.Outgoing,
                ApprovalRuleBase.DocumentFlow.Inner,
                ApprovalRuleBase.DocumentFlow.Contracts
            };
            foreach (var flow in documentFlows)
            {
                localizedValueCash[flow] = ApprovalRuleBases.Info.Properties.DocumentFlow.GetLocalizedValue(flow);
            }

            var tableData = new List <Structures.ApprovalRulesConsolidatedReport.TableLine>();
            // Сформировать список активных видов документов, которые можно утверждать.
            // Чтобы не было перезапросов к СП, весь список хранить в памяти.
            var approvalAction = Functions.Module.GetSendAction(OfficialDocuments.Info.Actions.SendForApproval);
            var rules          = ApprovalRuleBases.GetAll().Where(r => r.Status == ApprovalRuleBase.Status.Active ||
                                                                  r.Status == ApprovalRuleBase.Status.Draft).ToList();
            #endregion

            #region Фильтрация

            // НОР.
            List <Company.IBusinessUnit> businessUnits;
            if (filterBusinessUnit != null)
            {
                businessUnits = new List <Company.IBusinessUnit>()
                {
                    filterBusinessUnit
                };
                if (includeSubsidiary)
                {
                    businessUnits = this.GetSubBusinessUnits(businessUnits, Company.BusinessUnits.GetAll().Where(u => u.Status == Status.Active).ToList());
                }
            }
            else
            {
                businessUnits = Company.BusinessUnits.GetAll().Where(u => u.Status == Status.Active).ToList();

                // Для подразделений без НОР.
                if (filterDepartmentsForBusinessUnits)
                {
                    businessUnits.Add(null);
                }
            }

            // Подразделения.
            List <Company.IDepartment> departments;
            if (filterDepartment != null)
            {
                departments = new List <Company.IDepartment>()
                {
                    filterDepartment
                };
                if (includeSubsidiary)
                {
                    departments = this.GetSubDepartments(departments, Company.Departments.GetAll().Where(u => u.Status == Status.Active).ToList());
                }
            }
            else
            {
                departments = Company.Departments.GetAll().Where(u => u.Status == Status.Active).ToList();
            }

            // Виды документов.
            List <IDocumentKind> documentKinds;
            if (filterDocumentKind != null)
            {
                documentKinds = new List <IDocumentKind>()
                {
                    filterDocumentKind
                };
            }
            else
            {
                documentKinds = DocumentKinds.GetAll()
                                .Where(k => k.Status == DocumentKind.Status.Active && k.AvailableActions.Any(a => a.Action == approvalAction))
                                .ToList();
            }

            // Категории договоров.
            List <IDocumentGroupBase> categories;
            if (filterCategory != null)
            {
                categories = new List <IDocumentGroupBase>()
                {
                    filterCategory
                };
            }
            else
            {
                categories = DocumentGroupBases.GetAll().Where(d => d.Status == Status.Active).OrderBy(d => d.Name).ToList();
            }

            // Документопоток.
            if (!string.IsNullOrEmpty(filterDocumentFlow))
            {
                documentFlows = documentFlows.Where(x => localizedValueCash[x] == filterDocumentFlow).ToList();
            }

            #endregion

            var tableLines = new List <Structures.ApprovalRulesConsolidatedReport.TableLine>();

            foreach (var unit in businessUnits)
            {
                var subDepartments = departments.Where(d => (!filterDepartmentsForBusinessUnits && unit != null) || Equals(d.BusinessUnit, unit)).OrderBy(d => d.Name).ToList();

                if (!subDepartments.Any() &&
                    unit != null &&
                    filterDepartment == null)
                {
                    subDepartments.Add(null);
                }

                foreach (var department in subDepartments)
                {
                    foreach (var flow in documentFlows)
                    {
                        foreach (var kind in documentKinds.Where(k => Equals(k.DocumentFlow, flow)))
                        {
                            var subRules = rules
                                           .Where(r => r.DocumentFlow == flow &&
                                                  (!r.DocumentKinds.Any() || r.DocumentKinds.Any(k => Equals(k.DocumentKind, kind))) &&
                                                  (!r.BusinessUnits.Any() || r.BusinessUnits.Any(u => Equals(u.BusinessUnit, unit))) &&
                                                  (!r.Departments.Any() || r.Departments.Any(d => Equals(d.Department, department))));
                            var documentParentType = this.GetDocumentBaseTypeDisplayName(kind);

                            // Отдельно обрабатываем виды документов, для которых настроены категории.
                            var documentKindCategories = categories.Where(c => c.DocumentKinds.Any(d => Equals(d.DocumentKind, kind)));
                            if (documentKindCategories.Any())
                            {
                                foreach (var category in documentKindCategories)
                                {
                                    var categorySubRules = subRules.Where(sr => !sr.DocumentGroups.Any() || sr.DocumentGroups.Any(c => Equals(c.DocumentGroup, category)));
                                    tableLines = this.CreateTableDataLines(categorySubRules, reportSessionId, unit, department, category, flow, kind.Name, documentParentType, localizedValueCash);
                                    tableData.AddRange(tableLines);
                                }
                                continue;
                            }

                            // Если выбрана фильтрация по категории, то в отчет попадают только записи с заполненной категорией.
                            if (filterCategory == null)
                            {
                                // Если не найдено правила для доп. соглашений, тогда указываем, что используется правило договора.
                                var isSupAgreement = kind.DocumentType.DocumentTypeGuid == "265f2c57-6a8a-4a15-833b-ca00e8047fa5";
                                if (isSupAgreement)
                                {
                                    tableLines = this.CreateTableDataLines(subRules, reportSessionId, unit, department, null, flow, kind.Name, documentParentType, localizedValueCash);
                                    foreach (var tableLine in tableLines)
                                    {
                                        if (string.IsNullOrEmpty(tableLine.ApprovalRule))
                                        {
                                            tableLine.ApprovalRule = Reports.Resources.ApprovalRulesConsolidatedReport.ContractualDocumentRule;
                                        }
                                    }
                                    tableData.AddRange(tableLines);
                                    continue;
                                }

                                tableLines = this.CreateTableDataLines(subRules, reportSessionId, unit, department, null, flow, kind.Name, documentParentType, localizedValueCash);
                                tableData.AddRange(tableLines);
                            }
                        }
                    }
                }
            }

            Functions.Module.WriteStructuresToTable(Constants.ApprovalRulesConsolidatedReport.SourceTableName, tableData);
        }
        public virtual void ShowDocumentKinds(Sungero.Domain.Client.ExecuteActionArgs e)
        {
            var documentKinds = DocumentKinds.GetAllCached();

            documentKinds.Show();
        }
Пример #13
0
 public static global::System.Linq.IQueryable <Sungero.Docflow.IDocumentKind> GetDocumentKinds()
 {
     return(DocumentKinds.GetAll().Where(k => k.DocumentFlow == DocumentFlow.Contracts));
 }
Пример #14
0
        public override void BeforeSave(Sungero.Domain.BeforeSaveEventArgs e)
        {
            // Валидация срока рассмотрения.
            if (_obj.DeadlineInDays.HasValue && _obj.DeadlineInDays < 1)
            {
                e.AddError(DocumentKinds.Resources.IncorrectDeadline);
            }
            if (_obj.DeadlineInHours.HasValue && _obj.DeadlineInHours < 1)
            {
                e.AddError(DocumentKinds.Resources.IncorrectDeadline);
            }
            if (_obj.NumberingType != NumberingType.Numerable)
            {
                _obj.AutoNumbering = false;
            }

            // Нельзя изменить тип документа у видов документов МКДО, созданных инициализацией.
            if (!Equals(_obj.DocumentType, _obj.State.Properties.DocumentType.OriginalValue) && Functions.DocumentKind.IsExchangeNativeDocumentKind(_obj))
            {
                e.AddError(DocumentKinds.Resources.CantChange);
            }

            // Обрезать лишние пробелы.
            _obj.Name      = _obj.Name.Trim();
            _obj.ShortName = _obj.ShortName.Trim();

            if (!string.IsNullOrWhiteSpace(_obj.Code))
            {
                _obj.Code = _obj.Code.Trim();
                if (Regex.IsMatch(_obj.Code, @"\s"))
                {
                    e.AddError(_obj.Info.Properties.Code, Docflow.Resources.NoSpacesInCode);
                }
            }

            // Проверить код на пробелы, если свойство изменено.
            if (!string.IsNullOrEmpty(_obj.Code))
            {
                // При изменении кода e.AddError сбрасывается.
                var codeIsChanged = _obj.State.Properties.Code.IsChanged;
                _obj.Code = _obj.Code.Trim();

                if (codeIsChanged && Regex.IsMatch(_obj.Code, @"\s"))
                {
                    e.AddError(_obj.Info.Properties.Code, Company.Resources.NoSpacesInCode);
                }
            }

            // Нельзя закрывать вид документа по умолчанию.
            if (_obj.IsDefault == true && _obj.Status == Status.Closed)
            {
                e.AddError(DocumentKinds.Resources.ClosedDocumentKindCannotBeDefault);
            }

            // Нельзя закрывать вид документа, если по нему есть настройки или правила.
            var canClose = !Functions.Module.GetDocumentKindSettings(_obj).Any();

            if (_obj.Status == Status.Closed && !canClose)
            {
                e.AddError(DocumentKinds.Resources.CantClose, _obj.Info.Actions.ShowSettings);
            }

            if (_obj.IsDefault == true)
            {
                var defaultKinds = DocumentKinds.GetAll(k => k.Status == Status.Active && !Equals(k, _obj) &&
                                                        Equals(k.DocumentType, _obj.DocumentType) && k.IsDefault == true);
                foreach (var kind in defaultKinds)
                {
                    var lockInfo = Locks.GetLockInfo(kind);
                    if (lockInfo != null && lockInfo.IsLocked)
                    {
                        var error = Commons.Resources.LinkedEntityLockedFormat(
                            kind.Name,
                            kind.Id,
                            lockInfo.OwnerName);
                        e.AddError(error);
                    }

                    kind.IsDefault = false;
                }
            }
        }
Пример #15
0
 public static XmlDocumentKind GetXmlDocumentKindOrUnknown(this SourceKind sourceKind)
 => DocumentKinds.TryGetValue(sourceKind, out var kind) ? kind : XmlDocumentKind.Unknown;