ModuleClientFunctions.cs 16.1 KB
using System;
using System.Collections.Generic;
using System.Linq;
using Sungero.Core;
using Sungero.CoreEntities;

namespace DirRX.Storage.Client
{
  public class ModuleFunctions
  {
    /// <summary>
    /// Создать реестр описей.
    /// </summary>
    public virtual void CreateConsolidatedInventoryList()
    {
      DirRX.Storage.PublicFunctions.Module.ShowConsolidatedInventoryListCreationDialog();
    }
    
    /// <summary>
    /// Создать сводные описи электронных дел.
    /// </summary>
    public virtual void CreateConsolidatedInventories()
    {
      DirRX.Storage.PublicFunctions.Module.ShowConsolidatedInventoryCreationDialog();
    }

    /// <summary>
    /// Создать и отобразить список фондов.
    /// </summary>
    public virtual void CreateFundsList()
    {
      DirRX.Storage.PublicFunctions.Module.ShowFundsListCreationDialog();
    }
    
    /// <summary>
    /// Отобразить настройки модуля "Описи электронных дел".
    /// </summary>
    public virtual void ShowCaseInventorySettings()
    {
      DirRX.CaseArchiving.PublicFunctions.Module.ShowCaseInventorySettingsDialog();
    }

    /// <summary>
    /// Создать и отобразить акт уничтожения.
    /// </summary>
    public virtual void CreateDestructionAct()
    {
      DirRX.Storage.PublicFunctions.Module.ShowDestructionActCreationDialog();
    }
    
    /// <summary>
    /// Выполнить инцидентную проверку.
    /// </summary>
    public virtual void StartVerification()
    {
      DirRX.Storage.PublicFunctions.Module.ShowIncidentVerificationDialog();
    }

    /// <summary>
    /// Создать описи электронных дел.
    /// </summary>
    public virtual void CreateCaseInventories()
    {
      DirRX.CaseArchiving.PublicFunctions.Module.ShowCaseInventoryCreationDialog();
    }

    /// <summary>
    /// Отобразить настройки модуля "Передача в архив".
    /// </summary>
    public virtual void ShowTransferSettings()
    {
      DirRX.Container.PublicFunctions.ArchiveSetting.GetSettings().Show();
    }
    
    /// <summary>
    /// Создать запрос в архив.
    /// </summary>
    public virtual void ShowRequestProcessingTaskDialog()
    {
      DirRX.Storage.PublicFunctions.Module.CreateRequestProcessingTaskDialog();
    }

