ExternalEntityServerFunctions.cs 6.07 KB
using System;
using System.Collections.Generic;
using System.Linq;
using Sungero.Core;
using Sungero.CoreEntities;
using DirRX.Storage.ExternalEntity;
using Newtonsoft.Json.Linq;
using Sungero.Domain.Shared;
using Sungero.Domain.SessionExtensions;

namespace DirRX.Storage.Server
{
  partial class ExternalEntityFunctions
  {
    /// <summary>
    /// Получить список синхронизированных элементов.
    /// </summary>
    /// <returns>Список записей "Ссылки внешней системы".</returns>
    [Remote]
    public IQueryable<DirRX.LongTermArchive.IExternalEntityLink> GetEntityMapping()
    {
      return LongTermArchive.ExternalEntityLinks.GetAll();
    }

    /// <summary>
    /// Синхронизировать запись справочника внешней системы.
    /// </summary>
    /// <param name="externalId">ИД записи справочника внешней системы.</param>
    /// <returns>ИД сущности DirectumRX.</returns>
    [Public]
    public virtual int? GetEntityId(string externalId)
    {
      int? entityId = null;
      if (_obj.MappingMode == Storage.ExternalEntity.MappingMode.NoMapping)
      {
        int outValue;
        if (int.TryParse(externalId, out outValue))
          entityId = outValue;
        else
          return null;
      }
      else
      {
        entityId = LongTermArchive.ExternalEntityLinks.GetAll(x => x.ExtSystemId == _obj.ExternalSystem.SourceUid &&
                                                              x.ExtEntityType == _obj.Uid &&
                                                              x.EntityType == _obj.EntityType &&
                                                              x.ExtEntityId == externalId)
          .OrderByDescending(x => x.Id)
          .Select(x => x.EntityId)
          .FirstOrDefault();
      }
      
      // Получить сущность по ИД найденной записи.
      if (entityId.HasValue)
      {
        try
        {
          using (var session = new Sungero.Domain.Session())
          {
            var entity = session.Get(Sungero.Domain.Shared.TypeExtension.GetTypeByGuid(Guid.Parse(_obj.EntityType)), entityId.Value);
          }
        }
        catch (Exception e)
        {
          Logger.DebugFormat("Ошибка при получении сущности {0} по ее типу {1} и ИД {2}:\n{3}", _obj.Name, _obj.EntityType, entityId.ToString(), e.Message);
          entityId = null;
        }
      }

      return entityId;
    }
    
    /// <summary>
    /// Получить список синхронизированных записей.
    /// </summary>
    /// <returns>Строка в формате json.</returns>
    [Public]
    public virtual string GetRecordsData()
    {
      var json = new JObject();
      
      if (!string.IsNullOrEmpty(_obj.ExternalSystem.Name))
        json.Add("SystemName", _obj.ExternalSystem.Name);
      
      // Получить свойства для идентификации справочника.
      json.Add("SystemUid", _obj.ExternalSystem.SourceUid);
      json.Add("SourceName", _obj.Name);
      json.Add("SourceType", _obj.Uid);
      json.Add("ArchiveName", _obj.EntityName);
      json.Add("ArchiveType", _obj.EntityType);
      
      var entityTypeGuid = Guid.Parse(_obj.EntityType);
      var entityType = Sungero.Domain.Shared.TypeExtension.GetTypeByGuid(entityTypeGuid);
      
      // Получить свойства справочника.
      using (var session = new Sungero.Domain.Session())
      {
        var records = session.GetAll(entityType);
        if (records.Any())
        {
          // Список передаваемых реквизитов. Имя и ИД - обязательны.
          var propertyNames = new List<string>() { "Id", "Name" };
          
          propertyNames.AddRange(_obj.SyncProperties.Where(x => !propertyNames.Contains(x.Name) && x.Name != "_sourceId").Select(x => x.Name));                  
          
          var jsonRecords = new JArray();
          foreach (var record in records)
          {
            // Только для активных записей.
            var properties = record.GetType().GetProperties();
            var propStatus = properties.Where(x => x.Name == "Status").LastOrDefault();

            var jsonProperties = new JObject();
            var archiveId = 0;
            foreach (var propertyName in propertyNames)
            {
              // Получить значения синхронизируемых свойств.
              var property = properties.Where(p => p.Name == propertyName).LastOrDefault();
              if (property != null)
              {
                object propertyValue = property.GetValue(record);
                var propertyStringValue = Sungero.Commons.PublicFunctions.Module.GetValueAsString(propertyValue);
                jsonProperties.Add(propertyName, propertyStringValue);
                
                if (propertyName == "Id")
                  archiveId = (int)propertyValue;
              }
            }
            
            // Получить ИД исходной системы по ИД архивной.
            if (archiveId > 0)
            {
              var link = LongTermArchive.ExternalEntityLinks.GetAll(x => x.ExtSystemId == _obj.ExternalSystem.SourceUid &&
                                                                    x.ExtEntityType == _obj.Uid &&
                                                                    x.EntityType == _obj.EntityType &&
                                                                    x.EntityId == archiveId)
                .OrderByDescending(x => x.Id)
                .FirstOrDefault();
              
              if (link != null)
                jsonProperties.Add("_sourceId", link.ExtEntityId);
            }
            
            jsonRecords.Add(jsonProperties);
          }
          
          if (jsonRecords.Any())
            json.Add("Records", jsonRecords);
        }
      }
      
      return json.ToString();
    }
  }
}