Files
BusinessMgr-2019/SaBusMgrCoreProcs/Procs/Interfaces/SbmInterfaceProcess.cs
T

274 lines
10 KiB
C#

using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.BusinessMgr.Net.Core.Procs.Procs;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Bus;
using Sarand.Net.Standard.Base.Dbas;
using Sarand.Net.Standard.Base.Interfaces;
using Sarand.Net.Standard.Base.IO;
using Sarand.Net.Standard.Base.ItemOptions;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Sarand.Net.Standard.Base.Utils;
using System.IO;
using Sarand.BusinessMgr.Net.Standard.Base.Core;
namespace Sarand.BusinessMgr.Net.Core.Procs.Interfaces
{
//=======================================================================
public abstract class SbmInterfaceProcess : SbmProcess_Base
{
//-------------------------------------------------------------------
// Configuration.
public enum InterfaceProcessCreation
{
None,
OnStartProcessing,
OnLogMessage,
}
public new class Config : SbmProcess_Base.Config
{
protected Config(ISbmUserOrganisationContext userContext) : base(userContext)
{
}
public SysId InterfaceId { get; set; }
public List<SysId> ItemIds { get; } = new List<SysId>();
public InterfaceProcessCreation InterfaceProcessCreation { get; set; } = InterfaceProcessCreation.OnLogMessage;
}
//-------------------------------------------------------------------
// Definitions.
/// <summary>Interface processing groups - used for popup 'Process Interface' form.</summary>
public enum InterfaceProcessGroup
{
Import,
Export,
}
/// <summary>Interface configuration parameters.</summary>
public class InterfaceParams : SbmProcess_Base.ProcessParams
{
}
/// <summary>Process parameters - processing control properties.</summary>
public new class ProcessParams : SbmProcess_Base.ProcessParams
{
}
//-------------------------------------------------------------------
// Data members.
private Config config = null;
private static List<TypeCodeDesc> interfaceProcessGroups = null;
private SaInterface interfaceObj = null;
private SaInterfaceProcess interfaceProcess = null;
//-------------------------------------------------------------------
// Static initialisation.
static SbmInterfaceProcess()
{
// Interface process groups.
interfaceProcessGroups = new List<TypeCodeDesc>();
interfaceProcessGroups.Add(InterfaceProcessGroup.Import, "Import", "Import");
interfaceProcessGroups.Add(InterfaceProcessGroup.Export, "Export", "Export");
}
//-------------------------------------------------------------------
// Construction.
protected SbmInterfaceProcess(Config config) : base(config)
{
this.config = config;
interfaceObj = InterfaceConsole.GetInterfaceById(config.InterfaceId);
// Events.
base.OnProcessStarting += SbmInterfaceProcess_OnProcessStarting;
base.OnProgressInfoUpdated += SbmInterfaceProcess_OnProgressInfoUpdated;
base.OnProcessCompleted += SbmInterfaceProcess_OnProcessCompleted;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
base.Dispose(disposing);
}
//-------------------------------------------------------------------
// Properties.
protected String InterfaceCaptionSuffix { get; set; } = " [Interface]";
protected static List<TypeCodeDesc> InterfaceProcessGroups { get { return new List<TypeCodeDesc>(interfaceProcessGroups); } }
protected SaInterface Interface { get { return interfaceObj; } }
//-------------------------------------------------------------------
// Validate configuration.
protected virtual bool ValidateConfig()
{
return OK;
}
//-------------------------------------------------------------------
// P r o c e s s i n g
//-------------------------------------------------------------------
protected override void ResetProcess()
{
base.ResetProcess();
}
//-------------------------------------------------------------------
// I t e m O p t i o n D e f i n i t i o n s
//-------------------------------------------------------------------
protected static SaItemOptionDfn InitItemOptionDfn(String itemOptionName, String itemOptionCaption, List<TypeCodeDesc> optionContexts = null)
{
SaItemOptionDfn itemOptionDfn = new SaItemOptionDfn();
itemOptionDfn.Name = itemOptionName;
itemOptionDfn.DisplayOptions.Caption = itemOptionCaption;
if (optionContexts != null)
{
itemOptionDfn.DisplayOptions.Contexts.AddRange(optionContexts);
itemOptionDfn.DisplayOptions.RequiresContext = true;
}
itemOptionDfn.DisplayOptions.NonDisplayTemplate = true;
itemOptionDfn.DisplayOptions.CanAddOption = true;
itemOptionDfn.DisplayOptions.CanRemoveOption = true;
return itemOptionDfn;
}
//-------------------------------------------------------------------
// P r o c e s s i n g E v e n t s
//-------------------------------------------------------------------
private void SbmInterfaceProcess_OnProcessStarting(object sender, ProcessStartingEventArgs e)
{
if (config.InterfaceProcessCreation == InterfaceProcessCreation.OnStartProcessing)
OpenInterfaceProcess();
}
private void SbmInterfaceProcess_OnProgressInfoUpdated(object sender, ProgressInfoUpdatedEventArgs e)
{
}
private void SbmInterfaceProcess_OnProcessCompleted(object sender, ProcessCompletedEventArgs e)
{
CloseInterfaceProcess();
}
//-------------------------------------------------------------------
// I n t e r f a c e P r o c e s s
//-------------------------------------------------------------------
private bool OpenInterfaceProcess()
{
if (!SysId.IsValid(config.InterfaceId)) return false;
// Check if interface process already created.
if (interfaceProcess != null && interfaceProcess.InterfaceId.Equals(config.InterfaceId)) return true;
// Create interface process.
SaInterfaceProcessDirection processDirection = SaInterfaceProcessDirection.Inbound;
if (config.Export) processDirection = SaInterfaceProcessDirection.Outbound;
int processSequence = (InterfaceConsole.GetMaxProcessSequence(config.InterfaceId, processDirection, false) + 1);
interfaceProcess = InterfaceConsole.StartInterfaceProcess(config.InterfaceId, processDirection, DateUtil.Format(StartedAt, "yyyyMMddHHmmss"), StartedAt, processSequence, DbUpdateInfo);
return (interfaceProcess != null && interfaceProcess.InterfaceId.Equals(config.InterfaceId));
}
private bool CloseInterfaceProcess()
{
if (interfaceProcess == null) return false;
interfaceProcess.ElapseSecs = ElapsedSecs;
if (OK)
{
interfaceProcess.Status = SaStatus.Completed;
LogInterfaceProcessMessage("Processing completed successfully");
}
else
{
// Process has not completed.
interfaceProcess.Status = SaStatus.Cancelled;
if (HasErrorMessage()) LogInterfaceProcessMessage(GetErrorMessage(), SaMessageLevel.Error);
if (IsInterrupted) LogInterfaceProcessMessage("Processing cancelled by user", SaMessageLevel.Warning);
}
if (InterfaceConsole.StoreInterfaceProcess(interfaceProcess, DbUpdateInfo))
{ }
else if (!HasErrorMessage())
AddErrorMessage("Failed to store interface process: " + InterfaceConsole.ErrorStateMessage);
return true;
}
//-------------------------------------------------------------------
protected bool LogInterfaceProcessMessage(String message, SaMessageLevel messageLevel = SaMessageLevel.Info)
{
if (!OpenInterfaceProcess()) return false;
// Log interface process message.
InterfaceConsole.LogInterfaceProcessMessage(interfaceProcess.Id, DbUpdateInfo, message, messageLevel);
// Errors and warnings wil retunr false.
return (messageLevel == SaMessageLevel.Info || messageLevel == SaMessageLevel.Debug || messageLevel == SaMessageLevel.Trace);
}
//-------------------------------------------------------------------
// I n t e r f a c e D a t a I t e m s
//-------------------------------------------------------------------
protected bool StoreInterfaceDataItem(SaInterfaceDataItem interfaceDataItem, SaStatus processStatus, SaStatus itemStatus, String itemCaption)
{
if (!OK) return false;
DateTime now = DateTime.Now;
// Process status.
if ((int)processStatus > 0)
{
interfaceDataItem.ProcessStatus = processStatus;
interfaceDataItem.ProcessStatusAt = now;
interfaceDataItem.ProcessStatusBy = DbUpdateInfo.UserId;
}
// Item status.
if ((int)itemStatus > 0)
{
interfaceDataItem.ItemStatus = itemStatus;
interfaceDataItem.ItemStatusAt = now;
interfaceDataItem.ItemStatusBy = DbUpdateInfo.UserId;
}
// Store interface data item.
if (!InterfaceConsole.StoreInterfaceDataItem(interfaceDataItem, DbUpdateInfo))
AddErrorMessage("Failed to save Interface data item" + (!StringUtil.IsEmpty(itemCaption) ? " for " + itemCaption : "") + " - " + InterfaceConsole.ErrorStateMessage);
return OK;
}
//-------------------------------------------------------------------
// A r c h i v e F i l e
//-------------------------------------------------------------------
protected bool SaveFileDataToArchive(String archiveRootFolder, String fileName, String fileExtension, String fileData, String fn)
{
if (!OK) return false;
DateTime today = DateTime.Today;
String archiveFolder =
archiveRootFolder.TrimEnd(new char[] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar +
DateUtil.Format(today, "yyyy") + Path.DirectorySeparatorChar +
DateUtil.Format(today, "yyyyMM");
SaLogger.Debug(fn + " Archive folder: " + archiveFolder);
if (FileUtil.ValidateDirectory(archiveFolder, true))
{
for (int fileIdx = 0; fileIdx < 10000; fileIdx++)
{
String archiveFilename = fileName + (fileIdx > 0 ? "." + StringUtil.PadLeft(fileIdx.ToString(), 4, '0') : "") + (!StringUtil.IsEmpty(fileExtension) ? "." + fileExtension : "");
String archivePath = archiveFolder + Path.DirectorySeparatorChar + archiveFilename;
SaLogger.Debug(fn + " Archive path: " + archivePath);
if (!FileUtil.IsFile(archivePath))
{
File.WriteAllText(archivePath, fileData);
break;
}
}
}
else return LogInterfaceProcessMessage("Failed to validate archive folder '" + archiveFolder + "'.", SaMessageLevel.Warning);
return OK;
}
//-------------------------------------------------------------------
}
//=======================================================================
}