    /// <summary>
    /// Отобразить настройки модуля "Долговременный архив".
    /// </summary>
    [Public]
    public virtual void ShowStorageSettings()
    {
      var dialog = Dialogs.CreateInputDialog(Resources.MainSettingsDialogTitle);
      
      // Число дней до окончания действия подписи.
      var daysLeftParam = (int)Sungero.Docflow.PublicFunctions.Module.Remote.GetDocflowParamsNumbericValue(Constants.Module.DocflowParams.DaysBeforeImproveKey);
      var minDaysBeforeImprove = dialog.AddInteger(Resources.MainSettingsDaysBeforeImproveLabel, true, daysLeftParam);
      var improveAfterImport = Sungero.Docflow.PublicFunctions.Module.Remote.GetDocflowParamsStringValue(Constants.Module.DocflowParams.ImproveAfterImportKey) == "true";
      var improve = dialog.AddBoolean(Resources.MainSettingsImproveAfterImportLabel, improveAfterImport);
      
      var verificationInterval = (int)Sungero.Docflow.PublicFunctions.Module.Remote.GetDocflowParamsNumbericValue(Constants.Module.DocflowParams.VerificationIntervalKey);
      var verificationIntervalSelector = dialog.AddInteger(Resources.MainSettingsVerificationIntervalLabel, true, verificationInterval);
      var verificationResponsible = Storage.PublicFunctions.Module.Remote.GetVerificationResponsible();
      var verificationResponsibleSelector = dialog.AddSelect(Resources.MainSettingsVerificationResponsibleLabel, true, verificationResponsible);
      var requestResponsible = Storage.PublicFunctions.Module.Remote.GetRequestResponsible();
      var requestResponsibleSelector = dialog.AddSelect(Resources.MainSettingsRequestResponsibleLabel, true, requestResponsible);
      
      // Руководитель архива.
      var archiveManager = Storage.PublicFunctions.Module.Remote.GetArchiveManager();
      var archiveManagerSelector = dialog.AddSelect(Resources.MainSettingsArchiveManager, false, archiveManager);
      
      dialog.SetOnRefresh(e =>
                          {
                            if (e.IsValid)
                            {
                              if (minDaysBeforeImprove.Value < 1 || minDaysBeforeImprove.Value > 366)
                                e.AddError(Resources.MainSettingsDaysBeforeImproveWarning);
                              if (verificationIntervalSelector.Value.GetValueOrDefault() <= 0)
                                e.AddError(Resources.MainSettingsVerificationIntervalWarning);
                            }
                          });
      
      var changeVeridicationDateSelector = dialog.AddBoolean(Resources.MainSettingsChangeVerificationDateLabel, false);
      
      if (dialog.Show() == DialogButtons.Ok)
      {
        if (improve.Value != improveAfterImport || minDaysBeforeImprove.Value != daysLeftParam || verificationIntervalSelector.Value != verificationInterval)
          Functions.Module.Remote.SetMainSettings(verificationIntervalSelector.Value.GetValueOrDefault(), minDaysBeforeImprove.Value.GetValueOrDefault(), improve.Value == true);

        if (requestResponsibleSelector.Value != requestResponsible)
          Storage.PublicFunctions.Module.Remote.SetRequestResponsible(requestResponsibleSelector.Value);
        
        if (verificationResponsibleSelector.Value != verificationResponsible)
          Storage.PublicFunctions.Module.Remote.SetVerificationResponsible(verificationResponsibleSelector.Value);
        
        if (changeVeridicationDateSelector.Value.HasValue && changeVeridicationDateSelector.Value.Value == true)
        {
          Dialogs.NotifyMessage(Resources.MainSettingsChangeVerificationDateNotification);
          Storage.PublicFunctions.Module.Remote.SetVerificationTermForAllDocuments();
        }
        
        if (archiveManagerSelector.Value != archiveManager)
          Storage.PublicFunctions.Module.Remote.SetArchiveManager(archiveManagerSelector.Value);
      }
    }
    
    /// <summary>
    /// Отобразить диалог для выполнения инцидентных проверок.
    /// </summary>
    [Public]
    public virtual void ShowIncidentVerificationDialog()
    {
      var dialog = Dialogs.CreateInputDialog(Storage.Resources.VerificationDialogTitle);
      
      // Параметры проверки.
      var reason = dialog.AddString(Storage.Resources.VerificationDialogReasonLabel, true);
      var responsible = dialog.AddSelect(Storage.Resources.VerificationDialogResponsibleLabel, true, Storage.PublicFunctions.Module.Remote.GetVerificationResponsible());

      // Критерии отбора документов.
      var documentKinds = dialog.AddSelectMany(Storage.Resources.VerificationDialogDocumentKindsLabel, false, Sungero.Docflow.DocumentKinds.Null);
      var documentDepartments = dialog.AddSelectMany(Storage.Resources.VerificationDialogDepartmentsLabel, false, Sungero.Company.Departments.Null);
      var creationDateBegin = dialog.AddDate(Storage.Resources.VerificationDialogCreationDateBeginLabel, false);
      var creationDateEnd = dialog.AddDate(Storage.Resources.VerificationDialogCreationDateEndLabel, false);
      
      if (dialog.Show() == DialogButtons.Ok)
      {
        var ids = Storage.PublicFunctions.Module.Remote.GetArchiveDocumentsForVerification(documentKinds.Value.Select(x => x.Id).ToList(),
                                                                                           documentDepartments.Value.Select(x => x.Id).ToList(),
                                                                                           creationDateBegin.Value,
                                                                                           creationDateEnd.Value);
        if (ids.Any())
        {
          Storage.PublicFunctions.Module.Remote.EnqueueArchiveDocumentsVerification(ids, reason.Value, responsible.Value);
          Dialogs.NotifyMessage(Storage.Resources.VerificationDialogStartMessageFormat(ids.Count));
        }
        else
          Dialogs.ShowMessage(Storage.Resources.VerificationDialogDocumentsNotFoundWarning, MessageType.Warning);
      }
    }
    
