ModuleInitializer.cs 11.5 KB
using System;
using System.Collections.Generic;
using System.Linq;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Domain.Initialization;

namespace DirRX.CaseArchiving.Server
{
  public partial class ModuleInitializer
  {

    public override void Initializing(Sungero.Domain.ModuleInitializingEventArgs e)
    {
      CreateRoles();
      CreateDocumentTypes();
      CreateDocumentKinds();
      CreateApprovalRules();
      GrantAccessRights();
      SetDefaultSettings();
      SetCaseFileDefaultStage();
    }
    
    /// <summary>
    /// Заполнить незаполненное состояние в уже существующих делах.
    /// </summary>
    public static void SetCaseFileDefaultStage()
    {
      InitializationLogger.DebugFormat("Init: Set case files default stage");
      foreach (var caseFile in LongTermArchive.CaseFiles.GetAll(x => !x.LTAStageDirRX.HasValue))
      {
        caseFile.LTAStageDirRX = LongTermArchive.CaseFile.LTAStageDirRX.InWork;
        caseFile.Save();
      }
    }
    
    /// <summary>
    /// Выдать права.
    /// </summary>
    public static void GrantAccessRights()
    {
      var allUsers = Roles.AllUsers;
      if (allUsers != null)
      {
        InitializationLogger.DebugFormat("Init: Grant access rights");        

        // Права на создание и изменение дел - делопроизводителям.
        var clerksRole = Sungero.CoreEntities.Roles.GetAll(x => x.Sid == Constants.Module.Initialize.ClerksRole).SingleOrDefault();
        if (clerksRole != null)
        {          
          LongTermArchive.CaseFiles.AccessRights.Grant(clerksRole, DefaultAccessRightsTypes.Create);
          LongTermArchive.CaseFiles.AccessRights.Grant(clerksRole, DefaultAccessRightsTypes.Change);
          LongTermArchive.CaseFiles.AccessRights.Save();         
        }

        // Право на создание описи - всем.
        CaseArchiving.CaseInventories.AccessRights.Grant(allUsers, DefaultAccessRightsTypes.Create);
        
        // Право на утверждение описи - архивисту.
        var archivistRole = Roles.GetAll(x => x.Sid == Constants.Module.Initialize.ArchivistRoleGuid).FirstOrDefault();
        if (archivistRole != null)
        {
          CaseArchiving.CaseInventories.AccessRights.Grant(archivistRole, DefaultAccessRightsTypes.Approve);
          
          // Право на изменение дел - архивисту.
          LongTermArchive.CaseFiles.AccessRights.Grant(archivistRole, DefaultAccessRightsTypes.Change);
          LongTermArchive.CaseFiles.AccessRights.Save();
        }
        
        CaseArchiving.CaseInventories.AccessRights.Save();
        
        // Право на создание задачи на верификацию - всем.
        CaseArchiving.VerificationTasks.AccessRights.Grant(allUsers, DefaultAccessRightsTypes.Create);
        CaseArchiving.VerificationTasks.AccessRights.Save();
      }
    }
    
