ExternalSystemServerFunctions.cs 4.75 KB
using System;
using System.Collections.Generic;
using System.Linq;
using Sungero.Core;
using Sungero.CoreEntities;
using Sungero.Domain.Shared;
using DirRX.Storage.ExternalSystem;
using Newtonsoft.Json.Linq;

namespace DirRX.Storage.Server
{
  partial class ExternalSystemFunctions
  {
    /// <summary>
    /// Получить список справочников системы-источника.
    /// </summary>
    /// <returns>Список записей "Ссылки внешней системы".</returns>
    [Remote]
    public IQueryable<Storage.IExternalEntity> GetExternalEntities()
    {
      // В дочерней сущности настроена UI-фильтрация по контексту, поэтому здесь можно использовать GetAll без фильтра.
      return Storage.ExternalEntities.GetAll();
    }

    /// <summary>
    /// Создать обязательный справочник системы-источника.
    /// </summary>
    /// <param name="entityType">Тип справочника DirectumRX.</param>
    /// <returns>Запись "Справочник системы-источника".</returns>
    public Storage.IExternalEntity CreateRequiredExternalEntity(string entityType)
    {
      try
      {
        var entityMetadata = Sungero.Domain.Shared.TypeExtension.GetTypeByGuid(Guid.Parse(entityType)).GetFinalType().GetEntityMetadata();
        var entity = Storage.ExternalEntities.Create();
        entity.ExternalSystem = _obj;
        entity.EntityType = entityType;
        entity.EntityName = entityMetadata.GetCollectionDisplayName();
        entity.Name = entity.EntityName;
        entity.Uid = entityMetadata.Name;
        if (entityType == Constants.Module.EntityType.DocumentKind || entityType == Constants.Module.EntityType.FileRetentionPeriod)
        {
          entity.MappingMode = Storage.ExternalEntity.MappingMode.NoMapping;
        }
        else
        {
          // Добавить синхронизируемые свойства.
          var filtered = new List<string>();
          
          if (entityType == Constants.Module.EntityType.CaseFile)
            filtered.AddRange("Name,Title,Index,StartDate,EndDate".Split(','));

          entity.MappingMode = Storage.ExternalEntity.MappingMode.Auto;
          foreach (var property in entityMetadata.Properties.Where(x => !filtered.Any() || filtered.Contains(x.Name)))
          {
            var item = entity.SyncProperties.AddNew();
            item.Name = property.Name;
            item.Description = property.GetLocalizedName();
          }
          
          // В конце добавить обязательное служебное свойство _sourceId.
          if (entity.SyncProperties.Any())
          {
            var item = entity.SyncProperties.AddNew();
            item.Name = "_sourceId";
            item.Description = ExternalEntities.Resources.SourceIdDescription.ToString();
          }
        }
        entity.Save();
        return entity;
      }
      catch (Exception e)
      {
        Logger.DebugFormat("Storage. CreateRequiredExternalEntity. Не удалось создать сущность с типом {0}./n{1}", entityType, e.ToString());
      }
      return Storage.ExternalEntities.Null;
    }
    
    /// <summary>
    /// Настройки синхронизации справочников системы-источника.
    /// </summary>
    /// <returns>Настройки синхронизации в виде json-строки.</returns>
    [Public, Remote(IsPure = true)]
    public virtual string GetSyncSettings()
    {
      var json = new JObject();
      
      json.Add("SystemName", _obj.Name);
      json.Add("SystemUid", _obj.SourceUid);
      
      var jsonEntities = new JArray();
      foreach (var item in Storage.ExternalEntities.GetAll(x => x.ExternalSystem.Equals(_obj)))
      {
        var jsonElem = new JObject();
        jsonElem.Add("SourceName", item.Name);
        jsonElem.Add("SourceType", item.Uid);
        jsonElem.Add("ArchiveName", item.EntityName);
        jsonElem.Add("ArchiveType", item.EntityType);
        jsonElem.Add("SyncMode", item.MappingMode.ToString());
        if (item.MappingMode == Storage.ExternalEntity.MappingMode.Auto)
        {
          var jsonProps = new JArray();
          foreach (var propItem in item.SyncProperties)
          {
            var jsonProp = new JObject();
            jsonProp.Add("Name", propItem.Name);
            jsonProp.Add("Description", propItem.Description);
            jsonProps.Add(jsonProp);
          }
          jsonElem.Add("Properties", jsonProps);
        }
        
        jsonEntities.Add(jsonElem);
      }
      
      json.Add("Entities", jsonEntities);

      return json.ToString();
    }
  }
}