    /// <summary>
    /// Отобразить диалог для формирования актов на уничтожение.
    /// </summary>
    [Public]
    public virtual void ShowDestructionActCreationDialog()
    {
      // Проверить наличие дел для включения в акт.
      var caseFiles = Storage.PublicFunctions.Module.Remote.GetCaseFilesToDestroy();
      
      if (!caseFiles.Any())
      {
        Dialogs.ShowMessage(Storage.Resources.CreateActDialogCaseFileNotFoundWarning, MessageType.Warning);
        return;
      }
      
      var archivists = DirRX.CaseArchiving.PublicFunctions.Module.Remote.GetEmployeesForArchivistRole();
      
      if (!archivists.Any())
      {
        Dialogs.ShowMessage("Не удалось определить архивиста из роли.");
        return;
      }
      
      var departments = new List<Sungero.Company.IDepartment>();
      
      // Формировать акты в разрезе подразделений, если включена соответствующая настройка.
      if (CaseArchiving.PublicFunctions.Module.Remote.IsCreateCaseInventoryByDepartments())
        departments.AddRange(caseFiles.Where(x => x.Department != null).Select(x => x.Department).Distinct());

      // Формировать акты в разрезе статусов дел (завершенные или архивные).
      var stages = caseFiles.Select(x => x.LTAStageDirRX).Distinct().ToList();
      var stageNames = stages.Select(x => DirRX.LongTermArchive.CaseFiles.Info.Properties.LTAStageDirRX.GetLocalizedValue(x)).ToList();
      
      // Запросить параметры для формирования акта.
      var dialog = Dialogs.CreateInputDialog(Storage.Resources.CreateActDialogTitle);
      var stageSelector = dialog.AddSelect(Storage.Resources.CreateInventoriesDialogStageLabel, true, stageNames.First()).From(stageNames.ToArray());
      stageSelector.IsEnabled = stages.Count > 1;
      var archivistSelector = dialog.AddSelect(Storage.Resources.CreateInventoriesDialogArchivistLabel, true, archivists.First()).From(archivists);
      archivistSelector.IsEnabled = archivists.Count > 1;
      var departmentSelector = dialog.AddSelect(Storage.Resources.CreateInventoriesDialogDepartmentLabel, true, departments.FirstOrDefault()).From(departments);
      if (!departments.Any())
      {
        departmentSelector.IsRequired = false;
        departmentSelector.IsVisible = false;
      }
      else
        departmentSelector.IsEnabled = departments.Count > 1;
      
      if (dialog.Show() == DialogButtons.Ok)
      {
        // Создать и отобразить акт.
        var stage = stages[stageNames.IndexOf(stageSelector.Value)];
        caseFiles = caseFiles.Where(x => x.LTAStageDirRX == stage);
        if (departments.Any())
          caseFiles = caseFiles.Where(x => x.Department.Id == departmentSelector.Value.Id);
        
        var document = Storage.PublicFunctions.Module.Remote.CreateDestructionAct(caseFiles.ToList(), archivistSelector.Value, departments.Any() ? departmentSelector.Value : null);
        
        // Сформировать тело документа из отчета.
        Storage.PublicFunctions.DestructionAct.GenerateLastVersionFromReport(document);
        
        // Отправить акт на верификацию.
        Storage.PublicFunctions.Module.SendDestructionActForVerification(document);

        document.Edit();
        
      }
    }
    