    /// <summary>
    /// Создать правило согласования для инвентарных описей.
    /// </summary>
    public static void CreateApprovalRules()
    {
      InitializationLogger.DebugFormat("Init: Create approval rule {0}", Resources.RuleCaseInventoryDefaultRuleName);
      var caseInventoryDocumentKinds = PublicFunctions.Module.Remote.GetCaseInvenoryDocumentKinds().ToList();
      
      // Проверить нет ли уже правила по умолчанию для описей.
      if (!Sungero.Docflow.ApprovalRuleBases.GetAll(r => r.IsDefaultRule == true && r.DocumentFlow == Sungero.Docflow.ApprovalRuleBase.DocumentFlow.Inner)
          .Any(r => r.DocumentKinds.Any(d => caseInventoryDocumentKinds.Contains(d.DocumentKind))))
      {
        // Создать правило, заполнить карточку.
        var rule = Sungero.Docflow.ApprovalRules.Create();
        rule.Status = Sungero.Docflow.ApprovalRuleBase.Status.Active;
        rule.Name = Resources.RuleCaseInventoryDefaultRuleName;
        rule.DocumentFlow = Sungero.Docflow.ApprovalRuleBase.DocumentFlow.Inner;
        rule.ReworkDeadline = 2;
        rule.IsDefaultRule = true;
        
        if (caseInventoryDocumentKinds != null)
          foreach (var item in caseInventoryDocumentKinds)
            rule.DocumentKinds.AddNew().DocumentKind = item;
        
        // Добавить этап утверждения описи архивистом.
        var stage = Sungero.Docflow.ApprovalStages.Create();
        stage.StageType = Sungero.Docflow.ApprovalStage.StageType.Sign;
        stage.Name = Resources.RuleApprovalWithArchivistStageName;
        stage.DeadlineInDays = 2;
        stage.NeedStrongSign = false;
        
        rule.Stages.AddNew().Stage = stage;
        
        rule.Save();
      }
      
      #region Правило для описей бумажных дел.
      InitializationLogger.DebugFormat("Init: Create approval rule {0}", Resources.RulePaperCaseInventoryDefaultRuleName);
      var paperCaseInventoryDocumentKinds = PublicFunctions.Module.Remote.GetPaperCaseInvenoryDocumentKinds().ToList();
      
      // Проверить нет ли уже правила по умолчанию для описей.
      if (Sungero.Docflow.ApprovalRuleBases.GetAll(r => r.IsDefaultRule == true && r.DocumentFlow == Sungero.Docflow.ApprovalRuleBase.DocumentFlow.Inner)
          .Any(r => r.DocumentKinds.Any(d => paperCaseInventoryDocumentKinds.Contains(d.DocumentKind))))
        return;
      
      // Создать правило, заполнить карточку.
      var rulePaper = Sungero.Docflow.ApprovalRules.Create();
      rulePaper.Status = Sungero.Docflow.ApprovalRuleBase.Status.Active;
      rulePaper.Name = Resources.RulePaperCaseInventoryDefaultRuleName;
      rulePaper.DocumentFlow = Sungero.Docflow.ApprovalRuleBase.DocumentFlow.Inner;
      rulePaper.ReworkDeadline = 2;
      rulePaper.IsDefaultRule = true;

      if (paperCaseInventoryDocumentKinds != null)
        foreach (var item in paperCaseInventoryDocumentKinds)
          rulePaper.DocumentKinds.AddNew().DocumentKind = item;
      
      // Задание архивисту на согласование.
      var stageArchive = Sungero.Docflow.ApprovalStages.Create();
      stageArchive.StageType = Sungero.Docflow.ApprovalStage.StageType.Approvers;
      stageArchive.Name = Resources.RuleStageArchivistName;
      stageArchive.Subject = Resources.RuleStageArchivistSubject;
      stageArchive.DeadlineInDays = 1;
      stageArchive.AllowSendToRework = true;
      stageArchive.ReworkPerformer = Roles.GetAll().FirstOrDefault(x => x.Sid == Constants.Module.Initialize.ClerksRole);
      stageArchive.Recipients.AddNew().Recipient = Roles.GetAll().FirstOrDefault(x => x.Sid == Constants.Module.Initialize.ArchivistRoleGuid);
      stageArchive.Save();
      rulePaper.Stages.AddNew().Stage = stageArchive;
      
      // Задание на передачу дел Делопроизводителем.
      var stageClerkTransfer = Sungero.Docflow.ApprovalStages.Create();
      stageClerkTransfer.StageType = Sungero.Docflow.ApprovalStage.StageType.SimpleAgr;
      stageClerkTransfer.Name = "Задание делопроизводителю";
      stageClerkTransfer.Subject = "Передайте дела в архив";
      stageClerkTransfer.DeadlineInDays = 1;
      stageClerkTransfer.ApprovalRoles.AddNew().ApprovalRole = Sungero.Docflow.ApprovalRoles.GetAll().FirstOrDefault(x => x.Type == Sungero.Docflow.ApprovalRoleBase.Type.Initiator);      
      stageClerkTransfer.Save();
      rulePaper.Stages.AddNew().Stage = stageClerkTransfer;
      
      // Добавить этап утверждения описи архивистом.
      var stageManagerSign = Sungero.Docflow.ApprovalStages.Create();
      stageManagerSign.StageType = Sungero.Docflow.ApprovalStage.StageType.Sign;
      stageManagerSign.Name = Resources.RuleApprovalWithArchivistStageName;
      stageManagerSign.Subject = "Подпишите";
      stageManagerSign.NeedStrongSign = false;
      stageManagerSign.DeadlineInDays = 1;
      stageManagerSign.Save();
      rulePaper.Stages.AddNew().Stage = stageManagerSign;
      
      Sungero.Docflow.PublicFunctions.ApprovalRuleBase.CreateAutoTransitions(rulePaper);
      rulePaper.Save();
      #endregion
    }
    
