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());
        }
        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);
        }
Beispiel #3
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);
        }
Beispiel #4
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);
        }
        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)));
        }
Beispiel #6
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);
        }
Beispiel #7
0
 public static global::System.Linq.IQueryable <Sungero.Docflow.IDocumentKind> GetDocumentKinds()
 {
     return(DocumentKinds.GetAll().Where(k => k.DocumentFlow == DocumentFlow.Contracts));
 }
        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;
                }
            }
        }