private Action GetExecuteAction(EpsJob epsJob, Action <Mock <ISession> > sessionMockSetup = null) { var transaction = new Mock <ITransaction>(); transaction.Setup(i => i.Commit()); var session = new Mock <ISession>(); session.Setup(i => i.BeginTransaction()).Returns(transaction.Object); session.Setup(i => i.Get <EpsJob>(epsJob.JobCode)).Returns(epsJob); if (sessionMockSetup != null) { sessionMockSetup(session); } var sessionFactory = new Mock <ISessionFactory>(); sessionFactory.Setup(i => i.OpenSession()).Returns(session.Object); var job = new EpsJobExecutor(sessionFactory.Object); var executionContext = new Mock <IJobExecutionContext>(); var data = new JobDataMap { { "EpsJobCode", epsJob.JobCode } }; executionContext.SetupGet(i => i.MergedJobDataMap).Returns(data); return(() => { job.Execute(executionContext.Object); }); }
/// <summary> /// Проверка необходимости запуска. /// </summary> public static bool IsNeedToStart(EpsJob job, ISession session) { if (job.CPV_List == null || !job.CPV_List.Any()) { return(true); } // ищем нужную CPV var checkCpv = job.CPV_List.FirstOrDefault(i => i.CustomParam.CustomParamCode == CpvCheckSql); if (checkCpv == null) { return(true); } // достаем sql var sql = checkCpv.CPVValue; if (string.IsNullOrEmpty(sql)) { throw new Exception( $"In job '{job.JobCode}' cpv '{checkCpv.CustomParam.CustomParamCode}' is empty. Please enter value or remove it."); } // запускаем sql проверки var sqlReult = session.CreateSQLQuery(sql).List(); // если ничего не вернулось - запускать не нужно return(sqlReult.Any()); }
public void When_job_has_cpv_with_check_filter_false_than_execution_will_interrupt() { var epsJob = new EpsJob { JobCode = "10", JobHandler = 100, JobLocked = false, CPV_List = new HashSet <EpsJobCPV>(new[] { new EpsJobCPV() { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckRoot } }, new EpsJobCPV() { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckSql }, CPVValue = "select 1 from dual where 1 = 0" } }) }; var action = GetExecuteAction(epsJob, s => { var sqlQuery = new Mock <ISQLQuery>(); sqlQuery.Setup(i => i.List()).Returns(new List <object>()); s.Setup(i => i.CreateSQLQuery("select 1 from dual where 1 = 0")).Returns(sqlQuery.Object); }); action.ShouldThrow <JobExecutionException>( string.Format("Job '{0}' shouldn't be executed. Check return 0 rows.", epsJob.JobCode)); }
public void When_job_has_cpv_with_check_filter_and_cpvvalue_is_empty_than_expect_exception() { var epsJob = new EpsJob { JobCode = "10", JobHandler = 100, JobLocked = false, CPV_List = new HashSet <EpsJobCPV>(new[] { new EpsJobCPV() { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckRoot } }, new EpsJobCPV() { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckSql }, CPVValue = null } }) }; var action = GetExecuteAction(epsJob, s => { var sqlQuery = new Mock <ISQLQuery>(); sqlQuery.Setup(i => i.List()).Returns(new List <object>()); s.Setup(i => i.CreateSQLQuery("select 1 from dual where 1 = 0")).Returns(sqlQuery.Object); }); action.ShouldThrow <Exception>( $"In job '{epsJob.JobCode}' cpv '{EpsHelper.CpvCheckSql}' is empty. Please enter value or remove it."); }
public void SmokeTest() { var reportConfig = new TestEpsReportConfig() { ReportCode = "ReportCode", ConnectionString = "ConnectionString", ReportFullFileName = Path.Combine(TestContext.CurrentContext.TestDirectory, "TELabel.frx"), ReportName = "ReportName", ReportResultFileName = "ReportResultFileName" }; var shareTaskConfig = new TestEpsTaskConfig { ExportType = new ExportType { Format = "txt", Encoding = Encoding.ASCII, Spacelife = true }, IsNeedReserveCopy = true, IsNeedZip = true, TaskId = 100500, TaskOrder = 1, TaskExecutorType = EpsTaskExecutorTypes.SHARE, HandleTaskComplete = (i, exception, arg3) => { } }; var jobConfig = new TestEpsJobConfig { JobId = 42, Reports = new[] { reportConfig }, Tasks = new[] { shareTaskConfig } }; var epsConfig = new EpsConfiguration { ArchPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "ArchPath"), ReportPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "ReportPath"), TmpPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "ReportPath"), OdacConnectionString = "OdacConnectionString", OdbcConnectionString = "OdbcConnectionString" }; var archiver = new Archiver(); var moqTaskFactory = new Mock <IEpsTaskFactory>(); moqTaskFactory.Setup(i => i.CreateTask(shareTaskConfig)) .Returns(new EpsTaskShareExport(shareTaskConfig, epsConfig, archiver)); var moqReportFactory = new Mock <IEpsReportFactory>(); moqReportFactory.Setup(i => i.CreateReport(reportConfig)) .Returns(new EpsFastReport(reportConfig, epsConfig, new ReportExporterFactory())); using (var job = new EpsJob(jobConfig, epsConfig, moqTaskFactory.Object, moqReportFactory.Object)) job.Execute(); }
public void When_job_handler_is_empty_than_expect_exception() { var epsJob = new EpsJob { JobCode = "10" }; var action = GetExecuteAction(epsJob); action.ShouldThrow <JobExecutionException>() .And.Message.ShouldBeEquivalentTo( string.Format("Job '{0}' has no JobHandler. Please check job settings.", epsJob.JobCode)); }
public void When_job_is_locked_than_expect_lock_exception() { var epsJob = new EpsJob { JobCode = "10", JobHandler = 100, JobLocked = true }; var action = GetExecuteAction(epsJob); action.ShouldThrow <JobExecutionException>() .And.Message.ShouldBeEquivalentTo(string.Format("Eps job '{0}' is locked.", epsJob.JobCode)); }
public void When_job_has_cpv_with_split_query_returns_0_rows_job_will_be_interrupted() { var epsJob = new EpsJob { JobCode = "10", JobHandler = 100, JobLocked = false, CPV_List = new HashSet <EpsJobCPV> { new EpsJobCPV { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckRoot } }, new EpsJobCPV { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckSql }, CPVValue = "select 1 from dual where 1 = 1" }, new EpsJobCPV() { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvSplitSql }, CPVValue = "select 1 from dual where 1 = 0" } } }; var action = GetExecuteAction(epsJob, s => { var sqlTrueQuery = new Mock <ISQLQuery>(); sqlTrueQuery.Setup(i => i.List()).Returns(new[] { 1 }); var sqlFalseQuery = new Mock <ISQLQuery>(); sqlFalseQuery.Setup(i => i.List <Dictionary <string, object> >()) .Returns(new List <Dictionary <string, object> >()); sqlFalseQuery.Setup(i => i.SetResultTransformer(It.IsAny <IResultTransformer>())) .Returns(sqlFalseQuery.Object); s.Setup(i => i.CreateSQLQuery("select 1 from dual where 1 = 1")).Returns(sqlTrueQuery.Object); s.Setup(i => i.CreateSQLQuery("select 1 from dual where 1 = 0")).Returns(sqlFalseQuery.Object); }); action.ShouldThrow <JobExecutionException>( string.Format("Job '{0}' shouldn't be executed. Split query return 0 rows.", epsJob.JobCode)); }
/// <summary> /// Создание задания EPS. /// </summary> public static EpsOutput ProcessEpsJob(string executor, EpsJob job, ISession session, Dictionary <string, object> additionalParameters, ILog log) { // получаем параметры самого задания List <WmsReport> reports; var parameters = ProcessEpsConfigParams(job, additionalParameters, session, log, out reports); // получаем задачи var outputTasks = ProcessTaskParams(job, session, reports, log); //Формируем задание EPS var output = CreateEpsOutput(executor, job, outputTasks, reports, parameters, additionalParameters, log); return(output); }
private static void ProcessOutput(EpsJob epsJob, string executor, DataRow row) { try { var output = new Output { Login_R = executor, Host_R = WMSEnvironment.Instance.ClientCode, OutputStatus = OutputStatus.OS_NEW.ToString(), EpsHandler = epsJob.JobHandler }; FillOutputParams(epsJob, executor, output, row); using (var mgr = IoC.Instance.Resolve <IBaseManager <Output> >()) mgr.Insert(ref output); _log.InfoFormat("Create new Output '{0}' from Executor '{1}'.", output.GetKey(), executor); } catch (Exception ex) { _log.Error(string.Format("Can't create from Executor '{0}'. {1}", executor, ExceptionHelper.ExceptionToString(ex)), ex); } }
private static void FillOutputParams(EpsJob epsJob, string executor, Output output, DataRow row) { var epsJobId = epsJob.GetKey(); //Параметры EPS var lstReports = new List <Report>(); if (epsJob.ConfigEps == null) { _log.DebugFormat("EpsJob.ConfigEps is null in EpsJob '{0}' of Executor '{1}'.", epsJobId, executor); } else { if (output.EpsParams == null) { output.EpsParams = new WMSBusinessCollection <OutputParam>(); } if (output.ReportParams == null) { output.ReportParams = new WMSBusinessCollection <OutputParam>(); } var configs = epsJob.ConfigEps.Where(p => p != null && !string.IsNullOrEmpty(p.EpsConfigParamCode) && !p.EpsConfigLocked); foreach (var configEps in configs) { var configEpsId = configEps.GetKey(); switch (Extensions.To(configEps.EpsConfigParamCode, EpsTaskParams.None)) { //case EpsTaskParams.None: // _log.DebugFormat("Can't convert EpsConfigParamCode '{0}' to enum: EpsTaskParams in ConfigEps '{1}' of EpsJob '{2}' of Executor '{3}'.", // configEps.EpsConfigParamCode, configEpsId, epsJobId, executor); // continue; //Параметры отчета case EpsTaskParams.EpsReport: if (!string.IsNullOrEmpty(configEps.EpsConfigValue)) { // получаем отчет Report report; // TODO: сделать поддержку маски для вложенных коллекций // формируем шаблон получения отчета // var attrEntity = FilterHelper.GetAttrEntity<Report>( // Report.ReportCodePropertyName // , Report.ReportFile_RPropertyName // , Report.ReportLockedPropertyName // , Report.ConfigRepPropertyName // , Report.ReportCopiesPropertyName // ); // // var configAttrEntity = FilterHelper.GetAttrEntity<ReportCfg>( // ReportCfg.EpsConfigParamCodePropertyName, // ReportCfg.EpsConfigValuePropertyName // // ); // // var cfgAttr = TypeDescriptor.GetProperties(typeof(Report)) // .OfType<DynamicPropertyDescriptor>() // .Single(p => p.Name == Report.ConfigRepPropertyName) // .SourceName; // var replaceWith = string.Format("<{0}>{1}</{0}>", cfgAttr, configAttrEntity); // // attrEntity = attrEntity.Replace(string.Format("<{0} />", cfgAttr), replaceWith); // // // получаем отчет using (var mgr = IoC.Instance.Resolve <IBaseManager <Report> >()) report = mgr.Get(configEps.EpsConfigValue); //, attrEntity); if (report == null) { continue; } if (report.ReportLocked) { _log.WarnFormat("Report '{0}' is locked in ConfigEps '{1}' of EpsJob '{2}' of Executor '{3}'.", configEps.EpsConfigValue, configEpsId, epsJobId, executor); continue; } if (string.IsNullOrEmpty(report.ReportFile_R)) { _log.WarnFormat("Undefined report file name in report '{0}' of ConfigEps '{1}' of EpsJob '{2}' of Executor '{3}'.", configEps.EpsConfigValue, configEpsId, epsJobId, executor); continue; } //получаем файл отчета ReportFile reportFile; using (var mgr = IoC.Instance.Resolve <IBaseManager <ReportFile> >()) reportFile = ((IReportFileManager)mgr).GetByReportFile(report.ReportFile_R); if (reportFile != null) { output.ReportFileSubfolder_R = reportFile.ReportFileSubfolder; } lstReports.Add(report); output.ReportParams.Add(new OutputParam { OutputParamCode = configEps.EpsConfigParamCode, OutputParamValue = report.ReportFile_R, OutputParamType = EpsParamType.REP.ToString() }); if (report.ConfigRep == null) { _log.DebugFormat("Report.ConfigRep is null in report '{0}' of ConfigEps '{1}' of EpsJob '{2}' of Executor '{3}'.", configEps.EpsConfigValue, configEpsId, epsJobId, executor); } else { foreach (var configRep in report.ConfigRep.Where(p => p != null && !p.EpsConfigLocked)) { switch (Extensions.To(configRep.EpsConfigParamCode, EpsTaskParams.None)) { case EpsTaskParams.ResultReportFile: case EpsTaskParams.ChangeODBC: break; case EpsTaskParams.None: //Variable if (string.IsNullOrEmpty(configRep.EpsConfigParamCode)) { continue; } break; default: _log.DebugFormat("Illegal EpsConfigParamCode '{0}'.", configRep.EpsConfigParamCode); break; } var name = configRep.EpsConfigParamCode; if (!string.IsNullOrEmpty(name) && name[0] == '{' && name[name.Length - 1] == '}') { name = name.Substring(1, name.Length - 2); } var val = configRep.EpsConfigValue; // если передали строку, пытаемся из нее взять значение парметра if (row != null) { var col = row.Table.Columns.Cast <DataColumn>().FirstOrDefault(i => Extensions.EqIgnoreCase(i.ColumnName, name)); if (col != null) { val = row[(DataColumn)col] == null ? null : row[(DataColumn)col].ToString(); } } output.ReportParams.Add(new OutputParam { OutputParamCode = name, OutputParamValue = val, OutputParamSubvalue = report.ReportFile_R, OutputParamType = EpsParamType.REP.ToString() }); } } } break; default: output.EpsParams.Add(new OutputParam { OutputParamCode = configEps.EpsConfigParamCode, OutputParamValue = configEps.EpsConfigValue, OutputParamType = EpsParamType.EPS.ToString() }); break; } } if (!output.EpsParams.Any()) { output.EpsParams = null; } if (!output.ReportParams.Any()) { output.ReportParams = null; } } //Задачи if (epsJob.Job2Task == null) { _log.DebugFormat("EpsJob.Job2Tas is null in EpsJob '{0}' of Executor '{1}'.", epsJobId, executor); } else { if (output.OutputTasks == null) { output.OutputTasks = new WMSBusinessCollection <OutputTask>(); } using (var epsTaskManager = IoC.Instance.Resolve <IBaseManager <EpsTask> >()) using (var printerLogicalManager = IoC.Instance.Resolve <IBaseManager <PrinterLogical> >()) using (var printerPhysicalManager = IoC.Instance.Resolve <IBaseManager <PrinterPhysical> >()) foreach (var job2Task in epsJob.Job2Task.Where(p => p != null && !string.IsNullOrEmpty(p.EpsTask2JobTaskCode))) { PrinterLogical printerLogical = null; var epsTask = epsTaskManager.Get(job2Task.EpsTask2JobTaskCode); if (epsTask == null) { _log.DebugFormat("Can't get EpsTask by key '{0}'.", job2Task.EpsTask2JobTaskCode); continue; } if (epsTask.TaskLocked) { _log.DebugFormat("Task '{0}' is locked.", epsTask.GetKey()); continue; } EpsTaskType taskType; try { taskType = ConvertToEpsTaskType(epsTask.TaskType); } catch (Exception ex) { _log.Error(ex.Message, ex); continue; } if (taskType == EpsTaskType.None) { _log.Debug("Undefined EPS Task type."); continue; } var outputTasks = new OutputTask { OutputTaskCode = taskType.ToString(), OutputTaskOrder = job2Task.Task2JobOrder, TaskParams = new WMSBusinessCollection <OutputParam>() }; if (epsTask.ConfigTsk != null) { foreach (var configTsk in epsTask.ConfigTsk.Where(p => p != null && !string.IsNullOrEmpty(p.EpsConfigParamCode) && !p.EpsConfigLocked)) { var epsConfigParamCode = configTsk.EpsConfigParamCode; var paramCod = Extensions.To(epsConfigParamCode, EpsTaskParams.None); var epsConfigValue = configTsk.EpsConfigValue; switch (paramCod) { case EpsTaskParams.PhysicalPrinter: continue; case EpsTaskParams.None: if (Extensions.EqIgnoreCase(epsConfigParamCode, EpsLogicalPrinter, true)) { //Задан логический принтер if (!string.IsNullOrEmpty(epsConfigValue)) { printerLogical = printerLogicalManager.Get(epsConfigValue); if (printerLogical == null) { _log.DebugFormat("Can't get PrinterLogical by key '{0}'.", configTsk.EpsConfigValue); continue; } //Проверяем физический принтер var printerPhysical = printerPhysicalManager.Get(printerLogical.PhysicalPrinter_R); if (printerPhysical == null) { var message = string.Format("Can't get PrinterPhysical by key '{0}'.", printerLogical.PhysicalPrinter_R); _log.Debug(message); continue; } if (printerPhysical.PhysicalPrinterLocked) { _log.DebugFormat("Physical printer '{0}' is locked.", printerPhysical.GetKey()); continue; } epsConfigParamCode = EpsTaskParams.PhysicalPrinter.ToString(); epsConfigValue = printerLogical.PhysicalPrinter_R; } } else { _log.DebugFormat("Can't convert EpsConfigParamCode '{0}' to enum: EpsTaskParams.", configTsk.EpsConfigParamCode); continue; } break; } outputTasks.TaskParams.Add(new OutputParam { OutputParamCode = epsConfigParamCode, OutputParamValue = epsConfigValue, OutputParamType = EpsParamType.TSK.ToString() }); } //Проверяем наличие физ. принтера if (taskType == EpsTaskType.OTC_PRINT) { if (!outputTasks.TaskParams.Any(p => p != null && Extensions.To(p.OutputParamCode, EpsTaskParams.None) == EpsTaskParams.PhysicalPrinter)) { _log.DebugFormat("PhysicalPrinter parameter is not present for task '{0}'.", job2Task.GetKey()); } //Добавляем copies для задачи Print if (lstReports != null) { var copies = outputTasks.TaskParams.Where(p => p != null && Extensions.To(p.OutputParamCode, EpsTaskParams.None) == EpsTaskParams.Copies).ToArray(); if (copies.Any()) //Удаляем { foreach (var p in copies) { outputTasks.TaskParams.Remove(p); } //Определяем новые copies с учетом отчета и принтера var copy = copies.Select(p => Extensions.To(p.OutputParamValue, 0)).First(); foreach (var report in lstReports.Where(p => p != null && !string.IsNullOrEmpty(p.ReportFile_R))) { outputTasks.TaskParams.Add(new OutputParam { OutputParamCode = EpsTaskParams.Copies.ToString(), OutputParamValue = (report.ReportCopies * copy * (printerLogical == null ? 0 : printerLogical.LogicalPrinterCopies)).ToString(CultureInfo.InvariantCulture), OutputParamSubvalue = report.ReportFile_R, OutputParamType = EpsParamType.TSK.ToString() }); } } } } } if (outputTasks.TaskParams.Count == 0) { outputTasks.TaskParams = null; } output.OutputTasks.Add(outputTasks); } if (output.OutputTasks.Count == 0) { output.OutputTasks = null; } } }
/// <summary> /// Дополнение задачи параметрами. /// </summary> public static IList <Dictionary <string, object> > GetAddigionalParametersAndSplit(EpsJob job, ISession session) { if (job.CPV_List == null || !job.CPV_List.Any()) { return(null); } // получаем CPV var checkCpv = job.CPV_List.FirstOrDefault(i => i.CustomParam.CustomParamCode == CpvSplitSql); if (checkCpv == null) { return(null); } // достаем sql var sql = checkCpv.CPVValue; if (string.IsNullOrEmpty(sql)) { throw new Exception( string.Format("In job '{0}' cpv '{1}' is empty. Please enter value or remove it.", job.JobCode, checkCpv.CPVValue)); } // запускаем sql получения параметров и разделения return(session .CreateSQLQuery(sql) .SetResultTransformer(new DictionaryResultTransformer()) .List <Dictionary <string, object> >()); }
private static IEnumerable <EpsOutputTask> ProcessTaskParams(EpsJob job, ISession session, List <WmsReport> reports, ILog log) { var res = new List <EpsOutputTask>(); if (job.Job_EpsTask2Job_List.Count == 0) { return(res); } var uselog = log != null; foreach (var task2Job in job.Job_EpsTask2Job_List) { var task = task2Job.Task; if (task.TaskLocked) { if (uselog) { log.DebugFormat("Task '{0}' is locked.", task.TaskCode); } continue; } if (task.TaskType == EpsTaskTypes.None) { if (uselog) { log.Debug("Undefined EPS Task type."); } continue; } var outputTask = new EpsOutputTask { OutputTaskCode = (EpsOutputTaskCodes)Enum.Parse(typeof(EpsOutputTaskCodes), "OTC_" + task.TaskType), OutputTaskOrder = task2Job.Task2JobOrder }; // разбираем параметры if (task.CFG_List.Count > 0) { EpsPrinterLogical printerLogical = null; foreach (var configTsk in task.CFG_List) { if (configTsk.EpsConfigLocked) { if (uselog) { log.DebugFormat("Task {0}. Parameter '{1}' (id={2}) is locked.", task.TaskCode, configTsk.EpsConfigParamCode, configTsk.EpsConfigID); } continue; } if (string.IsNullOrEmpty(configTsk.EpsConfigParamCode)) { throw new Exception(string.Format("Param code in task {0} (id={1}) is empty.", configTsk.EpsConfigParamCode, configTsk.EpsConfigID)); } EpsTaskParams param; if (!Enum.TryParse(configTsk.EpsConfigParamCode, out param)) { param = EpsTaskParams.None; } var epsConfigParamCode = configTsk.EpsConfigParamCode; var epsConfigValue = configTsk.EpsConfigValue; switch (param) { case EpsTaskParams.PhysicalPrinter: continue; case EpsTaskParams.None: // из таких мы знаем только EpsLogicalPrinter if ( !string.Equals(configTsk.EpsConfigParamCode, EpsLogicalPrinter, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception(string.Format("Unknown EpsConfigParamCode '{0}'.", configTsk.EpsConfigParamCode)); } //Задан логический принтер if (!string.IsNullOrEmpty(configTsk.EpsConfigValue)) { printerLogical = session.Get <EpsPrinterLogical>(configTsk.EpsConfigValue); if (printerLogical == null) { throw new Exception( string.Format("Can't get PrinterLogical by key '{0}'.", configTsk.EpsConfigValue)); } //Проверяем физический принтер var printerPhysical = printerLogical.PhysicalPrinter_r; if (printerPhysical == null) { throw new Exception( string.Format("Can't get PrinterPhysical by logical '{0}'.", printerLogical.LogicalPrinter)); } if (printerPhysical.PhysicalPrinterLocked) { throw new Exception( string.Format("Physical printer '{0}' is locked.", printerPhysical.PhysicalPrinter)); } epsConfigParamCode = EpsTaskParams.PhysicalPrinter.ToString(); epsConfigValue = printerLogical.PhysicalPrinter_r.PhysicalPrinter; } break; } outputTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam { OutputTask = outputTask, OutputParamCode = epsConfigParamCode, OutputParamValue = epsConfigValue, OutputParamType = EpsParamTypes.TSK }); } //Проверяем наличие физ. принтера if (task.TaskType == EpsTaskTypes.PRINT) { if ( outputTask.OutputTask_EpsOutputParam_List.All( p => EnumHelper.ParseEnum(p.OutputParamCode, EpsTaskParams.None) != EpsTaskParams.PhysicalPrinter)) { throw new Exception(string.Format( "PhysicalPrinter parameter is not present for task '{0}'.", task.TaskCode)); } //Добавляем copies для задачи Print if (reports != null) { var copies = outputTask.OutputTask_EpsOutputParam_List.Where( p => EnumHelper.ParseEnum(p.OutputParamCode, EpsTaskParams.None) == EpsTaskParams.Copies).ToArray(); if (copies.Length > 0) //Удаляем { foreach (var p in copies) { session.Delete(p); outputTask.OutputTask_EpsOutputParam_List.Remove(p); } //Определяем новые copies с учетом отчета и принтера //TODO: почему тут мы берем первую попапвшуюся запись? int copy; int.TryParse(copies[0].OutputParamValue, out copy); foreach (var report in reports.Where(p => p.ReportFile_r != null)) { outputTask.OutputTask_EpsOutputParam_List.Add(new EpsOutputParam { OutputTask = outputTask, OutputParamCode = EpsTaskParams.Copies.ToString(), OutputParamValue = (report.ReportCopies * copy * (printerLogical == null ? 0 : printerLogical.LogicalPrinterCopies)) .ToString(CultureInfo.InvariantCulture), OutputParamSubValue = report.ReportFile_r.ReportFile, OutputParamType = EpsParamTypes.TSK }); } } } } } res.Add(outputTask); } return(res); }
public void Execute_without_split_and_check_cpv() { #region prepare data // report var report = new WmsReport { EpsHandler = 100, Report = "AutoTestReport", ReportCopies = 2, ReportFile_r = new WmsReportFile { ReportFile = "AutoTestReportFile.frx", ReportFileName = "AutoTestReportFile", ReportFileSubFolder = "AutoTests" } }; var reportConstParam = new WmsReportCFG { REPORT = report, EpsConfigParamCode = "{AutoTestParam}", EpsConfigValue = "ConstantValue" }; report.CFG_List = new HashSet <WmsReportCFG> { reportConstParam }; // job var epsJob = new EpsJob { JobCode = "AutoTestJob", JobHandler = 100, JobLocked = false, }; var epsConfigReport = new EpsJobCFG { JOB = epsJob, EpsConfigParamCode = "EpsReport", EpsConfigValue = report.Report }; epsJob.CFG_List = new HashSet <EpsJobCFG> { epsConfigReport }; //task var epsTask = new EpsTask { TaskCode = "AutoTestTask", TaskLocked = false, TaskType = EpsTaskTypes.MAIL, //TaskType = "MAIL", }; var emailTaskParam = new EpsTaskCFG { TASK = epsTask, EpsConfigParamCode = "Email", EpsConfigValue = "*****@*****.**" }; var fileFormatTaskParam = new EpsTaskCFG { TASK = epsTask, EpsConfigParamCode = "FileFormat", EpsConfigValue = "wmsMLC.EPS.wmsEPS.ExportTypes.FRPdf" }; epsTask.CFG_List = new HashSet <EpsTaskCFG> { emailTaskParam, fileFormatTaskParam }; //job2task epsJob.Job_EpsTask2Job_List = new HashSet <EpsTask2Job> { new EpsTask2Job { Job = epsJob, Task = epsTask, Task2JobOrder = 1 } }; #endregion var results = new List <object>(); var action = GetExecuteAction(epsJob, s => { s.Setup(i => i.Get <WmsReport>(report.Report)).Returns(report); s.Setup(i => i.Save(It.IsAny <object>())).Callback(new Action <object>(o => results.Add(o))); }); action(); var outputs = results.OfType <EpsOutput>().ToArray(); outputs.Should().HaveCount(1); var output = outputs[0]; output.Login_r.Should().Be(WmsEnvironment.UserName); output.Host_r.Should().Be(Environment.MachineName); output.OutputStatus.Should().Be(OutputStatuses.OS_NEW); //output.OutputStatus.Should().Be("OS_NEW"); output.EpsHandler.Should().Be(epsJob.JobHandler); output.Output_EpsOutputParam_List.Should().HaveCount(2); var outputReportParam = output.Output_EpsOutputParam_List.First(i => i.OutputParamCode == epsConfigReport.EpsConfigParamCode); outputReportParam.Output.Should().Be(output); outputReportParam.OutputTask.Should().BeNull(); outputReportParam.OutputParamType.Should().Be(EpsParamTypes.REP); outputReportParam.OutputParamValue.Should().Be(report.ReportFile_r.ReportFile); var trueReportConstParamName = reportConstParam.EpsConfigParamCode.Replace("{", "").Replace("}", ""); var constReportParam = output.Output_EpsOutputParam_List.First(i => i.OutputParamCode == trueReportConstParamName); constReportParam.Output.Should().Be(output); constReportParam.OutputTask.Should().BeNull(); constReportParam.OutputParamType.Should().Be(EpsParamTypes.REP); constReportParam.OutputParamValue.Should().Be(reportConstParam.EpsConfigValue); // check task output.Output_EpsOutputTask_List.Should().HaveCount(1); var outputTask = output.Output_EpsOutputTask_List.First(); outputTask.Output.Should().Be(output); //outputTask.OutputTaskCode.Should().Be("OTC_MAIL"); outputTask.OutputTaskCode.Should().Be(EpsOutputTaskCodes.OTC_MAIL); outputTask.OutputTaskOrder.Should().Be(1); outputTask.OutputTaskStatus.Should().Be(OutputStatuses.OS_NEW); //outputTask.OutputTaskStatus.Should().Be("OS_NEW"); outputTask.OutputTask_EpsOutputParam_List.Should().HaveCount(2); var outputTaskEmailParam = outputTask.OutputTask_EpsOutputParam_List.First(i => i.OutputParamCode == emailTaskParam.EpsConfigParamCode); outputTaskEmailParam.Output.Should().Be(output); outputTaskEmailParam.OutputTask.Should().Be(outputTask); outputTaskEmailParam.OutputParamType.Should().Be(EpsParamTypes.TSK); outputTaskEmailParam.OutputParamValue.Should().Be(emailTaskParam.EpsConfigValue); var outputTaskFileFormatParam = outputTask.OutputTask_EpsOutputParam_List.First(i => i.OutputParamCode == fileFormatTaskParam.EpsConfigParamCode); outputTaskFileFormatParam.Output.Should().Be(output); outputTaskFileFormatParam.OutputTask.Should().Be(outputTask); outputTaskFileFormatParam.OutputParamType.Should().Be(EpsParamTypes.TSK); outputTaskFileFormatParam.OutputParamValue.Should().Be(fileFormatTaskParam.EpsConfigValue); }
/// <summary> /// Параметры задания. /// </summary> private static IEnumerable <EpsOutputParam> ProcessEpsConfigParams(EpsJob job, Dictionary <string, object> additionalParameters, ISession session, ILog log, out List <WmsReport> reports) { var res = new List <EpsOutputParam>(); reports = new List <WmsReport>(); var uselog = log != null; if (job.CFG_List.Count == 0) { return(res); } foreach (var jobConfig in job.CFG_List) { if (jobConfig.EpsConfigLocked) { if (uselog) { log.DebugFormat("Job '{0}'. Parameter '{1}' (id={2}) is locked.", job.JobCode, jobConfig.EpsConfigParamCode, jobConfig.EpsConfigID); } continue; } if (string.IsNullOrEmpty(jobConfig.EpsConfigParamCode)) { throw new Exception( string.Format("Job '{0}'. Рarameter '{1}' (id={2}) has empty ParamCode. Please check settings.", job.JobCode, jobConfig.EpsConfigParamCode, jobConfig.EpsConfigID)); } switch (EnumHelper.ParseEnum(jobConfig.EpsConfigParamCode, EpsTaskParams.None)) { case EpsTaskParams.EpsReport: var reportCode = jobConfig.EpsConfigValue; if (string.IsNullOrEmpty(reportCode)) { throw new Exception( string.Format( "Job '{0}' has parameter '{1}' (id={2}; type={3}) with empty value. Please check settings.", job.JobCode, jobConfig.EpsConfigParamCode, jobConfig.EpsConfigID, jobConfig.EpsConfigParamCode)); } // получаем отчет var report = session.Get <WmsReport>(reportCode); if (report == null) { throw new Exception(string.Format("Can't find report with code '{0}'.", reportCode)); } if (report.ReportLocked) { throw new Exception(string.Format("Report '{0}' is Locked.", reportCode)); } if (report.ReportFile_r == null) { throw new Exception(string.Format("Report '{0}' has empty ReportFile link.", reportCode)); } reports.Add(report); // добавляем отчет res.Add(new EpsOutputParam { OutputParamCode = jobConfig.EpsConfigParamCode, OutputParamValue = report.ReportFile_r.ReportFile, OutputParamType = EpsParamTypes.REP }); if (report.CFG_List.Count > 0) { foreach (var reportConfig in report.CFG_List) { if (reportConfig.EpsConfigLocked) { if (uselog) { log.DebugFormat("Report {0}. Parameter '{1}' (id={2}) is locked.", reportCode, reportConfig.EpsConfigParamCode, reportConfig.EpsConfigID); } continue; } switch (EnumHelper.ParseEnum(reportConfig.EpsConfigParamCode, EpsTaskParams.None)) { case EpsTaskParams.ResultReportFile: case EpsTaskParams.ChangeODBC: break; case EpsTaskParams.None: //Variable if (string.IsNullOrEmpty(reportConfig.EpsConfigParamCode)) { continue; } break; default: throw new Exception( string.Format("Report param '{0}' is not supported.", reportConfig.EpsConfigParamCode)); } var name = reportConfig.EpsConfigParamCode; if (!string.IsNullOrEmpty(name) && name[0] == '{' && name[name.Length - 1] == '}') { name = name.Substring(1, name.Length - 2); } var val = reportConfig.EpsConfigValue; // если передали строку, пытаемся из нее взять значение парметра if (additionalParameters != null) { var key = additionalParameters.Keys.SingleOrDefault( i => string.Equals(i, name, StringComparison.InvariantCultureIgnoreCase)); if (!string.IsNullOrEmpty(key)) { val = additionalParameters[key] == null ? null : additionalParameters[key].ToString(); } } res.Add(new EpsOutputParam { OutputParamCode = name, OutputParamValue = val, OutputParamSubValue = report.ReportFile_r.ReportFile, OutputParamType = EpsParamTypes.REP }); } } break; default: res.Add(new EpsOutputParam { OutputParamCode = jobConfig.EpsConfigParamCode, OutputParamValue = jobConfig.EpsConfigValue, OutputParamType = EpsParamTypes.EPS }); break; } } return(res); }
/// <summary> /// Создание задачи. /// </summary> public static EpsOutput CreateEpsOutput(string executor, EpsJob job, IEnumerable <EpsOutputTask> outputTasks, IEnumerable <WmsReport> reports, IEnumerable <EpsOutputParam> parameters, Dictionary <string, object> additionalParameters, ILog log) { var output = new EpsOutput { Login_r = executor, Host_r = Environment.MachineName, OutputStatus = OutputStatuses.OS_NEW, EpsHandler = job.JobHandler ?? 20160614 }; if (parameters != null) { foreach (var p in parameters) { p.Output = output; output.Output_EpsOutputParam_List.Add(p); } } //TODO: тут нужно переделывать. если в задании 2 отчета из разных subfolder-ов, то в output попадет subfolder последнего if (reports != null && reports.Any()) { var subFolders = reports.Where(i => i.ReportFile_r != null) .Select(i => i.ReportFile_r.ReportFileSubFolder) .Distinct() .ToArray(); if (subFolders.Length > 1) { throw new Exception( string.Format("Job '{0}' has more than one reports from different sub folders '{1}'.", job.JobCode, string.Join("','", subFolders))); } output.ReportFileSubFolder_r = subFolders[0]; } // задачи if (outputTasks != null) { foreach (var outputTask in outputTasks) { outputTask.Output = output; output.Output_EpsOutputTask_List.Add(outputTask); if (outputTask.OutputTask_EpsOutputParam_List == null) { continue; } foreach (var t in outputTask.OutputTask_EpsOutputParam_List) { t.Output = output; } } } if (log != null) { log.InfoFormat("Create new EpsOutput '{0}' from Executor '{1}'.", output.OutputID, executor); } return(output); }
private static bool CheckJob(EpsJob epsJob, out DataTable table) { table = null; // если заблокировано - не запускаем if (epsJob.JobLocked) { _log.InfoFormat("Job '{0}' is locked", epsJob.GetKey()); return(false); } // cpv нет - выходим if (epsJob.CustomParamVal == null || epsJob.CustomParamVal.Count == 0) { return(true); } // проверяем наличие CPV проверки var root = epsJob.CustomParamVal.FirstOrDefault(i => CpvCheckRoot.Equals(i.CustomParamCode)); if (root == null) { return(true); } _log.DebugFormat("Checking by cpv"); // получаем основной sql var cpvSql = epsJob.CustomParamVal.FirstOrDefault(i => CpvSplitSQL.Equals(i.CustomParamCode)); if (cpvSql == null || string.IsNullOrEmpty(cpvSql.CPVValue)) { throw new OperationException("Can't find cpv with code '{0}' in cpv", CpvSplitSQL); } // проверяем нет ли быстрой проверки var cpvPreSql = epsJob.CustomParamVal.FirstOrDefault(i => CpvCheckSQL.Equals(i.CustomParamCode)); if (cpvPreSql != null && !string.IsNullOrEmpty(cpvPreSql.CPVValue)) { DataTable preResult; using (var mgr = IoC.Instance.Resolve <IBPProcessManager>()) preResult = mgr.ExecuteDataTable(cpvPreSql.CPVValue); // если ничего не вернулось - проверка не прошла if (preResult == null || preResult.Rows.Count == 0) { _log.Info("Prefilter return 0 rows. Don't run main filter. Exit correctly"); return(false); } } // запускаем основной SQL using (var mgr = IoC.Instance.Resolve <IBPProcessManager>()) table = mgr.ExecuteDataTable(cpvSql.CPVValue); // если ничего не вернулось, то данных нет, корректно выходим if (table == null || table.Rows.Count == 0) { _log.DebugFormat("Filter return 0 rows. Exit correctly"); return(false); } return(true); }
public void Execute_without_check_cpv_and_with_split_cvp_that_returns_2_enrich_param() { #region prepare data // report var report = new WmsReport { EpsHandler = 100, Report = "AutoTestReport", ReportCopies = 2, ReportFile_r = new WmsReportFile { ReportFile = "AutoTestReportFile.frx", ReportFileName = "AutoTestReportFile", ReportFileSubFolder = "AutoTests" } }; var reportConstParam = new WmsReportCFG { REPORT = report, EpsConfigParamCode = "{AutoTestParam}", EpsConfigValue = "ConstantValue" }; report.CFG_List = new HashSet <WmsReportCFG> { reportConstParam }; // job var epsJob = new EpsJob { JobCode = "AutoTestJob", JobHandler = 100, JobLocked = false, CPV_List = new HashSet <EpsJobCPV> { new EpsJobCPV { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvCheckRoot } }, new EpsJobCPV { CustomParam = new WmsCustomParam { CustomParamCode = EpsHelper.CpvSplitSql }, CPVValue = "select 'val1' as AutoTestParam from dual where 1 = 1 union all select 'val2' from dual where 1 = 1" } } }; var epsConfigReport = new EpsJobCFG { JOB = epsJob, EpsConfigParamCode = "EpsReport", EpsConfigValue = report.Report }; epsJob.CFG_List = new HashSet <EpsJobCFG> { epsConfigReport }; //task var epsTask = new EpsTask { TaskCode = "AutoTestTask", TaskLocked = false, TaskType = EpsTaskTypes.MAIL, //TaskType = "MAIL", }; var emailTaskParam = new EpsTaskCFG { TASK = epsTask, EpsConfigParamCode = "Email", EpsConfigValue = "*****@*****.**" }; var fileFormatTaskParam = new EpsTaskCFG { TASK = epsTask, EpsConfigParamCode = "FileFormat", EpsConfigValue = "wmsMLC.EPS.wmsEPS.ExportTypes.FRPdf" }; epsTask.CFG_List = new HashSet <EpsTaskCFG> { emailTaskParam, fileFormatTaskParam }; //job2task epsJob.Job_EpsTask2Job_List = new HashSet <EpsTask2Job> { new EpsTask2Job { Job = epsJob, Task = epsTask, Task2JobOrder = 1 } }; #endregion var results = new List <object>(); var action = GetExecuteAction(epsJob, s => { s.Setup(i => i.Get <WmsReport>(report.Report)).Returns(report); s.Setup(i => i.Save(It.IsAny <object>())).Callback(new Action <object>(o => results.Add(o))); var sqlSplitQuery = new Mock <ISQLQuery>(); sqlSplitQuery.Setup(i => i.List <Dictionary <string, object> >()) .Returns(new List <Dictionary <string, object> > { new Dictionary <string, object> { { "AutoTestParam", "val1" } }, new Dictionary <string, object> { { "AutoTestParam", "val2" } } }); sqlSplitQuery.Setup(i => i.SetResultTransformer(It.IsAny <IResultTransformer>())) .Returns(sqlSplitQuery.Object); s.Setup(i => i.CreateSQLQuery("select 'val1' as AutoTestParam from dual where 1 = 1 union all select 'val2' from dual where 1 = 1")).Returns(sqlSplitQuery.Object); }); action(); var trueReportConstParamName = reportConstParam.EpsConfigParamCode.Replace("{", "").Replace("}", ""); var outputs = results.OfType <EpsOutput>().ToArray(); outputs.Should().HaveCount(2); outputs.Should() .Contain(i => i.Output_EpsOutputParam_List.Any(j => j.Output == i && j.OutputTask == null && j.OutputParamType == EpsParamTypes.REP && j.OutputParamCode == trueReportConstParamName && j.OutputParamValue == "val1")); outputs.Should() .Contain(i => i.Output_EpsOutputParam_List.Any(j => j.Output == i && j.OutputTask == null && j.OutputParamType == EpsParamTypes.REP && j.OutputParamCode == trueReportConstParamName && j.OutputParamValue == "val2")); }