    /// <summary>
    /// Отобразить диалог для формирования списка фондов.
    /// </summary>
    [Public]
    public virtual void ShowFundsListCreationDialog()
    {
      var dialog = Dialogs.CreateInputDialog(Storage.Resources.CreateFundsListDialogTitle);
      var year = dialog.AddInteger(Storage.Resources.CreateFundsListDialogYearLabel, true, Calendar.Today.Year);
      if (dialog.Show() == DialogButtons.Ok)
      {
        if (year != null)
        {
          // Фонды на указанный период
          var funds = Storage.PublicFunctions.Module.GetFundsToList((int)year.Value);
          
          // Если на указанный период нет фондов - вывести ошибку
          if (!funds.Any())
          {
            Dialogs.ShowMessage("На указанный период нет фондов", MessageType.Warning);
            return;
          }
          
          // Список фондов за указанынй период.
          var fundsList = Storage.PublicFunctions.Module.GetFundsList((int)year.Value);
          
          // Если список уже есть - открыть новое диалоговое окно с выбором: прочитать или переформировать.
          if (fundsList.Count() > 0)
          {
            var fundslListExistsDialog = Dialogs.CreateInputDialog(DirRX.Storage.Resources.CreateFundsListInformation, DirRX.Storage.Resources.CreateFundsListExistsFormat((int)year.Value));
            var createNewList = fundslListExistsDialog.Buttons.AddCustom(DirRX.Storage.Resources.CreateFundsListCreateVersion);
            var showFundsList = fundslListExistsDialog.Buttons.AddCustom(DirRX.Storage.Resources.CreateFundsListShowExistingDocument);
            
            var result = fundslListExistsDialog.Show();
            
            if (result == createNewList)
            {
              Storage.PublicFunctions.FundsList.GenerateLastVersionFromReport(fundsList.FirstOrDefault()).Edit();
            }
            
            if (result == showFundsList)
            {
              Storage.FundsLists.GetAll(x => x.FundsDate.Value.Year == (int)year.Value).FirstOrDefault().Edit();
            }
          }
          else
          {
            // Создать и отобразить список.
            Storage.PublicFunctions.Module.Remote.CreateFundsList((int)year.Value).Edit();
          }
        }
      }
    }
    
    /// <summary>
    /// Создать реестр описей.
    /// </summary>
    [Public]
    public virtual void ShowConsolidatedInventoryListCreationDialog()
    {
      var approvedAnnualSections = Functions.Module.Remote.GetApprovedAnnualSections();
      
      if (!approvedAnnualSections.Any())
      {
        Dialogs.ShowMessage(Resources.ConsolidatedInventoryListAnnualSectionWasNotFound, MessageType.Warning);
        return;
      }
      
      var dialog = Dialogs.CreateConfirmDialog(Resources.ConsolidatedInventoryListCreatingConfirm);
      if (dialog.Show() == true)
      {
        var consolidatedInventoryList = Storage.PublicFunctions.Module.Remote.CreateConsolidatedInventoryList();
        if (consolidatedInventoryList != null)
          consolidatedInventoryList.Open();
      }
    }
    
    /// <summary>
    /// Отобразить дела для создания сводной описи.
    /// </summary>
    [Public]
    public virtual void ShowConsolidatedInventoryCreationDialog()
    {
      var query = PublicFunctions.Module.Remote.GetCaseFilesToInventory();
      
      if (!query.Any())
      {
        Dialogs.ShowMessage(ConsolidatedInventories.Resources.WarningCaseFilesNotFound, MessageType.Warning);
        return;
      }
      query.ShowModal();
    }

    /// <summary>
    /// Отобразить карточку задачи "Запрос в архив".
    /// </summary>
    [Public]
    public virtual void CreateRequestProcessingTaskDialog()
    {
      // Отобразить карточку задачи "Запросы в архив".
      Functions.Module.Remote.CreateRequestProcessingTask().Show();
    }
    
  }
}