    /// <summary>
    /// Установить параметры решения по умолчанию.
    /// </summary>
    public static void SetDefaultSettings()
    {
      var paramValue = Sungero.Docflow.PublicFunctions.Module.GetDocflowParamsValue(Constants.Module.DocflowParams.UseCaseInventoryInArchiveSystemKey);
      if (paramValue is DBNull || paramValue == null)
      {
        Sungero.Docflow.PublicFunctions.Module.InsertOrUpdateDocflowParam(Constants.Module.DocflowParams.UseCaseInventoryInSourceSystemKey, string.Empty);
        Sungero.Docflow.PublicFunctions.Module.InsertOrUpdateDocflowParam(Constants.Module.DocflowParams.UseCaseInventoryInArchiveSystemKey, "true");
      }
    }
    
    /// <summary>
    /// Создать роли.
    /// </summary>
    public static void CreateRoles()
    {
      Sungero.Docflow.PublicInitializationFunctions.Module.CreateRole(Resources.RoleArchivistName, Resources.RoleArchivistDescription, Constants.Module.Initialize.ArchivistRoleGuid);
    }
    
    /// <summary>
    /// Создать типы документов.
    /// </summary>
    public static void CreateDocumentTypes()
    {
      Sungero.Docflow.PublicInitializationFunctions.Module.CreateDocumentType(CaseInventories.Info.LocalizedName,
                                                                              CaseInventory.ClassTypeGuid,
                                                                              Sungero.Docflow.DocumentType.DocumentFlow.Inner,
                                                                              true);
    }
    
    /// <summary>
    /// Создать виды документов.
    /// </summary>
    public static void CreateDocumentKinds()
    {
      Sungero.Docflow.PublicInitializationFunctions.Module.CreateDocumentKind(Resources.InitCaseInvenoryDocumentKindName,
                                                                              Resources.InitCaseInvenoryDocumentKindName,
                                                                              Sungero.Docflow.DocumentKind.NumberingType.Numerable,
                                                                              Sungero.Docflow.DocumentKind.DocumentFlow.Inner,
                                                                              true, false, CaseInventory.ClassTypeGuid, null,
                                                                              Constants.Module.Initialize.CaseInventoryDocumentKind, true);
      
      Sungero.Docflow.PublicInitializationFunctions.Module.CreateDocumentKind(Resources.InitPaperCaseInvenoryDocumentKindName,
                                                                              Resources.InitPaperCaseInvenoryDocumentKindName,
                                                                              Sungero.Docflow.DocumentKind.NumberingType.Numerable,
                                                                              Sungero.Docflow.DocumentKind.DocumentFlow.Inner,
                                                                              true, false, CaseInventory.ClassTypeGuid, null,
                                                                              Constants.Module.Initialize.PaperCaseInventoryDocumentKind, false);
    }
    
  }
}