commit cecb662375a2a413ccc36fb9f8cb5943b46ca9a7 Author: 小郭\xg <18321862510@139.com> Date: Fri Jul 31 15:42:16 2026 +0800 1 diff --git a/MESEAI/.vs/MESEAI/v16/.suo b/MESEAI/.vs/MESEAI/v16/.suo new file mode 100644 index 0000000..590b7dc Binary files /dev/null and b/MESEAI/.vs/MESEAI/v16/.suo differ diff --git a/MESEAI/EAICws/EAICws/EAIws_C.csproj b/MESEAI/EAICws/EAICws/EAIws_C.csproj new file mode 100644 index 0000000..e1fa295 --- /dev/null +++ b/MESEAI/EAICws/EAICws/EAIws_C.csproj @@ -0,0 +1,186 @@ + + + + + Debug + AnyCPU + {74B7676A-6420-0784-301F-696024D2A8D7} + Library + EAIws_C + EAIws_C + 512 + Windows + v4.6.2 + SAK + SAK + SAK + SAK + + $(DefaultItemExcludes);$(ProjectDir)**\*.vb + + + true + full + true + true + ..\..\..\MES_S_DLL\ + ..\..\..\MES_S_DLL\EAIws_C.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + false + + + pdbonly + false + true + true + bin\Release\ + bin\Release\EAIws_C.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + false + + + On + + + Binary + + + Off + + + On + + + + False + ..\..\..\MES_S_DLL\Apache.NMS.dll + False + + + False + ..\..\..\MES_S_DLL\Apache.NMS.ActiveMQ.dll + False + + + ..\..\..\..\..\..\项目环境\SHLQ_C20260316\DefaultSite\MESws_API\bin\API_Base.dll + + + False + ..\..\..\MES_S_DLL\BouncyCastle.Crypto.dll + + + False + ..\..\..\MES_S_DLL\EAIws.dll + + + False + ..\..\..\MES_S_DLL\EAIws_C.dll + + + False + ..\..\..\MES_S_DLL\iMESAppSetting.dll + False + + + False + ..\..\..\MES_S_DLL\iMESCIOC.dll + + + False + ..\..\..\MES_S_DLL\iMESConst.dll + False + + + False + ..\..\..\..\..\环境\MESws_EAI\bin\kcMTL.dll + + + False + ..\..\..\..\..\环境\MESws_EAI\bin\kcOE.dll + + + False + ..\..\..\..\..\环境\MESws_EAI\bin\kcPRD.dll + + + + False + ..\..\..\MES_S_DLL\iMESCIO.dll + False + + + False + ..\..\..\MES_S_DLL\iMESException.dll + + + False + ..\..\..\MES_S_DLL\Newtonsoft.Json.dll + False + + + + + + + + + + + + + False + ..\..\..\MES_S_DLL\tcEAI.dll + + + False + ..\..\..\MES_S_DLL\tcEAI_C.dll + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + Settings.settings + True + + + + + MyApplicationCodeGenerator + Application.Designer.cs + + + SettingsSingleFileGenerator + EAIws_C.My + Settings.Designer.cs + + + + + + \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/EAIws_C.csproj.user b/MESEAI/EAICws/EAICws/EAIws_C.csproj.user new file mode 100644 index 0000000..23e78fe --- /dev/null +++ b/MESEAI/EAICws/EAICws/EAIws_C.csproj.user @@ -0,0 +1,6 @@ + + + + D:\iMES\LQ\环境\DefaultSite\MESws_API\bin\ + + \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/My Project/Application.Designer.cs b/MESEAI/EAICws/EAICws/My Project/Application.Designer.cs new file mode 100644 index 0000000..299bbe3 --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/Application.Designer.cs @@ -0,0 +1,11 @@ +// ------------------------------------------------------------------------------ +// +// 這段程式碼是由工具產生的。 +// 執行階段版本:4.0.30319.42000 +// +// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, +// 變更將會遺失。 +// +// ------------------------------------------------------------------------------ + + diff --git a/MESEAI/EAICws/EAICws/My Project/Application.myapp b/MESEAI/EAICws/EAICws/My Project/Application.myapp new file mode 100644 index 0000000..758895d --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 1 + true + diff --git a/MESEAI/EAICws/EAICws/My Project/AssemblyInfo.cs b/MESEAI/EAICws/EAICws/My Project/AssemblyInfo.cs new file mode 100644 index 0000000..eca4b74 --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +// 組件的一般資訊是由下列的屬性集控制。 +// 變更這些屬性的值即可修改組件的相關 +// 資訊。 + +// 檢閱組件屬性的值 + +[assembly: AssemblyTitle("EAIws_C")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("EAICws")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] + +[assembly: ComVisible(false)] + +// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID +[assembly: Guid("968ccd3c-116a-41ae-97a1-bd5dafb45d36")] + +// 組件的版本資訊由下列四個值所組成: +// +// 主要版本 +// 次要版本 +// 組建編號 +// 修訂編號 +// +// 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號 +// 指定為預設值: +// + +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MESEAI/EAICws/EAICws/My Project/Resources.resx b/MESEAI/EAICws/EAICws/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/My Project/Settings.Designer.cs b/MESEAI/EAICws/EAICws/My Project/Settings.Designer.cs new file mode 100644 index 0000000..e8b6167 --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/Settings.Designer.cs @@ -0,0 +1,88 @@ +// ------------------------------------------------------------------------------ +// +// 這段程式碼是由工具產生的。 +// 執行階段版本:4.0.30319.42000 +// +// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, +// 變更將會遺失。 +// +// ------------------------------------------------------------------------------ + +using System.Diagnostics; +using Microsoft.VisualBasic; + + +namespace EAIws_C.My +{ + + [System.Runtime.CompilerServices.CompilerGenerated()] + [System.CodeDom.Compiler.GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + internal sealed partial class MySettings : System.Configuration.ApplicationSettingsBase + { + + private static MySettings defaultInstance = (MySettings)Synchronized(new MySettings()); + + #region My.Settings 自動儲存功能 + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + #endregion + + public static MySettings Default + { + get + { + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + return defaultInstance; + } + } + } +} + +namespace EAIws_C.My +{ + + [HideModuleName()] + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + internal static class MySettingsProperty + { + + [System.ComponentModel.Design.HelpKeyword("My.Settings")] + internal static MySettings Settings + { + get + { + return MySettings.Default; + } + } + } +} \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/My Project/Settings.settings b/MESEAI/EAICws/EAICws/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/MESEAI/EAICws/EAICws/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MESEAI/EAICws/EAICws/modEAP.cs b/MESEAI/EAICws/EAICws/modEAP.cs new file mode 100644 index 0000000..e78bae7 --- /dev/null +++ b/MESEAI/EAICws/EAICws/modEAP.cs @@ -0,0 +1,1221 @@ +using System; +using System.Collections.Generic; +using System.Collections; +using System.Xml; +using iMESCIOC.Request.WMS_Request; +using iMESCIOC.Response.WMS_Response; +using Microsoft.VisualBasic; +using Newtonsoft.Json; +using tcEAI_C; +using iMESCIOC.Request.EAP; +using Microsoft.VisualBasic.ApplicationServices; +using EAIws; +using System.Data; +using Newtonsoft.Json.Linq; +using iMESCIOC.Response.EAP; +using Microsoft.VisualBasic.CompilerServices; +using API_Base; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using iMESCIOC.Request.WMS_Request; +using iMESCIOC.Response.WMS_Response; +using iMESCIOC.Request.EAP; +using iMESCIOC.Response.EAP; + +namespace EAIws_C +{ + + static class modEAP + { + + private static XmlDocument xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + private static DateTime ArriveTime; // 送達時間 + private static string strIdentity; // Identity XML字串 + private static string strReturnValue; // ReturnValue XML字串 + private static string strException; // Exception XML字串 + private static string strResult; // Result XML字串 + private static string strMessage; // Message XML字串 + private static object strServiceName = "modEAP"; + private static int i = 0; + + + + #region "测试工序进出站" + private static string funCheckJson(object parameters) + { + string result = ""; + string transactionid = ""; + string moduleid = ""; + string functionid = ""; + string computername = ""; + string curuserno = "DS"; + string curusrpwd = "";//新增用户密码 SM2加密 + string sendtime = ""; + string languagemode = ""; + string outXml = ""; + string Json = ""; + + string ContentType = ""; + string SourceSystem = ""; + string TargetSystem = ""; + string Authorization = ""; + try + { + //转换为数组 + if (parameters is object[] paramArray && paramArray.Length >= 2) + { + if (paramArray[1] is API_Base.ServiceInfo serviceInfo) + { + Json = serviceInfo.InJson; + string headerText = serviceInfo.httpRequest.ToString(); + + // 解析逻辑 + var lines = headerText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + Dictionary headers = new Dictionary(); + foreach (var line in lines) + { + int index = line.IndexOf(':'); + if (index > 0) + { + string key = line.Substring(0, index).Trim(); + string value = line.Substring(index + 1).Trim(); + headers[key] = value; + } + } + // 结果 + //curuserno = headers.TryGetValue("curuserno", out var no) ? no : ""; + //curusrpwd = headers.TryGetValue("curusrpwd", out var pwd) ? pwd : ""; + + + ContentType = headers.TryGetValue("Content-Type", out var contp) ? contp : ""; + SourceSystem = headers.TryGetValue("Source-System", out var sous) ? sous : ""; + TargetSystem = headers.TryGetValue("Target-System", out var tars) ? tars : ""; + Authorization = headers.TryGetValue("Authorization", out var auth) ? auth : ""; + + curusrpwd = Authorization; + } + } + + tcEAI_C.clsERP.funCheckUser(curuserno, curusrpwd); + + } + catch (Exception ex) + { + throw ex; + } + return Json; + } + public static string funTrackIn_Inquiry_CS(object parameters) + { + string funTrackIn_Inquiry_CS = default(string); + // 0102096: [6.0.5] EAP自動報工架構_SDD210906_05-01/ Execute_CI_LOT + string strReturnValue = "fail"; + string unitid = ""; + string eqp_id = ""; + string socketid = ""; + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + var aryMessage = new List(); + string LanguageMode = "zh-cht"; // 預設繁中 + string strMsg = ""; //返回信息 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResult = ""; //返回结果 + + try + { + //获取进站报文 + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + unitid = result.unitid; + socketid = result.socketid; + eqp_id = result.eqp_id; + if (eqp_id =="") + { + throw new iMESException.MESException("0000-200002", "[%EquipmentNo%] [%NOT FOUND%]"); + } + + var jObj = JObject.Parse(strRequestJson); + Dictionary dicPars = jObj.ToObject>(); + + var dicPars_Tables = default(Dictionary); + + DataTable dt = new DataTable("lotattrib"); + dt.Columns.Add("row_count", typeof(int)); + dt.Columns.Add("attribno", typeof(string)); + dt.Columns.Add("attribvalue", typeof(string)); + + DataRow dr = dt.NewRow(); + dr["row_count"] = 1; + dr["attribno"] = "socketid"; + dr["attribvalue"] = socketid ; + dt.Rows.Add(dr); + + dicPars_Tables = new Dictionary + { + { "lotattrib", dt } + }; + + // 2.執行tcEAI + var obj = new tcEAI_C.clsEAP(); + strReturnValue = obj.Execute_CI_LOT(dicPars, dicPars_Tables, "DS", LanguageMode, ref aryMessage); + strResult = "success"; + } + + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + //组装返回JOSN + TrackIn_Inquiry_CS_Response response = null; + + if (strResult == "success") + { + response = new TrackIn_Inquiry_CS_Response + { + code = "0000", + message = "TrackIn_Inquiry_CS successfully", + time = DateTime .Now + }; + } + else + { + // 失败逻辑 + response = new TrackIn_Inquiry_CS_Response + { + code = "1111", + message = "TrackIn_Inquiry :异常信息:"+ strMsg, + time = DateTime.Now + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + funTrackIn_Inquiry_CS = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "EAP", "funTrackIn_Inquiry_CS", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, "", strMessage, strException, strRequestJson, strResponseJson, "funTrackIn_Inquiry_CS", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + } + + return funTrackIn_Inquiry_CS; + } + + public static string TrackOut_Inquiry_CS(object parameters) + { + string Execute_CO_LOTRet = default(string); + + string strReturnValue = "fail"; + string unitid = ""; + string eqp_id = ""; + string result_c = ""; + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + var aryMessage = new List(); + string LanguageMode = "zh-cht"; // 預設繁中 + string strMsg = ""; //返回信息 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResult = ""; //返回结果 + + try + { + strReturnValue = ""; + + //获取进站报文 + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + unitid = result.unitid; + result_c = result.result; + eqp_id = result.eqp_id; + if (eqp_id == "") + { + throw new iMESException.MESException("0000-200002", "[%EquipmentNo%] [%NOT FOUND%]"); + } + + var jObj = JObject.Parse(strRequestJson); + Dictionary dicPars = jObj.ToObject>(); + + var dicPars_Tables = new Dictionary(); + + // 2.執行tcEAI + var obj = new tcEAI_C.clsEAP(); + strReturnValue = obj.Execute_CO_LOT(dicPars, dicPars_Tables, "DS", LanguageMode, ref aryMessage); + strResult = "success"; + } + + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + //组装返回JOSN + TrackIn_Inquiry_CS_Response response = null; + + if (strResult == "success") + { + response = new TrackIn_Inquiry_CS_Response + { + code = "0000", + message = "TrackOut_Inquiry_CS successfully", + time = DateTime.Now + }; + } + else + { + // 失败逻辑 + response = new TrackIn_Inquiry_CS_Response + { + code = "1111", + message = "TrackOut_Inquiry :异常信息:" + strMsg, + time = DateTime.Now + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + Execute_CO_LOTRet = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "EAP", "funTrackOut_Inquiry_CS", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, "", strMessage, strException, strRequestJson, strResponseJson, "funTrackOut_Inquiry_CS", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + } + + return Execute_CO_LOTRet; + } + #endregion + + + #region EAP 客制接口 + /// + /// 接口断点测试 + /// + /// + /// + public static string funEAPTEST(object parameters) + { + string funEAPTEST = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + + try + { + + + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + + } + return funEAPTEST; + } + + + /// + /// 首站-进站接口 + /// + /// + /// + public static string funTrackIn_Inquiry(object parameters) + { + string funTrackIn_Inquiry = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + bool bolclsEAP = false; + + try + { + //获取进站报文 + strRequestJson = modERP.funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //检查mono和eqp_id是否都传 + + if (result.mono == null || result.eqp_id == null) + { + throw new Exception("[%工单编号和设备编号都必须传入!%]"); + } + + //判空 + if (result.mono == "" || result.eqp_id == "") + { + throw new Exception("[%工单编号或者设备编号不能为空!%]"); + } + + + bolclsEAP = clsEAP.funTrackIn_Inquiry(ref strMessage, ref strException, MONO: result.mono, EQPID: result.eqp_id); + if (bolclsEAP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + var resModel = new EAP_funTrackInOut_Inquiry_Response(); + if (strResult == "success") + { + resModel.Code = 0000; + resModel.Message = "TrackIn_Inquiry successfully"; + } + else + { + // 失败逻辑 + resModel.Code = 1111; + resModel.Message = "TrackIn_Inquiry :" + strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + funTrackIn_Inquiry = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "funTrackIn_Inquiry", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "TrackIn_Inquiry", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + + } + return funTrackIn_Inquiry; + } + + /// + /// 首站-出站接口 + /// + /// + /// + /// + /// 首站-出站接口 + /// + /// + /// + public static string funTrackOut_Inquiry(object parameters) + { + string funTrackOut_Inquiry = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + bool bolclsEAP = false; + + + try + { + //获取进站报文 + strRequestJson = modERP.funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //检查mono和eqp_id是否都传 + + if (result.mono == null || result.eqp_id == null || result.panleid == null || result.qty == null || result.column == null || result.line == null) + { + throw new Exception("[%工单编号,设备编号,panleid,数量,行数,列数都必须传入!%]"); + } + + + + //判空 + if (result.mono == "" || result.eqp_id == "" || result.panleid == "" || result.qty == "" || result.column == "" || result.line == "") + { + throw new Exception("[%工单编号,设备编号,panleid,数量,行数,列数都必须传入!%]"); + } + + //数量不能为0或者负数 + if (Convert.ToDecimal(result.qty) <= 0) + { + throw new Exception("[%数量不能为0或者负数!%]"); + } + + + bolclsEAP = clsEAP.funTrackOut_Inquiry(ref strMessage, ref strException, MONO: result.mono, EQPID: result.eqp_id, PanleId: result.panleid, Column: result.column, Line: result.line, carrierId: result.carrier_id, Qty: Convert.ToDecimal(result.qty), MapData: result.mapdata); + if (bolclsEAP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + var resModel = new EAP_funTrackInOut_Inquiry_Response(); + if (strResult == "success") + { + resModel.Code = 0; + resModel.Message = "TrackOut_Inquiry successfully"; + } + else + { + // 失败逻辑 + resModel.Code = 1111; + resModel.Message = "TrackOut_Inquiry :" + strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + funTrackOut_Inquiry = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "funTrackOut_Inquiry", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "TrackOut_Inquiry", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + + } + return funTrackOut_Inquiry; + } + + + + /// + /// 进站接口 + /// + /// + /// + public static string funTrackIn_Inquiry_LQ(object parameters) + { + string funTrackIn_Inquiry = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + bool bolclsEAP = false; + + try + { + //获取进站报文 + strRequestJson = modERP.funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //检查mono和eqp_id是否都传 + + if ( result.eqp_id == null) + { + throw new Exception("[%设备编号必须传入!%]"); + } + + //判空 + if ( result.eqp_id == "") + { + throw new Exception("[%type或者设备编号不能为空!%]"); + } + + if (result.ID == null) + { + throw new Exception("[%ID必须传入!%]"); + } + + //判空 + if (result.ID == "") + { + throw new Exception("[%ID编号不能为空!%]"); + } + + bolclsEAP = clsEAP.funTrackIn_Inquiry_LQ(ref strMessage, ref strException, EQPID: result.eqp_id, result.ID,result.remark); + if (bolclsEAP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + var resModel = new EAP_funTrackInOut_Inquiry_Response(); + if (strResult == "success") + { + resModel.Code = 0000; + resModel.Message = "TrackIn_Inquiry_LQ successfully"; + } + else + { + // 失败逻辑 + resModel.Code = 1111; + resModel.Message = "TrackIn_Inquiry_LQ :" + strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + funTrackIn_Inquiry = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "funTrackIn_Inquiry_LQ", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "TrackIn_Inquiry_LQ", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + + } + return funTrackIn_Inquiry; + } + + public static string funTrackOut_Inquiry_LQ(object parameters) + { + string funTrackOut_Inquiry = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + bool bolclsEAP = false; + + + try + { + //获取进站报文 + strRequestJson = modERP.funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //检查mono和eqp_id是否都传 + + if (result.eqp_id == null) + { + throw new Exception("[%设备编号必须传入!%]"); + } + + //判空 + if (result.eqp_id == "") + { + throw new Exception("[%type或者设备编号不能为空!%]"); + } + + if (result.ID == null) + { + throw new Exception("[%ID必须传入!%]"); + } + + //判空 + if (result.ID == "") + { + throw new Exception("[%ID编号不能为空!%]"); + } + + + bolclsEAP = clsEAP.funTrackOut_Inquiry_LQ(ref strMessage, ref strException, result.eqp_id, result.ID, result.remark); + if (bolclsEAP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + var resModel = new EAP_funTrackInOut_Inquiry_Response(); + if (strResult == "success") + { + resModel.Code = 0; + resModel.Message = "TrackOut_Inquiry_LQ successfully"; + } + else + { + // 失败逻辑 + resModel.Code = 1111; + resModel.Message = "TrackOut_Inquiry_LQ :" + strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + funTrackOut_Inquiry = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "funTrackOut_Inquiry_LQ", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "TrackOut_Inquiry_LQ", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + + } + return funTrackOut_Inquiry; + } + #endregion + #region"Mapping反转方向接口" + /// + /// 计量 + /// + /// + /// + public static string PrdMapping(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + //调 clsERP 传入参数 + string Productid = ""; + string Eqp_id = ""; + + var listTest = new List(); + int REVERSALMETHOD = -1; + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //要因 没有值,则给 * + Productid = GetSafeString(result.Productid); + Eqp_id = GetSafeString(result.Eqp_id); + + bool bolclsERP = clsERP.funGetPrdMapping(ref strMessage, ref strException, Productid, Eqp_id, ref REVERSALMETHOD); + + if (bolclsERP == true) + { + strResult = "success"; + } + else + { + strResult = "fail"; + } + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + MappingResponse response = null; + + if (strResult == "success") + { + ResponseData data = new ResponseData(); + if (REVERSALMETHOD == 0) + { + data.REVERSALMETHOD = "上下反转"; + } + else if (REVERSALMETHOD == 1) + { + data.REVERSALMETHOD = "左右反转"; + } + else if (REVERSALMETHOD == 2) + { + data.REVERSALMETHOD = "上下左右反转"; + } + else + { + data.REVERSALMETHOD = "无反转"; + } + response = new MappingResponse + { + code = "0000", + message = "成功", + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = data, + extras = null, + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + else + { + // 失败逻辑 + response = new MappingResponse + { + code = "1111", + message = strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = null, + extras = null, + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "PrdMapping", + "ERP", "ERP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "PrdMapping", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "ERP"); + } + + return GetJLSPCData; + } + public static string GetSafeString(string value, string defaultValue = "*") + { + return string.IsNullOrEmpty(value) ? defaultValue : value; + } + #endregion + + #region "MakingCode明码查询接口" + /// + /// 明码查询接口 + /// + /// + /// + public static string MakingCode(object parameters) + { + string GetMakingCode = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JSON + string strRequestJson = ""; //传入JSON + + //返回数据 + string strMAKINGCODE = ""; + string strUNITSN = ""; + + try + { + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + string PanelSN = GetSafeString(result.PanelSN, ""); + string EQPID = GetSafeString(result.EQPID, ""); + + if (string.IsNullOrEmpty(PanelSN)) + { + throw new Exception("[%PanelSN不能为空!%]"); + } + if (string.IsNullOrEmpty(EQPID)) + { + throw new Exception("[%EQPID不能为空!%]"); + } + + bool bolclsEAP = clsEAP.funMakingCode(ref strMessage, ref strException, PanelSN, EQPID, ref strMAKINGCODE, ref strUNITSN); + + if (bolclsEAP == true) + { + strResult = "success"; + } + else + { + strResult = "fail"; + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + } + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + //组装返回JSON + MakingCodeResponse response = null; + + if (strResult == "success") + { + var data = new MakingCodeResponseData + { + MAKINGCODE = strMAKINGCODE, + UNITSN = strUNITSN + }; + response = new MakingCodeResponse + { + code = "0000", + message = "MakingCode successfully", + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = data, + extras = new Dictionary(), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + else + { + response = new MakingCodeResponse + { + code = "1111", + message = "MakingCode :" + strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = new MakingCodeResponseData(), + extras = new Dictionary(), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + + //resModel 转成JSON返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetMakingCode = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "MakingCode", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "MakingCode", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + } + + return GetMakingCode; + } + #endregion + + #region "LotMessage批次信息查询接口" + /// + /// 批次信息查询接口 + /// + /// + /// + public static string LotMessage(object parameters) + { + string GetLotMessage = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JSON + string strRequestJson = ""; //传入JSON + + //返回数据 + string strLOTNO = ""; + string strPROCESSNO = ""; + string strOPNO = ""; + string strPRODUCTNO = ""; + string strCUSTOMERNO = ""; + + try + { + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + string PanelSN = GetSafeString(result.PanelSN, ""); + string EQPID = GetSafeString(result.EQPID, ""); + + if (string.IsNullOrEmpty(PanelSN)) + { + throw new Exception("[%PanelSN不能为空!%]"); + } + if (string.IsNullOrEmpty(EQPID)) + { + throw new Exception("[%EQPID不能为空!%]"); + } + + bool bolclsEAP = clsEAP.funLotMessage(ref strMessage, ref strException, PanelSN, EQPID, + ref strLOTNO, ref strPROCESSNO, ref strOPNO, ref strPRODUCTNO, ref strCUSTOMERNO); + + if (bolclsEAP == true) + { + strResult = "success"; + } + else + { + strResult = "fail"; + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + } + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + //组装返回JSON + LotMessageResponse response = null; + + if (strResult == "success") + { + var data = new LotMessageResponseData + { + LOTNO = strLOTNO, + PROCESSNO = strPROCESSNO, + OPNO = strOPNO, + PRODUCTNO = strPRODUCTNO, + CUSTOMERNO = strCUSTOMERNO + }; + response = new LotMessageResponse + { + code = "0000", + message = "LotMessage successfully", + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = data, + extras = new Dictionary(), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + else + { + response = new LotMessageResponse + { + code = "1111", + message = "LotMessage :" + strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = new LotMessageResponseData(), + extras = new Dictionary(), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + + //resModel 转成JSON返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetLotMessage = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "LotMessage", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "LotMessage", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + } + + return GetLotMessage; + } + #endregion + + #region "MACBLUE MAC&蓝牙地址生成接口" + /// + /// MAC&蓝牙地址生成接口 + /// + public static string MACBLUE(object parameters) + { + string GetMACBLUE = default(string); + string strResult = ""; + string strMsg = ""; + string strKeyValue = ""; + var strException = new List(); + var strMessage = new List(); + string strResponseJson = ""; + string strRequestJson = ""; + + try + { + strRequestJson = funCheckJson(parameters); + string responseStr = clsEAP.funMACBLUE(strRequestJson); + + var responseJson = JsonConvert.DeserializeObject(responseStr); + if (responseJson.code == "0000") + { + strResult = "success"; + strResponseJson = responseStr; + } + else + { + strResult = "fail"; + strMsg = responseJson.message; + strResponseJson = responseStr; + } + } + catch (Exception ex) + { + strResult = "fail"; + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + MACBLUEResponse response = null; + if (strResult == "success") + { + response = JsonConvert.DeserializeObject(strResponseJson); + } + else + { + response = new MACBLUEResponse + { + code = "1111", + message = "MACBLUE :" + strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = new MACBLUEResponseData(), + extras = new Dictionary(), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + strResponseJson = JsonConvert.SerializeObject(response); + } + + GetMACBLUE = strResponseJson; + + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "MACBLUE", + "EAP", "EAP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "MACBLUE", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "EAP"); + } + + return GetMACBLUE; + } + #endregion + + + } +} \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/modERP.cs b/MESEAI/EAICws/EAICws/modERP.cs new file mode 100644 index 0000000..e371186 --- /dev/null +++ b/MESEAI/EAICws/EAICws/modERP.cs @@ -0,0 +1,4495 @@ +using API_Base; +using iMESCIOC.Request.EAP; +using iMESCIOC.Request.ERP; +using iMESCIOC.Request.WMS_Request; +using iMESCIOC.Response.EAP; +using iMESCIOC.Response.ERP; +using iMESCIOC.Response.WMS_Response; +using iMESCore.Settings; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Data; +using System.Linq; +using System.Net.Http.Headers; +using System.Reflection; +//using System.Web.Services; +using System.Xml; +using System.Xml; +using tcEAI_C; +using static iMESCore.Base.iMESConst; + +namespace EAIws_C +{ + + static class modERP + { + + public static string strService = "ERP"; + public static string strDataBaseType; + public static string strConnectionString; + + //public static string funCreateOperation(string InXml) + //{ + // string funCreateOperationRet = default(string); + // System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // 用以讀取Xml字串 + // string OutXml = null; + + // string strIdentity = string.Empty; // Identity XML字串 + // string strResult = "fail"; // Result XML字串 + // List strException = new List(); // Exception XML字串 + // List strMessage = new List(); // Message XML字串 + // string strKeyValue = string.Empty; // TransactionLot KeyValue + // string strMode = string.Empty; // Mode + + // try + // { + // try + // { + // // 讀取InXml字串 + // xmlDoc.LoadXml(InXml); + // } + // catch (Exception ex) + // { + // clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace); + // goto exitFun; + // } + + // // 組Identity字串 + // try + // { + // strIdentity = modWS.CombineXMLIdentity(xmlDoc); + // } + // catch (Exception ex) + // { + // clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace); + // goto exitFun; + // } + + + // // 2019/05/09 OwenLiu, Mantis:0057304 作業站整合若資料已存在, + // // 且ERP未傳值的狀況, 不更新OPType, OPClass, OPShortName, OPOrder + // string OPNo = string.Empty; + // string OPName = string.Empty; + // string OPType = defString; + // string PSNo = defString; + // int OPClass = defInteger; // Default 0 : General OP + // string OPShortName = defString; + // int OPOrder = defInteger; // Default 0 + // string Description = string.Empty; + // string Creator = string.Empty; + // DateTime CreateDate = DateTime.Now; // Default Today + // int PrintOutOnRunCard = 1; // Default 1 + // double StdUnitRunTime = 0; // Default 0 + // long CountOpUnitQty = 1; // Default 1 + // double StdQueueTime = 0; // Default 0 + // decimal decStdUnitRunTime = defInteger; + // decimal decCountOpUnitQty = defInteger; + // decimal decStdQueueTime = defInteger; + // int OSOption = defInteger; + // int OSOptionTemp = defInteger; + // string ERPPDLineNo = defString; + // // Dim OldERPPDLineNo As String = defString '存放作業站修改前的群組資料 + + // // OPNo + // if (xmlDoc.DocumentElement.GetElementsByTagName("opno").Count > 0 && xmlDoc.GetElementsByTagName("opno").Item(0).SelectNodes("value").Count > 0) + // OPNo = modWS.CInput(xmlDoc.DocumentElement.GetElementsByTagName("opno").Item(0).SelectNodes("value").Item(0).InnerText); + + // // OPName + // if (xmlDoc.DocumentElement.GetElementsByTagName("opname").Count > 0 && xmlDoc.GetElementsByTagName("opname").Item(0).SelectNodes("value").Count > 0) + // OPName = modWS.CInput(xmlDoc.DocumentElement.GetElementsByTagName("opname").Item(0).SelectNodes("value").Item(0).InnerText); + + + + // // 判斷成功與否 + // if (strException.Count > 0) + // goto exitFun; + + // strResult = "success"; + + // exitFun: + // ; + // } + + // catch (Exception ex) + // { + // clsERP.combineException(ref strException, null, ex.Message, "[%CreateOPFail%]", ex.StackTrace); + // } + + // finally + // { + + // // 將各部份之XML字串組起來並傳出 + // OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage); + + // funCreateOperationRet = OutXml; + // } + + // return funCreateOperationRet; + //} + + + #region --- SD_DSC_SI009 MO --- + public static string funAddMO(string InXml) + { + string funAddMORet = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + var strAlert = new List(); + + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + string MONo = string.Empty; + string RONo = string.Empty; + string ItemNo = string.Empty; // RO ItemNo + string CustomerNo = string.Empty; + string CustomerLotNo = string.Empty; + string MOUnitNo = string.Empty; // MOUnitNo + string ProductNo = string.Empty; + string ProductVersion = string.Empty; + decimal MOQty = 0m; + int MOTypeNo = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOTypeNo"]); + int Priority = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPriority"]); + var PlanFinishDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanFinishDate"]), DateTime.Now); + var PlanStartDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanStartDate"]), Convert.ToDateTime(Strings.Format(DateTime.Now, "yyyy/MM/dd"))); + string Creator = string.Empty; + var CreateDate = DateTime.Now; // Default Today + string Description = string.Empty; + string FactoryNo = string.Empty; + var MOProperty = new List(); + int MaterialLevel = defInteger; + int wipEntityId = defInteger; + string bomVersion = string.Empty; + string lcPlantype = string.Empty; + string faiFlag = string.Empty; + + string strERPMOLineNo = defString; + string strDeliveryMethod = defString; + + string SubstituteMaterialNo = string.Empty; + string MaterialNo = string.Empty; + string OPNO = string.Empty; + string Orgcode = string.Empty; + string OrgMono = string.Empty; + + if (xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Count > 0 && xmlDoc.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText; + Orgcode = modWS.CInput_Singlequotation(argstrInput); + xmlDoc.DocumentElement.GetElementsByTagName("orgcode").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Count > 0 && xmlDoc.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText; + OrgMono = modWS.CInput_Singlequotation(argstrInput); + xmlDoc.DocumentElement.GetElementsByTagName("orgmono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput; + } + // MONo + if (xmlDoc.DocumentElement.GetElementsByTagName("mono").Count > 0 && xmlDoc.GetElementsByTagName("mono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText; + MONo = modWS.CInput_Singlequotation(argstrInput); + xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput; + } + + // RONo + if (xmlDoc.DocumentElement.GetElementsByTagName("rono").Count > 0 && xmlDoc.GetElementsByTagName("rono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput1 = xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText; + RONo = modWS.CInput_Singlequotation(argstrInput1); + xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput1; + } + + // ItemNo + if (xmlDoc.DocumentElement.GetElementsByTagName("itemno").Count > 0 && xmlDoc.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput2 = xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText; + ItemNo = modWS.CInput_Singlequotation(argstrInput2); + xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput2; + } + + // 如傳入的值為0001則轉換成1 + if (!string.IsNullOrEmpty(ItemNo)) + { + ItemNo = Conversions.ToInteger(ItemNo).ToString(); + } + + + // CustomerNo + if (xmlDoc.DocumentElement.GetElementsByTagName("customerno").Count > 0 && xmlDoc.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText; + CustomerNo = modWS.CInput_Singlequotation(argstrInput3); + xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3; + } + + // CustomerLotNo + if (xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Count > 0 && xmlDoc.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText; + CustomerLotNo = modWS.CInput_Singlequotation(argstrInput3); + xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3; + } + + // MOUnitNo + if (xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Count > 0 && xmlDoc.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput4 = xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText; + MOUnitNo = modWS.CInput_Singlequotation(argstrInput4); + xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput4; + } + + // ProductNo + if (xmlDoc.DocumentElement.GetElementsByTagName("productno").Count > 0 && xmlDoc.GetElementsByTagName("productno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput5 = xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText; + ProductNo = modWS.CInput_Singlequotation(argstrInput5); + xmlDoc.DocumentElement.GetElementsByTagName("productno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput5; + } + + // FactoryNo + if (xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Count > 0 && xmlDoc.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput6 = xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText; + FactoryNo = modWS.CInput_Singlequotation(argstrInput6); + xmlDoc.DocumentElement.GetElementsByTagName("factoryno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput6; + } + + // MOQty + if (xmlDoc.DocumentElement.GetElementsByTagName("moqty").Count > 0 && xmlDoc.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + MOQty = Convert.ToDecimal(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText); + + // MOTypeNo + if (xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Count > 0 && xmlDoc.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) == true) + { + MOTypeNo = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText); + } + else + { + clsERP.combineException(ref strException, mesmsg: "[%MOTypeError%]"); + } + // Priority + if (xmlDoc.DocumentElement.GetElementsByTagName("priority").Count > 0 && xmlDoc.GetElementsByTagName("priority").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + Priority = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText); + + // PlanFinishDate + if (xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Count > 0 && xmlDoc.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + PlanFinishDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // PlanStartDate + if (xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Count > 0 && xmlDoc.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + PlanStartDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // Creator + Creator = modWS.GetXMLIdentityNode(xmlDoc, "curuserno"); + + // Description + if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput7 = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText; + Description = modWS.CInput_Singlequotation(argstrInput7); + xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput7; + } + + // 2018/3/19 Vick 新增欄位 ERPMOLineNo + if (xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Count > 0 && xmlDoc.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText; + strERPMOLineNo = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + + if (xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Count > 0 && xmlDoc.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + wipEntityId = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText); + + + if (xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Count > 0 && xmlDoc.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText; + bomVersion = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Count > 0 && xmlDoc.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText; + lcPlantype = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Count > 0 && xmlDoc.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText; + faiFlag = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(MONo)) + clsERP.combineException(ref strException, mesmsg: "[%MONoEmpty%]"); + if (string.IsNullOrEmpty(MOUnitNo)) + clsERP.combineException(ref strException, mesmsg: "[%MOUnitNoEmpty%]"); + if (string.IsNullOrEmpty(ProductNo)) + clsERP.combineException(ref strException, mesmsg: "[%ProductNoEmpty%]"); + if (string.IsNullOrEmpty(FactoryNo)) + clsERP.combineException(ref strException, mesmsg: "[%FactoryNoEmpty%]"); + if (MOQty <= 0m) + clsERP.combineException(ref strException, mesmsg: "[%MOQtyError%]"); + if (strException.Count > 0) + goto exitFun; + + // 2019/08/16 Grace 新增tblOEMOBasis.FromERP=1處理, 不需在Description填入"From ERP" + // '20180514 KevinChang 0046325: TIPTOP工單整合-工單刪除問題 + // Description = IIf(String.IsNullOrEmpty(Description), "From ERP", "From ERP," & Description) + + // ----- MO Detail ----- + var dtMTL = new DataTable("MOMaterialList"); + dtMTL.Columns.Add("MONo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialLevel", Type.GetType("System.Int16")); + dtMTL.Columns.Add("StdQty", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("UnitNo", Type.GetType("System.String")); + dtMTL.Columns.Add("OPNo", Type.GetType("System.String")); + dtMTL.Columns.Add("PutInPlaceType", Type.GetType("System.Int16")); + dtMTL.Columns.Add("DecreaseRate", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("Specified", Type.GetType("System.Int16")); + dtMTL.Columns.Add("MaterialType", Type.GetType("System.String")); + dtMTL.Columns.Add("CountWay", Type.GetType("System.Int16")); + dtMTL.Columns.Add("CheckLotNo", Type.GetType("System.Int16")); + dtMTL.Columns.Add("MaterialVersion", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String")); + dtMTL.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String")); + dtMTL.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int16")); // 2012/12/26,Even,新增替代物料及物料使用量 + dtMTL.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 2012/12/28,Even,新增替代料標準數 + dtMTL.Columns.Add("RequireQty", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("DeliveryMethod", Type.GetType("System.String")); // 2019/09/26 Grace 新增"材料型態" + + dtMTL.Columns.Add("MainItem", Type.GetType("System.String")); //主料编号 + dtMTL.Columns.Add("PhantomItem", Type.GetType("System.String")); //虚拟件 + dtMTL.Columns.Add("LockRequirement", Type.GetType("System.String")); //是否锁定需求 + dtMTL.Columns.Add("OperationSeqnum", Type.GetType("System.String")); //工序 + if (xmlDoc.DocumentElement.GetElementsByTagName("momateriallist").Count > 0) + { + if (xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value"); + if (xmlList.Count == 0) + { + clsERP.combineException(ref strMessage, mesmsg: "[%MOMaterialListNotExist%]"); + } + else + { + DataRow dr; + bool errorFlag = false; + for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++) + { + OPNO = string.Empty; + errorFlag = false; + try + { + dr = dtMTL.NewRow(); + + // ----- MONo ----- + dr["MONo"] = MONo; + + // ----- MaterialMo ----- + if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText)) + { + dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper(); + MaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper(); + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListMaterialNoError%]"); + } + + // ----- MaterialLevel ----- + if (xmlList[i].SelectNodes("materiallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) == true) + + { + MaterialLevel = Conversions.ToInteger(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText); + } + else + { + // Default value + MaterialLevel = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListMaterialLevel"]); + } + dr["MaterialLevel"] = MaterialLevel; + + // ----- StdQty ----- + decimal dblStdQty = 0m; + + if (xmlList[i].SelectNodes("stdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) == true) + + { + dr["StdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("stdqty").Item(0).InnerText); + + dblStdQty = Convert.ToDecimal(dr["StdQty"]); // 暫存StdQty + } + + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListSTDQtyError%]"); + } + + // ----- UnitNo ----- + if (xmlList[i].SelectNodes("unitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("unitno").Item(0).InnerText)) + { + string argstrInput9 = xmlList[i].SelectNodes("unitno").Item(0).InnerText; + dr["UnitNo"] = modWS.CInput_Singlequotation(argstrInput9); + xmlList[i].SelectNodes("unitno").Item(0).InnerText = argstrInput9; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListUnitNoError%]"); + } + + // ----- PutInPlaceType ----- + if (xmlList[i].SelectNodes("putinplacetype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText.ToUpper()) == true) + + { + dr["PutInPlaceType"] = Conversions.ToInteger(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText); + } + else + { + // Default value + dr["PutInPlaceType"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListPutInPlaceType"]); + } + + // ----- DecreaseRate ----- + if (xmlList[i].SelectNodes("decreaserate").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) == true) + + { + dr["DecreaseRate"] = Convert.ToDecimal(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText); + } + else + { + // Default value + dr["DecreaseRate"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListDecreaseRate"]); + } + + // ----- Specified ----- + if (xmlList[i].SelectNodes("specified").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("specified").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("specified").Item(0).InnerText) == true) + + { + dr["Specified"] = Convert.ToDecimal(xmlList[i].SelectNodes("specified").Item(0).InnerText); + } + else + { + // Default value + dr["Specified"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListSpecified"]); + } + + // ----- MaterialType----- + if (xmlList[i].SelectNodes("materialtype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialtype").Item(0).InnerText)) + + { + string argstrInput10 = xmlList[i].SelectNodes("materialtype").Item(0).InnerText; + dr["MaterialType"] = modWS.CInput_Singlequotation(argstrInput10); + xmlList[i].SelectNodes("materialtype").Item(0).InnerText = argstrInput10; + } + + // ----- CountWay ----- + if (xmlList[i].SelectNodes("countway").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("countway").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("countway").Item(0).InnerText) == true) + + { + dr["CountWay"] = Conversions.ToInteger(xmlList[i].SelectNodes("countway").Item(0).InnerText); + } + else + { + // Default value + dr["CountWay"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListCountWay"]); + } + + // ----- CheckLotNo ----- + if (xmlList[i].SelectNodes("checklotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) == true) + + + dr["CheckLotNo"] = Conversions.ToInteger(xmlList[i].SelectNodes("checklotno").Item(0).InnerText); + + // ----- MaterialVersion ----- + if (xmlList[i].SelectNodes("materialversion").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialversion").Item(0).InnerText)) + + { + string argstrInput11 = xmlList[i].SelectNodes("materialversion").Item(0).InnerText; + dr["MaterialVersion"] = modWS.CInput_Singlequotation(argstrInput11); + xmlList[i].SelectNodes("materialversion").Item(0).InnerText = argstrInput11; + } + + // ----- SubstituteMaterialNo ----- + if (xmlList[i].SelectNodes("substitutematerialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText)) + { + dr["SubstituteMaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper(); + SubstituteMaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper(); + } + else + { + // Default value + dr["SubstituteMaterialNo"] = dr["materialno"].ToString().ToUpper(); + SubstituteMaterialNo = dr["materialno"].ToString().ToUpper(); + } + + // ----- OPNo ----- + // 若有傳入作業站資訊以傳入的資訊為主 + // 若沒有傳入作業站資訊,則優先以產品BOM上定義的作業站,若產品BOM無定義,以物料屬性 PutInPlace_OPNo 中的值為主 + // 若皆無傳入則以Config中定義的作業站為主 + if (xmlList[i].SelectNodes("opno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("opno").Item(0).InnerText)) + { + string argstrInput12 = xmlList[i].SelectNodes("opno").Item(0).InnerText; + dr["OPNo"] = modWS.CInput_Singlequotation(argstrInput12); + xmlList[i].SelectNodes("opno").Item(0).InnerText = argstrInput12; + } + else + { + // 檢查產品BOM是否有定義,若無繼續往下查找對應作業站資訊 + using (var objPRD = new kcPRD.clsProduct()) + { + try + { + ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper()); + } + catch (Exception ex) + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%GetProductVersionFail%]"); + } + + DataSet dsTemp_PRD; + if (SubstituteMaterialNo == MaterialNo) + { + dsTemp_PRD = objPRD.ShowBOM(ProductNo, ProductVersion, MaterialNo); + if (dsTemp_PRD.Tables["PRDBOM"].Rows.Count > 0) + { + OPNO = dsTemp_PRD.Tables["PRDBOM"].Rows[0]["OPNO"].ToString().ToUpper(); + dsTemp_PRD = null; + } + else + { + dsTemp_PRD = null; + } + } + else + { + dsTemp_PRD = objPRD.ShowBOMMaterialGroup(ProductNo, ProductVersion, MaterialNo, MaterialNo: SubstituteMaterialNo); + if (dsTemp_PRD.Tables["MaterialGroup"].Rows.Count > 0) + { + OPNO = dsTemp_PRD.Tables["MaterialGroup"].Rows[0]["OPNO"].ToString().ToUpper(); + dsTemp_PRD = null; + } + else + { + dsTemp_PRD = null; + } + } + + } + + if (string.IsNullOrEmpty(OPNO)) + { + // 檢查物料屬性是否有定義,若繼續往下查找對應作業站資訊 + DataSet dsTemp_MTL; + using (var objMTL = new kcMTL.clsMTLBasis()) + { + dsTemp_MTL = objMTL.ShowMaterialProperty(SubstituteMaterialNo, "PutInPlace_OPNo", 2); + if (dsTemp_MTL.Tables["MaterialProperty"].Rows.Count > 0) + { + OPNO = dsTemp_MTL.Tables["MaterialProperty"].Rows[0]["DEFAULTVALUE"].ToString().ToUpper(); + dsTemp_MTL = null; + } + else + { + dsTemp_MTL = null; + } + } + + if (string.IsNullOrEmpty(OPNO)) + { + // Default value + dr["OPNo"] = ConfigurationManager.AppSettings["defMOListOPNo"]; + } + else + { + dr["OPNo"] = OPNO; + } + } + else + { + dr["OPNo"] = OPNO; + } + + } + + // 2012/02/18,Even,新增替代物料等級、替代料標準數及物料使用量------- + // ----- SubstituteMaterialLevel ----- + if (xmlList[i].SelectNodes("substitutemateriallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) == true) + + { + dr["SubstituteMaterialLevel"] = Conversions.ToInteger(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText); + } + else + { + // Default value,未抓取到,抓取MaterialLevel + dr["SubstituteMaterialLevel"] = MaterialLevel; + } + // ----- SubstituteStdQty -- + if (xmlList[i].SelectNodes("substitutestdqty").Count > 0 && + !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) && + Information.IsNumeric(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText)) + { + dr["SubstituteStdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText); + + if (dr["MaterialNo"].ToString() == dr["SubstituteMaterialNo"].ToString()) + { + if (Convert.ToDecimal(dr["stdqty"]) != Convert.ToDecimal(dr["substitutestdqty"])) + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: dr["MaterialNo"].ToString() + "[%StdQtyAndSubstituteStdQtyMustBeTheSame%]"); + } + } + } + else + { + // 2018/09/20 OwenLiu, 因為後端程式會重新計算,這邊取消預設值的指定 + // 'Default value,未抓取到,抓取則抓物料之標準數 + // dr("SubstituteStdQty") = dr("StdQty") + } + // ----- RequireQty--------若無資料則為工單數 * 標準數*(1+損耗率) + if (xmlList[i].SelectNodes("requireqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) == true) + + { + dr["RequireQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("requireqty").Item(0).InnerText); + } + else + { + // 2018/09/20 OwenLiu, 因為後端程式會重新計算,這邊取消預設值的指定 + // 'Default value + // dr("RequireQty") = MOQty * dblStdQty * (1 + dr("DecreaseRate")) + } + + + // ----- DeliveryMethod ----- + // 2019/09/26 Grace 新增tagname, 材料型態:DeliveryMethod (Optional參數,非必傳) + if (xmlList[i].SelectNodes("deliverymethod").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText; + dr["DeliveryMethod"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText = argstrInput13; + } + + + if (xmlList[i].SelectNodes("mainitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("mainitem").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("mainitem").Item(0).InnerText; + dr["MainItem"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("mainitem").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("phantomitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("phantomitem").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("phantomitem").Item(0).InnerText; + dr["PhantomItem"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("phantomitem").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("lockrequirement").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText; + dr["LockRequirement"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("operationseqnum").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText; + dr["OperationSeqnum"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText = argstrInput13; + } + + if (errorFlag == false) + { + dtMTL.Rows.Add(dr); + } + } + + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOMaterialListError%]", stack: ex.StackTrace); + } + } + } + } + } + + // ----- MO Property ----- + var dtMOProperty = new DataTable("MOProperty"); + dtMOProperty.Columns.Add("MONo", Type.GetType("System.String")); + dtMOProperty.Columns.Add("PropertyNo", Type.GetType("System.String")); + dtMOProperty.Columns.Add("PropertyValue", Type.GetType("System.String")); + dtMOProperty.Columns.Add("DataType", Type.GetType("System.String")); // DataType: 0:Numeric, 1:String(default), 2:Percent, 3:DateTime, 4:Boolean + + // web.config裡預設的MOProperty (ERPUnitNo)(原本是寫在ArrayList裡,改寫在DataTable裡) + if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["defERPUnitNoProperty"])) + { + DataRow drP; + drP = dtMOProperty.NewRow(); + drP["MONo"] = MONo; + drP["PropertyNo"] = ConfigurationManager.AppSettings["defERPUnitNoProperty"]; + drP["PropertyValue"] = MOUnitNo; + drP["DataType"] = "String"; + dtMOProperty.Rows.Add(drP); + } + + // ERP拋過來的工單屬性 + if (xmlDoc.DocumentElement.GetElementsByTagName("property").Count > 0) + { + if (xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value"); + if (xmlList.Count == 0) + { + } + // clsERP.combineMessage(strMessage, , , "[%MOPropertyNotExist%]") + else + { + DataRow dr; + bool errorFlag = false; + for (int i = 0, loopTo1 = xmlList.Count - 1; i <= loopTo1; i++) + { + errorFlag = false; + try + { + dr = dtMOProperty.NewRow(); + + // ----- MONo ----- + dr["MONo"] = MONo; + + // ----- PropertyNo ----- + if (xmlList[i].SelectNodes("name").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("name").Item(0).InnerText)) + { + string argstrInput14 = xmlList[i].SelectNodes("name").Item(0).InnerText; + dr["PropertyNo"] = modWS.CInput_Singlequotation(argstrInput14); + xmlList[i].SelectNodes("name").Item(0).InnerText = argstrInput14; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%PropertyNoEmpty%]"); + } + + // ----- PropertyValue ----- + if (xmlList[i].SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("value").Item(0).InnerText)) + { + string argstrInput15 = xmlList[i].SelectNodes("value").Item(0).InnerText; + dr["PropertyValue"] = modWS.CInput_Singlequotation(argstrInput15); + xmlList[i].SelectNodes("value").Item(0).InnerText = argstrInput15; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%PropertyValueEmpty%]"); + } + + // ----- DataType ----- + if (xmlList[i].SelectNodes("type").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("type").Item(0).InnerText)) + { + string argstrInput16 = xmlList[i].SelectNodes("type").Item(0).InnerText; + dr["DataType"] = modWS.CInput_Singlequotation(argstrInput16); + xmlList[i].SelectNodes("type").Item(0).InnerText = argstrInput16; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%DataTypeEmpty%]"); + } + + if (errorFlag == false) + { + dtMOProperty.Rows.Add(dr); + } + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOPropertyError%]", stack: ex.StackTrace); + } + } + } + } + } + + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = MONo; + + // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit ----- + clsOE.addMO(Orgcode, OrgMono, MONo, MOUnitNo, ProductNo, MOQty, FactoryNo, RONo, ItemNo, CustomerNo, MOTypeNo, Priority, PlanFinishDate, Creator, CreateDate, Description, dtMTL, MOProperty, strMessage, strException, strAlert, dtMOProperty, strERPMOLineNo, CustomerLotNo, PlanStartDate, wipEntityId: wipEntityId, bomVersion: bomVersion, lcPlantype: lcPlantype, faiFlag: faiFlag); + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: ex.StackTrace); + } + + finally + { + + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + + // 紀錄Transaction Log + try + { + clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMO", Conversions.ToInteger(ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + } + catch (Exception ex) + { + string strMsg = ex.Message; + } + + + funAddMORet = OutXml; + + } + + return funAddMORet; + + } + + public static string funEditMO(string InXml) + { + string funEditMORet = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + var strAlert = new List(); + string strKeyValue = string.Empty; // TransactionLot KeyValue + + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + string MONo = string.Empty; + string RONo = string.Empty; + string ItemNo = string.Empty; // RO ItemNo + string CustomerNo = string.Empty; + string CustomerLotNo = string.Empty; //CustomerLotNo + decimal MOQty = 0m; + int MOTypeNo = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOTypeNo"]); + int Priority = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPriority"]); + var PlanFinishDate = DateAndTime.DateAdd(DateInterval.Day, Conversions.ToInteger(ConfigurationManager.AppSettings["defMOPlanFinishDate"]), DateTime.Now); + var PlanStartDate = defDateTime; + string Creator = string.Empty; + var CreateDate = DateTime.Now; // Default Today + string Description = string.Empty; + string MOUnitNo = string.Empty; + int MaterialLevel = defInteger; + int wipEntityId = defInteger; + string bomVersion = string.Empty; + string lcPlantype = string.Empty; + string faiFlag = string.Empty; + + string strERPMOLineNo = defString; + + string ProductNo = string.Empty; + string ProductVersion = string.Empty; + string SubstituteMaterialNo = string.Empty; + string MaterialNo = string.Empty; + string OPNO = string.Empty; + + // MONo + if (xmlDoc.DocumentElement.GetElementsByTagName("mono").Count > 0 && xmlDoc.GetElementsByTagName("mono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText; + MONo = modWS.CInput_Singlequotation(argstrInput); + xmlDoc.DocumentElement.GetElementsByTagName("mono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput; + } + + // RONo + if (xmlDoc.DocumentElement.GetElementsByTagName("rono").Count > 0 && xmlDoc.GetElementsByTagName("rono").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput1 = xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText; + RONo = modWS.CInput_Singlequotation(argstrInput1); + xmlDoc.DocumentElement.GetElementsByTagName("rono").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput1; + } + + // ItemNo + if (xmlDoc.DocumentElement.GetElementsByTagName("itemno").Count > 0 && xmlDoc.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput2 = xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText; + ItemNo = modWS.CInput_Singlequotation(argstrInput2); + xmlDoc.DocumentElement.GetElementsByTagName("itemno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput2; + } + + // 如傳入的值為0001則轉換成1 + if (!string.IsNullOrEmpty(ItemNo)) + { + ItemNo = Conversions.ToInteger(ItemNo).ToString(); + } + + // CustomerNo + if (xmlDoc.DocumentElement.GetElementsByTagName("customerno").Count > 0 && xmlDoc.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText; + CustomerNo = modWS.CInput_Singlequotation(argstrInput3); + xmlDoc.DocumentElement.GetElementsByTagName("customerno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3; + } + + // CustomerLotNo + if (xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Count > 0 && xmlDoc.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput3 = xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText; + CustomerLotNo = modWS.CInput_Singlequotation(argstrInput3); + xmlDoc.DocumentElement.GetElementsByTagName("customerlotno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput3; + } + + // MOQty + if (xmlDoc.DocumentElement.GetElementsByTagName("moqty").Count > 0 && xmlDoc.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + MOQty = Convert.ToDecimal(xmlDoc.DocumentElement.GetElementsByTagName("moqty").Item(0).SelectNodes("value").Item(0).InnerText); + + // MOTypeNo + if (xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Count > 0 && xmlDoc.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + MOTypeNo = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("motypeno").Item(0).SelectNodes("value").Item(0).InnerText); + + // Priority + if (xmlDoc.DocumentElement.GetElementsByTagName("priority").Count > 0 && xmlDoc.GetElementsByTagName("priority").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + Priority = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("priority").Item(0).SelectNodes("value").Item(0).InnerText); + + // PlanFinishDate + if (xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Count > 0 && xmlDoc.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + PlanFinishDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planfinishdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // PlanStartDate + if (xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Count > 0 && xmlDoc.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsDate(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + PlanStartDate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("planstartdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // Creator + Creator = modWS.GetXMLIdentityNode(xmlDoc, "curuserno"); + + // Description + if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText)) + + + Description = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText; + + // MOUnitNo + if (xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Count > 0 && xmlDoc.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput4 = xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText; + MOUnitNo = modWS.CInput_Singlequotation(argstrInput4); + xmlDoc.DocumentElement.GetElementsByTagName("mounitno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput4; + } + + // 2018/3/19 Vick 新增欄位 ERPMOLineNo + if (xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Count > 0 && xmlDoc.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput5 = xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText; + strERPMOLineNo = modWS.CInput_Singlequotation(argstrInput5); + xmlDoc.DocumentElement.GetElementsByTagName("erpmolineno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput5; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Count > 0 && xmlDoc.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) && Information.IsNumeric(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText) == true) + + + + wipEntityId = Conversions.ToInteger(xmlDoc.DocumentElement.GetElementsByTagName("wipentityid").Item(0).SelectNodes("value").Item(0).InnerText); + + + if (xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Count > 0 && xmlDoc.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText; + bomVersion = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("bomversion").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Count > 0 && xmlDoc.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText; + lcPlantype = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("lcplantype").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Count > 0 && xmlDoc.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText)) + + + { + string argstrInput8 = xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText; + faiFlag = modWS.CInput_Singlequotation(argstrInput8); + xmlDoc.DocumentElement.GetElementsByTagName("faiflag").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput8; + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(MONo)) + clsERP.combineException(ref strException, mesmsg: "[%MONoEmpty%]"); + if (MOQty <= 0m) + clsERP.combineException(ref strException, mesmsg: "[%MOQtyError%]"); + + // 2022/04/08 Eric 檢查產品資訊,並取得目前產品資訊用於後續判斷投料作業站 + using (var objOE = new kcOE.clsOEBasis()) + { + DataSet dsTemp_OE; + dsTemp_OE = objOE.ShowMOBasis(MONo); + if (dsTemp_OE.Tables["OEMOBasis"].Rows.Count > 0) + { + ProductNo = dsTemp_OE.Tables["OEMOBasis"].Rows[0]["ProductNo"].ToString().ToUpper(); + ProductVersion = dsTemp_OE.Tables["OEMOBasis"].Rows[0]["ProductVersion"].ToString().ToUpper(); + dsTemp_OE = null; + } + else + { + // 工單編號不存在 + clsERP.combineException(ref strException, mesmsg: "[%MONoNotExist%]"); + dsTemp_OE = null; + } + } + + if (strException.Count > 0) + goto exitFun; + + // 2019/02/24 OwenLiu, Mantis:0055248 TIPTOP工單整合-工單刪除問題 + Description = (string.IsNullOrEmpty(Description) ? "From ERP" : "From ERP," + Description); + + // ----- MO Detail ----- + var dtMTL = new DataTable("MOMaterialList"); + dtMTL.Columns.Add("MONo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialLevel", Type.GetType("System.Int16")); + dtMTL.Columns.Add("StdQty", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("UnitNo", Type.GetType("System.String")); + dtMTL.Columns.Add("OPNo", Type.GetType("System.String")); + dtMTL.Columns.Add("PutInPlaceType", Type.GetType("System.Int16")); + dtMTL.Columns.Add("DecreaseRate", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("Specified", Type.GetType("System.Int16")); + dtMTL.Columns.Add("MaterialType", Type.GetType("System.String")); + dtMTL.Columns.Add("CountWay", Type.GetType("System.Int16")); + dtMTL.Columns.Add("CheckLotNo", Type.GetType("System.Int16")); + dtMTL.Columns.Add("MaterialVersion", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String")); + dtMTL.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String")); + dtMTL.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int16")); // 2012/12/26,Even,新增替代物料及物料使用量 + dtMTL.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 2012/12/28,Even,新增替代料標準數 + dtMTL.Columns.Add("RequireQty", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("DeliveryMethod", Type.GetType("System.String")); // 2019/09/26 Grace 新增"材料型態" + + dtMTL.Columns.Add("MainItem", Type.GetType("System.String")); //主料编号 + dtMTL.Columns.Add("PhantomItem", Type.GetType("System.String")); //虚拟件 + dtMTL.Columns.Add("LockRequirement", Type.GetType("System.String")); //是否锁定需求 + dtMTL.Columns.Add("OperationSeqnum", Type.GetType("System.String")); //工序 + + if (xmlDoc.DocumentElement.GetElementsByTagName("momateriallist").Count > 0) + { + if (xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("momateriallist").Item(0).SelectNodes("value"); + if (xmlList.Count == 0) + { + clsERP.combineException(ref strMessage, mesmsg: "[%MOMaterialListNotExist%]"); + } + else + { + DataRow dr; + bool errorFlag = false; + for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++) + { + OPNO = string.Empty; + errorFlag = false; + try + { + dr = dtMTL.NewRow(); + + // ----- MONo ----- + dr["MONo"] = MONo; + + // ----- MaterialMo ----- + if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText)) + { + dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper(); + MaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper(); + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListMaterialNoError%]"); + } + + // ----- MaterialLevel ----- + if (xmlList[i].SelectNodes("materiallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText) == true) + + { + MaterialLevel = Conversions.ToInteger(xmlList[i].SelectNodes("materiallevel").Item(0).InnerText); + } + else + { + // Default value + MaterialLevel = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListMaterialLevel"]); + } + dr["MaterialLevel"] = MaterialLevel; + + // ----- StdQty ----- + decimal dblStdQty = 0m; + if (xmlList[i].SelectNodes("stdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("stdqty").Item(0).InnerText) == true) + + { + + dr["StdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("stdqty").Item(0).InnerText); + dblStdQty = Convert.ToDecimal(dr["StdQty"]); + } + + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListSTDQtyError%]"); + } + + // ----- UnitNo ----- + if (xmlList[i].SelectNodes("unitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("unitno").Item(0).InnerText)) + { + string argstrInput6 = xmlList[i].SelectNodes("unitno").Item(0).InnerText; + dr["UnitNo"] = modWS.CInput_Singlequotation(argstrInput6); + xmlList[i].SelectNodes("unitno").Item(0).InnerText = argstrInput6; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialListUnitNoError%]"); + } + + // ----- PutInPlaceType ----- + if (xmlList[i].SelectNodes("putinplacetype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText.ToUpper()) == true) + + { + dr["PutInPlaceType"] = Conversions.ToInteger(xmlList[i].SelectNodes("putinplacetype").Item(0).InnerText); + } + else + { + // Default value + dr["PutInPlaceType"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListPutInPlaceType"]); + } + + // ----- DecreaseRate ----- + if (xmlList[i].SelectNodes("decreaserate").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText) == true) + + { + dr["DecreaseRate"] = Convert.ToDecimal(xmlList[i].SelectNodes("decreaserate").Item(0).InnerText); + } + else + { + // Default value + dr["DecreaseRate"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListDecreaseRate"]); + } + + // ----- Specified ----- + if (xmlList[i].SelectNodes("specified").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("specified").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("specified").Item(0).InnerText) == true) + + { + dr["Specified"] = Convert.ToDecimal(xmlList[i].SelectNodes("specified").Item(0).InnerText); + } + else + { + // Default value + dr["Specified"] = Convert.ToDecimal(ConfigurationManager.AppSettings["defMOListSpecified"]); + } + + // ----- MaterialType----- + if (xmlList[i].SelectNodes("materialtype").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialtype").Item(0).InnerText)) + + { + string argstrInput7 = xmlList[i].SelectNodes("materialtype").Item(0).InnerText; + dr["MaterialType"] = modWS.CInput_Singlequotation(argstrInput7); + xmlList[i].SelectNodes("materialtype").Item(0).InnerText = argstrInput7; + } + + // ----- CountWay ----- + if (xmlList[i].SelectNodes("countway").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("countway").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("countway").Item(0).InnerText) == true) + + { + dr["CountWay"] = Conversions.ToInteger(xmlList[i].SelectNodes("countway").Item(0).InnerText); + } + else + { + // Default value + dr["CountWay"] = Conversions.ToInteger(ConfigurationManager.AppSettings["defMOListCountWay"]); + } + + // ----- CheckLotNo ----- + if (xmlList[i].SelectNodes("checklotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("checklotno").Item(0).InnerText) == true) + + + dr["CheckLotNo"] = Conversions.ToInteger(xmlList[i].SelectNodes("checklotno").Item(0).InnerText); + + // ----- MaterialVersion ----- + if (xmlList[i].SelectNodes("materialversion").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialversion").Item(0).InnerText)) + + { + string argstrInput8 = xmlList[i].SelectNodes("materialversion").Item(0).InnerText; + dr["MaterialVersion"] = modWS.CInput_Singlequotation(argstrInput8); + xmlList[i].SelectNodes("materialversion").Item(0).InnerText = argstrInput8; + } + + // ----- SubstituteMaterialNo ----- + if (xmlList[i].SelectNodes("substitutematerialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText)) + { + dr["SubstituteMaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper(); + SubstituteMaterialNo = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("substitutematerialno").Item(0).InnerText).ToString().ToUpper(); + } + else + { + // Default value + dr["SubstituteMaterialNo"] = dr["materialno"].ToString().ToUpper(); + SubstituteMaterialNo = dr["materialno"].ToString().ToUpper(); + } + + // ----- OPNo ----- + // 若有傳入作業站資訊以傳入的資訊為主 + // 若沒有傳入作業站資訊,則優先以產品BOM上定義的作業站,若產品BOM無定義,以物料屬性 PutInPlace_OPNo 中的值為主 + // 若皆無傳入則以Config中定義的作業站為主 + if (xmlList[i].SelectNodes("opno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("opno").Item(0).InnerText)) + { + string argstrInput9 = xmlList[i].SelectNodes("opno").Item(0).InnerText; + dr["OPNo"] = modWS.CInput_Singlequotation(argstrInput9); + xmlList[i].SelectNodes("opno").Item(0).InnerText = argstrInput9; + } + else + { + // 檢查產品BOM是否有定義,若無繼續往下查找對應作業站資訊 + using (var objPRD = new kcPRD.clsProduct()) + { + + DataSet dsTemp_PRD; + if (SubstituteMaterialNo == MaterialNo) + { + dsTemp_PRD = objPRD.ShowBOM(ProductNo, ProductVersion, MaterialNo); + if (dsTemp_PRD.Tables["PRDBOM"].Rows.Count > 0) + { + OPNO = dsTemp_PRD.Tables["PRDBOM"].Rows[0]["OPNO"].ToString().ToUpper(); + dsTemp_PRD = null; + } + else + { + dsTemp_PRD = null; + } + } + else + { + dsTemp_PRD = objPRD.ShowBOMMaterialGroup(ProductNo, ProductVersion, MaterialNo, MaterialNo: SubstituteMaterialNo); + if (dsTemp_PRD.Tables["MaterialGroup"].Rows.Count > 0) + { + OPNO = dsTemp_PRD.Tables["MaterialGroup"].Rows[0]["OPNO"].ToString().ToUpper(); + dsTemp_PRD = null; + } + else + { + dsTemp_PRD = null; + } + } + + } + + if (string.IsNullOrEmpty(OPNO)) + { + // 檢查物料屬性是否有定義,若繼續往下查找對應作業站資訊 + DataSet dsTemp_MTL; + using (var objMTL = new kcMTL.clsMTLBasis()) + { + dsTemp_MTL = objMTL.ShowMaterialProperty(SubstituteMaterialNo, "PutInPlace_OPNo", 2); + if (dsTemp_MTL.Tables["MaterialProperty"].Rows.Count > 0) + { + OPNO = dsTemp_MTL.Tables["MaterialProperty"].Rows[0]["DEFAULTVALUE"].ToString().ToUpper(); + dsTemp_MTL = null; + } + else + { + dsTemp_MTL = null; + } + } + + if (string.IsNullOrEmpty(OPNO)) + { + // Default value + dr["OPNo"] = ConfigurationManager.AppSettings["defMOListOPNo"]; + } + else + { + dr["OPNo"] = OPNO; + } + } + else + { + dr["OPNo"] = OPNO; + } + + } + + // 2013/02/18,Even,新增替代物料及物料使用量------- + // ----- SubstituteMaterialLevel ----- + if (xmlList[i].SelectNodes("substitutemateriallevel").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText) == true) + + { + dr["SubstituteMaterialLevel"] = Conversions.ToInteger(xmlList[i].SelectNodes("substitutemateriallevel").Item(0).InnerText); + } + else + { + // Default value,未抓取到,抓取MaterialLevel + dr["SubstituteMaterialLevel"] = MaterialLevel; + } + // ----- SubstituteStdQty -- + if (xmlList[i].SelectNodes("substitutestdqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText) == true) + + { + dr["SubstituteStdQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("substitutestdqty").Item(0).InnerText); + } + else + { + // 2018/09/20 OwenLiu, 因為後端程式會重新計算,這邊取消預設值的指定 + // 'Default value,未抓取到,抓取則抓物料之標準數 + // dr("SubstituteStdQty") = dr("StdQty") + } + + // ----- RequireQty--------若無資料則為工單數 * 標準數*(1+損耗率) + if (xmlList[i].SelectNodes("requireqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("requireqty").Item(0).InnerText) == true) + + { + dr["RequireQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("requireqty").Item(0).InnerText); + } + else + { + // 2018/09/20 OwenLiu, 因為後端程式會重新計算,這邊取消預設值的指定 + // 'Default value + // dr("RequireQty") = MOQty * dblStdQty * (1 + dr("DecreaseRate")) + } + + // ----- DeliveryMethod ----- + // 2019/09/26 Grace 新增tagname, 材料型態:DeliveryMethod (Optional參數,非必傳) + if (xmlList[i].SelectNodes("deliverymethod").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText)) + + { + string argstrInput10 = xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText; + dr["DeliveryMethod"] = modWS.CInput_Singlequotation(argstrInput10); + xmlList[i].SelectNodes("deliverymethod").Item(0).InnerText = argstrInput10; + } + + if (xmlList[i].SelectNodes("mainitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("mainitem").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("mainitem").Item(0).InnerText; + dr["MainItem"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("mainitem").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("phantomitem").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("phantomitem").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("phantomitem").Item(0).InnerText; + dr["PhantomItem"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("phantomitem").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("lockrequirement").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText; + dr["LockRequirement"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("lockrequirement").Item(0).InnerText = argstrInput13; + } + + if (xmlList[i].SelectNodes("operationseqnum").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText)) + + { + string argstrInput13 = xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText; + dr["OperationSeqnum"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("operationseqnum").Item(0).InnerText = argstrInput13; + } + + if (errorFlag == false) + { + dtMTL.Rows.Add(dr); + } + } + + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOMaterialListError%]", stack: ex.StackTrace); + } + } + } + } + } + + // MO Property + var dtMOProperty = new DataTable("MOProperty"); + dtMOProperty.Columns.Add("MONo", Type.GetType("System.String")); + dtMOProperty.Columns.Add("PropertyNo", Type.GetType("System.String")); + dtMOProperty.Columns.Add("PropertyValue", Type.GetType("System.String")); + // dtMOProperty.Columns.Add("LotSerial", System.Type.GetType("System.String")) + dtMOProperty.Columns.Add("DataType", Type.GetType("System.String")); // DataType: 0:Numeric, 1:String(default), 2:Percent, 3:DateTime, 4:Boolean + + // web.config裡預設的MOProperty (ERPUnitNo)(原本是寫在ArrayList裡,改寫在DataTable裡) + if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["defERPUnitNoProperty"])) + { + DataRow drP; + drP = dtMOProperty.NewRow(); + drP["MONo"] = MONo; + drP["PropertyNo"] = ConfigurationManager.AppSettings["defERPUnitNoProperty"]; + drP["PropertyValue"] = MOUnitNo; + drP["DataType"] = "String"; + dtMOProperty.Rows.Add(drP); + } + + + bool PropertyFlag = false; // haoqian 221025 + // ERP拋過來的屬性 + if (xmlDoc.DocumentElement.GetElementsByTagName("property").Count > 0) + { + if (xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("property").Item(0).SelectNodes("value"); + if (xmlList.Count == 0) + { + } + // clsERP.combineMessage(strMessage, , , "[%MOPropertyNotExist%]") + else + { + DataRow dr; + bool errorFlag = false; + PropertyFlag = true; // haoqian 221025 + for (int i = 0, loopTo1 = xmlList.Count - 1; i <= loopTo1; i++) + { + errorFlag = false; + try + { + dr = dtMOProperty.NewRow(); + + // ----- MONo ----- + dr["MONo"] = MONo; + + // ----- PropertyNo ----- + if (xmlList[i].SelectNodes("name").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("name").Item(0).InnerText)) + { + string argstrInput11 = xmlList[i].SelectNodes("name").Item(0).InnerText; + dr["PropertyNo"] = modWS.CInput_Singlequotation(argstrInput11); + xmlList[i].SelectNodes("name").Item(0).InnerText = argstrInput11; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MOPropertyNoEmpty%]"); + } + + // ----- PropertyValue ----- + if (xmlList[i].SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("value").Item(0).InnerText)) + { + string argstrInput12 = xmlList[i].SelectNodes("value").Item(0).InnerText; + dr["PropertyValue"] = modWS.CInput_Singlequotation(argstrInput12); + xmlList[i].SelectNodes("value").Item(0).InnerText = argstrInput12; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MOPropertyValueEmpty%]"); + } + + // ----- DataType ----- + if (xmlList[i].SelectNodes("type").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("type").Item(0).InnerText)) + { + string argstrInput13 = xmlList[i].SelectNodes("type").Item(0).InnerText; + dr["DataType"] = modWS.CInput_Singlequotation(argstrInput13); + xmlList[i].SelectNodes("type").Item(0).InnerText = argstrInput13; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MOPropertyDataTypeEmpty%]"); + } + + if (errorFlag == false) + { + dtMOProperty.Rows.Add(dr); + } + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MOPropertyError%]", stack: ex.StackTrace); + } + } + } + } + } + + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = MONo; + + // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit ----- + clsOE.editMO(MONo, MOQty, RONo, ItemNo, CustomerNo, MOTypeNo, Priority, PlanFinishDate, Creator, CreateDate, Description, dtMTL, strMessage, strException, strAlert, dtMOProperty, strERPMOLineNo, PropertyFlag, CustomerLotNo, PlanStartDate); + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: ex.StackTrace); + } + + finally + { + + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + + // 紀錄Transaction Log + clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "EditMO", Conversions.ToInteger(ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + + funEditMORet = OutXml; + + } + + return funEditMORet; + + } + #endregion + + /// + /// 匹配你调试结构的API服务入参信息类 + /// + public class API_Base_ServiceInfo + { + public string ComputerName { get; set; } + public string CurUserNo { get; set; } + public string FunctionID { get; set; } + // 你需要取的目标属性1 + public string InJson { get; set; } + public string ModuleID { get; set; } + public string OutJson { get; set; } + public string PackageName { get; set; } + public DateTime SendTime { get; set; } + public int TargetType { get; set; } + public string TransactionId { get; set; } + // 你需要取的目标属性2 + public HttpRequestHeaders httpRequest { get; set; } + public int keepJson { get; set; } + } + public static string InvokeSrv_JsonToXml(object parameters) + { + string result = ""; + string transactionid = ""; + string moduleid = ""; + string functionid = ""; + string computername = ""; + string curuserno = ""; + string curusrpwd = "";//新增用户密码 SM2加密 + string sendtime = ""; + string languagemode = ""; + string outXml = ""; + string Json = ""; + + + + string ContentType = ""; + string SourceSystem = ""; + string TargetSystem = ""; + string Authorization = ""; + + try + { + //转换为数组 + if (parameters is object[] paramArray && paramArray.Length >= 2) + { + if (paramArray[1] is API_Base.ServiceInfo serviceInfo) + { + Json = serviceInfo.InJson; + string headerText = serviceInfo.httpRequest.ToString(); + + // 解析逻辑 + var lines = headerText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + Dictionary headers = new Dictionary(); + foreach (var line in lines) + { + int index = line.IndexOf(':'); + if (index > 0) + { + string key = line.Substring(0, index).Trim(); + string value = line.Substring(index + 1).Trim(); + headers[key] = value; + } + } + // 结果 + //curuserno = headers.TryGetValue("curuserno", out var no) ? no : ""; + //curusrpwd = headers.TryGetValue("curusrpwd", out var pwd) ? pwd : ""; + + + ContentType = headers.TryGetValue("Content-Type", out var contp) ? contp : ""; + SourceSystem = headers.TryGetValue("Source-System", out var sous) ? sous : ""; + TargetSystem = headers.TryGetValue("Target-System", out var tars) ? tars : ""; + Authorization = headers.TryGetValue("Authorization", out var auth) ? auth : ""; + + curusrpwd = Authorization; + + + + + + } + } + + XmlDocument xmlDoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(Json); + + if (xmlDoc.GetElementsByTagName("transactionid").Count > 0) + transactionid = xmlDoc.GetElementsByTagName("transactionid")[0].InnerText; + if (xmlDoc.GetElementsByTagName("moduleid").Count > 0) + moduleid = xmlDoc.GetElementsByTagName("moduleid")[0].InnerText; + if (xmlDoc.GetElementsByTagName("computername").Count > 0) + computername = xmlDoc.GetElementsByTagName("computername")[0].InnerText; + if (xmlDoc.GetElementsByTagName("curuserno").Count > 0) + curuserno = xmlDoc.GetElementsByTagName("curuserno")[0].InnerText; + ////解析传入密码 + //if (xmlDoc.GetElementsByTagName("curusrpwd").Count > 0) + // curusrpwd = xmlDoc.GetElementsByTagName("curusrpwd")[0].InnerText; + + + if (xmlDoc.GetElementsByTagName("sendtime").Count > 0) + sendtime = xmlDoc.GetElementsByTagName("sendtime")[0].InnerText; + if (xmlDoc.GetElementsByTagName("languagemode").Count > 0) + languagemode = xmlDoc.GetElementsByTagName("languagemode")[0].InnerText; + + XmlNodeList temp = xmlDoc.GetElementsByTagName("functionid"); + XmlNode nFunctionId = temp.Count > 0 ? temp[0] : null; + if (nFunctionId == null) + throw new iMESException.MESException("0000-003000", "functionid Not Found"); + + if (curuserno == "") + { + throw new iMESException.MESException("0000-003000", "curuserno Not Found"); + } + + if (curusrpwd == "") + { + throw new iMESException.MESException("0000-003000", "curusrpwd Not Found"); + } + + + //if (ContentType == "") + //{ + // throw new iMESException.MESException("0000-003000", "ContentType Not Found"); + //} + + if (SourceSystem == "") + { + throw new iMESException.MESException("0000-003000", "SourceSystem Not Found"); + } + + if (TargetSystem == "") + { + throw new iMESException.MESException("0000-003000", "TargetSystem Not Found"); + } + + + functionid = nFunctionId.InnerText; + + //add by 14166 for 新增权限校验 + tcEAI_C.clsERP.funCheckUser(curuserno, curusrpwd); + + //alter by 14166 for 调整调用方式 + //仅支持标准接口客开 + + //MethodInfo mi = typeof(EAIws.wsERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance); + //System.Reflection.ConstructorInfo ctor = typeof(EAIws.wsERP).GetConstructor(Type.EmptyTypes); + + + ////调整支持新个案接口 + //MethodInfo mi = null; + //System.Reflection.ConstructorInfo ctor = null; + + //// 定义要搜索的类型顺序 + //Type[] searchTypes = { typeof(modERP), typeof(EAIws.wsERP) }; + //Type targetType = null; + + //foreach (Type type in searchTypes) + //{ + // mi = type.GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + // if (mi != null) + // { + // targetType = type; + // break; + // } + //} + + //if (targetType == null) + //{ + // throw new iMESException.MESException("0000-003000", functionid + " [%INVOKE FAIL%]!"); + //} + + + + MethodInfo mi = null; + System.Reflection.ConstructorInfo ctor = null; + + + mi = typeof(modERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + if (mi == null) + { + mi = typeof(EAIws.wsERP).GetMethod(functionid, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + if (mi == null) + { + throw new iMESException.MESException("0000-003000", functionid + " [%INVOKE FAIL%]!"); + } + else + { + ctor = typeof(EAIws.wsERP).GetConstructor(Type.EmptyTypes); + object instance = ctor.Invoke(null); + outXml = mi.Invoke(instance, new object[] { xmlDoc.OuterXml }).ToString(); + } + } + else + { + outXml = mi.Invoke(null, new object[] { xmlDoc.OuterXml }).ToString(); + } + + + XmlDocument xmlDoc2 = new XmlDocument(); + xmlDoc2.LoadXml(outXml); + result = Newtonsoft.Json.JsonConvert.SerializeObject(xmlDoc2); + } + catch (Exception ex) + { + if (ex is TargetInvocationException && ex.InnerException != null) ex = ex.InnerException; + + Dictionary resultObj = new Dictionary(); + resultObj["response"] = new Dictionary(); + Dictionary response = resultObj["response"] as Dictionary; + response["identity"] = new Dictionary(); + response["exception"] = new Dictionary(); + response["returnvalue"] = ""; + response["result"] = "fail"; + Dictionary identity = ((resultObj["response"] as Dictionary)["identity"] as Dictionary); + identity["transactionid"] = transactionid; + identity["moduleid"] = moduleid; + identity["functionid"] = functionid; + identity["computername"] = computername; + identity["curuserno"] = curuserno; + identity["sendtime"] = sendtime; + identity["languagemode"] = languagemode; + Dictionary exception = ((resultObj["response"] as Dictionary)["exception"] as Dictionary); + exception["code"] = ex is iMESException.MESException ? (ex as iMESException.MESException).ErrorCode : "0000-999999"; + exception["sysmsg"] = ex.Message; + exception["mesmsg"] = ex.Message; + exception["stack"] = ex.StackTrace; + result = Newtonsoft.Json.JsonConvert.SerializeObject(resultObj); + } + + return result; + } + + + + + + + #region-----------add by 14166 for 新增人员接口----------- + public static string CreateUesr(string InXml) + { + string funAddUserRet = default(string); + System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // 用以讀取Xml字串 + System.Xml.XmlNodeList xmlList; + + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + List strException = new List(); // Exception XML字串 + List strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + string strMode = string.Empty; // Mode + + try + { + try + { + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace); + goto exitFun; + } + + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace); + goto exitFun; + } + + string UserNo = string.Empty;//用户编号 + string UserName = string.Empty;//用户名称 + string UserLevel = string.Empty;//用户等级 + + + string Creator = "ERP";//创建人 + string CreateDate = Conversions.ToString(DateTime.Now);//创建时间 + + string Description = string.Empty;//描述 + string IssueState = string.Empty;//签核状态 + + + + string ChangeDate = Conversions.ToString(DateTime.Now);//变更时间 + string ResetPassword = string.Empty;//第一次登录是否重设密码 + + string UserType = string.Empty;//用户类别 + string UserDP = string.Empty;//用户部门 + string UserEmail = string.Empty;//电子邮箱 + + + string Password = string.Empty;//密码 + + //DateTime InputDate = DateTime.Now; // Default Today + + // UserNo 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("userno").Count > 0 && xmlDoc.GetElementsByTagName("userno").Item(0).SelectNodes("value").Count > 0) + UserNo = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userno").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserNo == string.Empty) + clsERP.combineException(ref strException, null, null, "[%UserNoEmpty%%]"); + + // UserName 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("username").Count > 0 && xmlDoc.GetElementsByTagName("username").Item(0).SelectNodes("value").Count > 0) + UserName = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("username").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserName == string.Empty) + clsERP.combineException(ref strException, null, null, "[%UserNameEmpty%%]"); + + // UserLevel 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Count > 0 && xmlDoc.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Count > 0) + UserLevel = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserLevel == string.Empty) + clsERP.combineException(ref strException, null, null, "[%UserLevelEmpty%%]"); + + + + // Password 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("password").Count > 0 && xmlDoc.GetElementsByTagName("password").Item(0).SelectNodes("value").Count > 0) + Password = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("password").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserLevel == string.Empty) + clsERP.combineException(ref strException, null, null, "[%PasswordEmpty%%]"); + + + + // Creator 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0) + Creator = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText); + + // CreateDate 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0) + CreateDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // Description 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0) + Description = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText); + + // IssueState 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Count > 0 && xmlDoc.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Count > 0) + IssueState = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Item(0).InnerText); + + // ChangeDate 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("changedate").Count > 0 && xmlDoc.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Count > 0) + ChangeDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Item(0).InnerText); + + // ResetPassword 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Count > 0 && xmlDoc.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Count > 0) + ResetPassword = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Item(0).InnerText); + + // UserType 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("usertype").Count > 0 && xmlDoc.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Count > 0) + UserType = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Item(0).InnerText); + + + + // UserEmail 邮件非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Count > 0 && xmlDoc.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Count > 0) + UserEmail = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Item(0).InnerText); + + // UserDP 部门非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Count > 0 && xmlDoc.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Count > 0) + UserDP = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Item(0).InnerText); + + + + + + // 檢查必要性欄位 + if (strException.Count > 0) + goto exitFun; + //string UserNo = string.Empty;//用户编号 + //string UserName = string.Empty;//用户名称 + //string UserLevel = string.Empty;//用户等级 + + + //string Creator = "ERP";//创建人 + //string CreateDate = Conversions.ToString(DateTime.Now);//创建时间 + + //string Description = string.Empty;//描述 + //string IssueState = string.Empty;//签核状态 + + + + //string ChangeDate = string.Empty;//变更时间 + //string ResetPassword = string.Empty;//第一次登录是否重设密码 + + //string UserType = string.Empty;//用户类别 + //string UserDP = string.Empty;//用户部门 + //string UserEmail = string.Empty;//电子邮箱 + // KeyValue + strKeyValue = UserNo; + + clsERP.funAddUser(ref strMessage, ref strException, UserNo, UserName, UserLevel, Creator, CreateDate, Description, IssueState, ChangeDate, ResetPassword, UserType, UserDP, UserEmail, Password); + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%AddUserFail%]", ex.StackTrace); + } + finally + { + + // 將各部份之XML字串組起來並傳出 + OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage); + + // 紀錄Transaction Log + clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddUser(" + strMode + ")", Conversions.ToInteger(1), Conversions.ToInteger(1), LogClass: "ERP"); + + funAddUserRet = OutXml; + } + + return funAddUserRet; + } + + public static string DelUesr(string InXml) + { + string funAddUserRet = default(string); + System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // 用以讀取Xml字串 + System.Xml.XmlNodeList xmlList; + + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + List strException = new List(); // Exception XML字串 + List strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + string strMode = string.Empty; // Mode + + try + { + try + { + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%InXmlError%]", ex.StackTrace); + goto exitFun; + } + + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%IndentityError%]", ex.StackTrace); + goto exitFun; + } + + string UserNo = string.Empty;//用户编号 + string UserName = string.Empty;//用户名称 + string UserLevel = string.Empty;//用户等级 + + + string Creator = "ERP";//创建人 + string CreateDate = Conversions.ToString(DateTime.Now);//创建时间 + + string Description = string.Empty;//描述 + string IssueState = string.Empty;//签核状态 + + + + string ChangeDate = Conversions.ToString(DateTime.Now);//变更时间 + string ResetPassword = string.Empty;//第一次登录是否重设密码 + + string UserType = string.Empty;//用户类别 + string UserDP = string.Empty;//用户部门 + string UserEmail = string.Empty;//电子邮箱 + + + string Password = string.Empty;//密码 + + //DateTime InputDate = DateTime.Now; // Default Today + + // UserNo 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("userno").Count > 0 && xmlDoc.GetElementsByTagName("userno").Item(0).SelectNodes("value").Count > 0) + UserNo = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userno").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserNo == string.Empty) + clsERP.combineException(ref strException, null, null, "[%UserNoEmpty%%]"); + + // UserName 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("username").Count > 0 && xmlDoc.GetElementsByTagName("username").Item(0).SelectNodes("value").Count > 0) + UserName = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("username").Item(0).SelectNodes("value").Item(0).InnerText); + + //if (UserName == string.Empty) + // clsERP.combineException(ref strException, null, null, "[%UserNameEmpty%%]"); + + // UserLevel 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Count > 0 && xmlDoc.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Count > 0) + UserLevel = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("userlevel").Item(0).SelectNodes("value").Item(0).InnerText); + + //if (UserLevel == string.Empty) + // clsERP.combineException(ref strException, null, null, "[%UserLevelEmpty%%]"); + + + + // Password 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("password").Count > 0 && xmlDoc.GetElementsByTagName("password").Item(0).SelectNodes("value").Count > 0) + Password = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("password").Item(0).SelectNodes("value").Item(0).InnerText); + + if (UserLevel == string.Empty) + clsERP.combineException(ref strException, null, null, "[%PasswordEmpty%%]"); + + + + // Creator 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0) + Creator = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText); + + // CreateDate 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0) + CreateDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText); + + // Description 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0) + Description = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText); + + // IssueState 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Count > 0 && xmlDoc.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Count > 0) + IssueState = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("issuestate").Item(0).SelectNodes("value").Item(0).InnerText); + + // ChangeDate 必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("changedate").Count > 0 && xmlDoc.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Count > 0) + ChangeDate = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("changedate").Item(0).SelectNodes("value").Item(0).InnerText); + + // ResetPassword 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Count > 0 && xmlDoc.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Count > 0) + ResetPassword = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("resetpassword").Item(0).SelectNodes("value").Item(0).InnerText); + + // UserType 非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("usertype").Count > 0 && xmlDoc.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Count > 0) + UserType = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("usertype").Item(0).SelectNodes("value").Item(0).InnerText); + + + + // UserEmail 邮件非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Count > 0 && xmlDoc.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Count > 0) + UserEmail = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("emailaddress").Item(0).SelectNodes("value").Item(0).InnerText); + + // UserDP 部门非必要輸入 + if (xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Count > 0 && xmlDoc.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Count > 0) + UserDP = modWS.CInput_Singlequotation(xmlDoc.DocumentElement.GetElementsByTagName("departmentno").Item(0).SelectNodes("value").Item(0).InnerText); + + + + + + // 檢查必要性欄位 + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = UserNo; + + clsERP.funDelUser(ref strMessage, ref strException, UserNo, UserName, UserLevel, Creator, CreateDate, Description, IssueState, ChangeDate, ResetPassword, UserType, UserDP, UserEmail, Password); + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, null, ex.Message, "[%DelUserFail%]", ex.StackTrace); + } + finally + { + + // 將各部份之XML字串組起來並傳出 + OutXml = modWS.CombineXMLResponse(strIdentity, null, strException, strResult, strMessage); + + // 紀錄Transaction Log + clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddUser(" + strMode + ")", Conversions.ToInteger(1), Conversions.ToInteger(1), LogClass: "ERP"); + + funAddUserRet = OutXml; + } + + return funAddUserRet; + } + #endregion + + + #region --- 辅料调拨接口 --- + public static string AddMaterial_WIP(string InXml) + { + string funAddMaterial_WIP = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + var strAlert = new List(); + + int Status = 0;//status:0为发料,1为退料 + + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + // ----- Material In List ----- + var dtMTL = new DataTable("MaterialTransferList"); + dtMTL.Columns.Add("Vendorno", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialNo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialLotNo", Type.GetType("System.String")); + dtMTL.Columns.Add("MaterialUnitNo", Type.GetType("System.String")); + dtMTL.Columns.Add("TransferQty", Type.GetType("System.Decimal")); + dtMTL.Columns.Add("FromInventoryNo", Type.GetType("System.String")); + dtMTL.Columns.Add("FromLocatorNo", Type.GetType("System.String")); + dtMTL.Columns.Add("ToInventoryNo", Type.GetType("System.String")); + dtMTL.Columns.Add("ToLocatorNo", Type.GetType("System.String")); + + if (xmlDoc.GetElementsByTagName("materialtransferlist").Count > 0) + { + if (xmlDoc.GetElementsByTagName("materialtransferlist").Item(0).SelectNodes("value").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("materialtransferlist").Item(0).SelectNodes("value"); + if (xmlList.Count == 0) + { + clsERP.combineException(ref strException, mesmsg: "[%MaterialListNotExist%]"); + + } + else + { + DataRow dr; + bool errorFlag = false; + for (int i = 0, loopTo = xmlList.Count - 1; i <= loopTo; i++) + { + errorFlag = false; + + try + { + dr = dtMTL.NewRow(); + + + // ----- Vendorno ----- + if (xmlList[i].SelectNodes("vendorno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("vendorno").Item(0).InnerText)) + + { + dr["Vendorno"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("vendorno").Item(0).InnerText).ToString(); + } + + // ----- MaterialNo ----- + if (xmlList[i].SelectNodes("materialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialno").Item(0).InnerText)) + { + dr["MaterialNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materialno").Item(0).InnerText).ToString().ToUpper(); + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialNoEmpty%]"); + } + + // ----- MaterialLotNo ----- + if (xmlList[i].SelectNodes("materiallotno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materiallotno").Item(0).InnerText)) + + { + dr["MaterialLotNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("materiallotno").Item(0).InnerText).ToString(); + } + + + // ----- MaterialUnitNo ----- + if (xmlList[i].SelectNodes("materialunitno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("materialunitno").Item(0).InnerText)) + { + string argstrInput = xmlList[i].SelectNodes("materialunitno").Item(0).InnerText; + dr["MaterialUnitNo"] = modWS.CInput_Singlequotation(argstrInput); + xmlList[i].SelectNodes("materialunitno").Item(0).InnerText = argstrInput; + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%MaterialUnitNoEmpty%]"); + } + + // ----- TransferQty ----- + if (xmlList[i].SelectNodes("transferqty").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("transferqty").Item(0).InnerText) && Information.IsNumeric(xmlList[i].SelectNodes("transferqty").Item(0).InnerText) == true) + + { + dr["TransferQty"] = Convert.ToDecimal(xmlList[i].SelectNodes("transferqty").Item(0).InnerText); + //if (Mode == 2 || Mode == 4) + //{ + // // 還原發料或還原退料時將Qty改為負 + // dr["Qty"] = -Convert.ToDecimal(dr["Qty"]); + //} + } + else + { + errorFlag = true; + clsERP.combineException(ref strException, mesmsg: "[%TransferQtyEmtpy%]"); + } + + // ----- FromInventoryNo ----- + if (xmlList[i].SelectNodes("frominventoryno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("frominventoryno").Item(0).InnerText)) + + { + dr["FromInventoryNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("frominventoryno").Item(0).InnerText).ToString(); + } + + // ----- FromLocatorNo ----- + dr["FromLocatorNo"] = "N/A"; + + // ----- ToInventoryNo ----- + if (xmlList[i].SelectNodes("toinventoryno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("toinventoryno").Item(0).InnerText)) + + { + dr["ToInventoryNo"] = modWS.CInput_Singlequotation(xmlList[i].SelectNodes("toinventoryno").Item(0).InnerText).ToString(); + } + + // ----- ToLocatorNo ----- + dr["ToLocatorNo"] = "N/A"; + + if (errorFlag == false) + { + dtMTL.Rows.Add(dr); + } + } + catch (Exception ex) + { + switch (Status) + { + case 0: + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MaterialTransferListFail%]", stack: ex.StackTrace); // 发料错误 + break; + } + case 1: + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%MaterialTransferListFail%]", stack: ex.StackTrace); // 退料错误 + break; + } + } + + } + + } + + } + } + + + } + + + string SubInventoryTransferNo = string.Empty; + string Description = string.Empty; + string Creator = string.Empty; + var Createdate = DateTime.Now; + + // SubInventoryTransferNo + if (xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Count > 0 && xmlDoc.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText)) + { + string argstrInput = xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText; + SubInventoryTransferNo = modWS.CInput_Singlequotation(argstrInput); + xmlDoc.DocumentElement.GetElementsByTagName("subinventorytransferno").Item(0).SelectNodes("value").Item(0).InnerText = argstrInput; + } + + // Description + if (xmlDoc.DocumentElement.GetElementsByTagName("description").Count > 0 && xmlDoc.GetElementsByTagName("description").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Description = xmlDoc.DocumentElement.GetElementsByTagName("description").Item(0).SelectNodes("value").Item(0).InnerText; + } + + // Creator + if (xmlDoc.DocumentElement.GetElementsByTagName("creator").Count > 0 && xmlDoc.GetElementsByTagName("creator").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Creator = xmlDoc.DocumentElement.GetElementsByTagName("creator").Item(0).SelectNodes("value").Item(0).InnerText; + } + + // ToDateTime + if (xmlDoc.DocumentElement.GetElementsByTagName("createdate").Count > 0 && xmlDoc.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Createdate = Convert.ToDateTime(xmlDoc.DocumentElement.GetElementsByTagName("createdate").Item(0).SelectNodes("value").Item(0).InnerText); + } + + // Status + if (xmlDoc.DocumentElement.GetElementsByTagName("status").Count > 0 && xmlDoc.GetElementsByTagName("status").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("status").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Status = Convert.ToInt32(xmlDoc.DocumentElement.GetElementsByTagName("status").Item(0).SelectNodes("value").Item(0).InnerText); + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(SubInventoryTransferNo)) + clsERP.combineException(ref strException, mesmsg: "[%SubInventoryTransferNoEmpty%]"); + if (string.IsNullOrEmpty(Status.ToString())) + clsERP.combineException(ref strException, mesmsg: "[%StatusEmpty%]"); + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = SubInventoryTransferNo; + + // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit ----- + tcEAI_C.clsERP.funAddMaterial_WIP(SubInventoryTransferNo, Description, Creator, Status, Createdate, dtMTL, strMessage, strException, strAlert); + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace); + } + finally + { + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + funAddMaterial_WIP = OutXml; + + } + + return funAddMaterial_WIP; + + } + #endregion + + #region 更新MES箱状态接口 + public static string UpdateMESCarrier(string InXml) + { + string UpdateMESCarrier = default(string); + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + string dbCode = ""; + string execType = ""; + string Type = ""; + string Barcode = ""; + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Count > 0 && xmlDoc.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Item(0).InnerText)) + { + dbCode = xmlDoc.DocumentElement.GetElementsByTagName("dbcode").Item(0).SelectNodes("value").Item(0).InnerText; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("exectype").Count > 0 && xmlDoc.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Item(0).InnerText)) + { + execType = xmlDoc.DocumentElement.GetElementsByTagName("exectype").Item(0).SelectNodes("value").Item(0).InnerText; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("type").Count > 0 && xmlDoc.GetElementsByTagName("type").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("type").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Type = xmlDoc.DocumentElement.GetElementsByTagName("type").Item(0).SelectNodes("value").Item(0).InnerText; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("barcode").Count > 0 && xmlDoc.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Barcode = xmlDoc.DocumentElement.GetElementsByTagName("barcode").Item(0).SelectNodes("value").Item(0).InnerText; + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(dbCode)) + clsERP.combineException(ref strException, mesmsg: "[%dbCodeEmpty%]"); + if (string.IsNullOrEmpty(execType)) + clsERP.combineException(ref strException, mesmsg: "[%execTypeEmpty%]"); + if (string.IsNullOrEmpty(Type)) + clsERP.combineException(ref strException, mesmsg: "[%TypeEmpty%]"); + if (string.IsNullOrEmpty(Barcode)) + clsERP.combineException(ref strException, mesmsg: "[%BarcodeEmpty%]"); + if (strException.Count > 0) + goto exitFun; + + // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit ----- + + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace); + } + finally + { + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + UpdateMESCarrier = OutXml; + + } + + return UpdateMESCarrier; + } + #endregion + + #region 湿敏接口 + public static string UpdateMaterialSM(string InXml) + { + string UpdateMaterialSM = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + DataRow drData; + string Factory = ""; + DataTable dtData = new DataTable(); + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && xmlDoc.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText; + } + + dtData.Columns.Add("REELID", Type.GetType("System.String")); + dtData.Columns.Add("STATUS", Type.GetType("System.String")); + dtData.Columns.Add("OPENDATETIME", Type.GetType("System.DateTime")); + dtData.Columns.Add("CLOSEDATETIME", Type.GetType("System.DateTime")); + dtData.Columns.Add("OPENUSER", Type.GetType("System.String")); + dtData.Columns.Add("CLOSEUSER", Type.GetType("System.String")); + dtData.Columns.Add("INTERVALTIME", Type.GetType("System.String")); + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0) + { + if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("msdinfo").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("msdinfo"); + var loopTo = xmlList.Count - 1; + for (int i = 0; i <= loopTo; i++) + { + if (xmlList[i].SelectNodes("REELID").Count == 0 | xmlList[i].SelectNodes("STATUS").Count == 0 | xmlList[i].SelectNodes("OPENDATETIME").Count == 0 | xmlList[i].SelectNodes("CLOSEDATETIME").Count == 0 | xmlList[i].SelectNodes("OPENUSER").Count == 0 | xmlList[i].SelectNodes("CLOSEUSER").Count == 0 | xmlList[i].SelectNodes("INTERVALTIME").Count == 0) + { + throw new iMESException.MESException("0000-200001", "REELID,STATUS,OPENDATETIME,CLOSEDATETIME,OPENUSER,CLOSEUSER,INTERVALTIME can not empty!"); + } + drData = dtData.NewRow(); + drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText; + drData["STATUS"] = xmlList[i].SelectNodes("STATUS").Item(0).InnerText; + drData["OPENDATETIME"] = Convert.ToDateTime(xmlList[i].SelectNodes("OPENDATETIME").Item(0).InnerText); + drData["CLOSEDATETIME"] = Convert.ToDateTime(xmlList[i].SelectNodes("CLOSEDATETIME").Item(0).InnerText); + drData["OPENUSER"] = xmlList[i].SelectNodes("OPENUSER").Item(0).InnerText; + drData["CLOSEUSER"] = xmlList[i].SelectNodes("CLOSEUSER").Item(0).InnerText; + drData["INTERVALTIME"] = xmlList[i].SelectNodes("INTERVALTIME").Item(0).InnerText; + dtData.Rows.Add(drData); + } + } + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(Factory)) + clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]"); + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = Factory; + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace); + } + finally + { + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + UpdateMaterialSM = OutXml; + + } + + return UpdateMaterialSM; + } + #endregion + + #region MES退料接口 + public static string funMaterialReturn(string InXml) + { + string funMaterialReturn = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + DataRow drData; + string Factory = ""; + DataTable dtData = new DataTable(); + DataTable dtDataTemp = new DataTable(); + string mocode = ""; + string mvdcode = ""; + string fromstorage = ""; + string tostorage = ""; + string usercode = ""; + string mdate = ""; + string mtime = ""; + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + + + if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && xmlDoc.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText)) + { + Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).SelectNodes("value").Item(0).InnerText; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Item(0).InnerText)) + { + mocode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mocode").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mvdcode").Item(0).InnerText)) + { + mvdcode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mvdcode").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("fromstorage").Item(0).InnerText)) + { + fromstorage = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("fromstorage").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("tostorage").Item(0).InnerText)) + { + tostorage = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("tostorage").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("usercode").Item(0).InnerText)) + { + usercode = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("usercode").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mdate").Item(0).InnerText)) + { + mdate = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mdate").Item(0).InnerText; + } + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0 && xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mcode").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mtime").Item(0).InnerText)) + { + mtime = xmlDoc.DocumentElement.GetElementsByTagName("Detail").Item(0).SelectNodes("mtime").Item(0).InnerText; + } + + dtData.Columns.Add("MCODE", Type.GetType("System.String")); + dtData.Columns.Add("QTY", Type.GetType("System.String")); + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0) + { + if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mlist").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("mlist"); + var loopTo = xmlList.Count - 1; + for (int i = 0; i <= loopTo; i++) + { + if (xmlList[i].SelectNodes("MCODE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0) + { + throw new iMESException.MESException("0000-200001", "MCODE,QTY can not empty!"); + } + drData = dtData.NewRow(); + drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText; + drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText; + dtData.Rows.Add(drData); + } + } + } + + dtDataTemp.Columns.Add("REELID", Type.GetType("System.String")); + dtDataTemp.Columns.Add("MCODE", Type.GetType("System.String")); + dtDataTemp.Columns.Add("QTY", Type.GetType("System.String")); + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0) + { + if (xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("reelinfo").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("Detail").Item(0).SelectNodes("reelinfo"); + var loopTo = xmlList.Count - 1; + for (int i = 0; i <= loopTo; i++) + { + if (xmlList[i].SelectNodes("MCODE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0 | xmlList[i].SelectNodes("REELID").Count == 0) + { + throw new iMESException.MESException("0000-200001", "REELID,MCODE,QTY can not empty!"); + } + drData = dtDataTemp.NewRow(); + drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText; + drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText; + drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText; + dtDataTemp.Rows.Add(drData); + } + } + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(Factory)) + clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]"); + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = Factory; + + // '呼叫Dll執行 ----- UnitNo=UnitType=SystemUnit ----- + + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: ex.StackTrace); + } + finally + { + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + funMaterialReturn = OutXml; + + } + + return funMaterialReturn; + } + #endregion + + //#region Reel校验接口 + ////public static string CheckReelQty(string jsonInput) + ////{ + //// JObject response = new JObject(); + //// try + //// { + //// JObject requestJson = JObject.Parse(jsonInput); + //// string factory = (string)requestJson["Data"]?["Factory"]; + //// string reelId = (string)requestJson["Data"]?["Detail"]?["REELID"]; + //// string qty = (string)requestJson["Data"]?["Detail"]?["QTY"]; + //// bool isSuccess = true; + + //// if (isSuccess) + //// { + //// response["result"] = 1; + //// response["qty"] = qty; + //// response["mcode"] = "111"; + //// response["vendorcode"] = "123456"; + //// response["vendordate"] = "20240512"; + //// response["manufacturer"] = "龙旗"; + //// response["vendorlotno"] = "123"; + //// response["oraFacReel"] = "12"; + //// response["snscale"] = "09"; + //// response["mpn"] = ""; + //// response["produceArea"] = ""; + //// response["cnum"] = 0; + //// response["msg"] = null; + //// } + //// else + //// { + //// response["result"] = 0; + //// response["msg"] = $"未找到该料卷{reelId}"; + //// response["qty"] = ""; + //// } + //// } + //// catch (Exception ex) + //// { + //// response["result"] = 0; + //// response["msg"] = "解析异常或系统错误: " + ex.Message; + //// response["qty"] = ""; + + //// // 此处可以加上你原来的记录 Log 的代码 + //// } + + //// return response.ToString(Newtonsoft.Json.Formatting.None ); + ////} + + //public static string CheckReelQty(object input) + //{ + // JObject response = new JObject(); + // string Json = ""; + // var strException = new List(); // Exception XML字串 + // var strMessage = new List(); // Message XML字串 + // try + // { + // if (input is object[] paramArray && paramArray.Length >= 2) + // { + // if (paramArray[1] is API_Base.ServiceInfo serviceInfo) + // { + // Json = serviceInfo.InJson; + // //JObject requestJson = JObject.FromObject(input); + // JObject requestJson = JObject.Parse(Json); + // string factory = requestJson["Data"]?["Factory"]?.ToString(); + // string reelId = requestJson["Data"]?["Detail"]?["REELID"]?.ToString(); + // string qty = requestJson["Data"]?["Detail"]?["QTY"]?.ToString(); + // string STORAGECODE = requestJson["Data"]?["Detail"]?["STORAGECODE"]?.ToString(); + + // // 逻辑判断(这里保持你原有的逻辑) + // //clsERP.CheckReelQty() + // bool isSuccess = true; + // string mcode = ""; + // string qty1 = ""; + // isSuccess = clsERP.CheckReelQty(ref strException, ref strMessage, reelId,ref mcode,ref qty1); + // if (isSuccess) + // { + // response["result"] = 1; + // response["qty"] = qty1; + // response["mcode"] = mcode; + // response["vendorcode"] = "123456"; + // response["vendordate"] = DateTime.Now.ToString("yyyy-MM-dd"); + // response["manufacturer"] = "龙旗"; + // response["vendorlotno"] = "123"; + // response["oraFacReel"] = reelId; + // response["snscale"] = "09"; + // response["mpn"] = ""; + // response["produceArea"] = ""; + // response["cnum"] = 0; + // response["msg"] = null; + // } + // else + // { + // response["result"] = 0; + // response["msg"] = $"未找到该料卷{reelId}"; + // response["qty"] = ""; + // } + // } + // } + // } + // catch (Exception ex) + // { + // response["result"] = 0; + // response["msg"] = "数据解析异常或系统错误: " + ex.Message; + // response["qty"] = ""; + // // Log.Error(ex); + // } + + // return response.ToString(Newtonsoft.Json.Formatting.None); + //} + //#endregion + + + + #region 电子料仓发料明细数据回传(按销售订单回传) + public static string SendMaterial_RAW(string InXml) + { + string SendMaterial_RAWs = default(string); + + var xmlDoc = new XmlDocument(); // 用以讀取Xml字串 + XmlNodeList xmlList; + string OutXml = null; + + string strIdentity = string.Empty; // Identity XML字串 + string strResult = "fail"; // Result XML字串 + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strKeyValue = string.Empty; // TransactionLot KeyValue + DataRow drData; + string Factory = ""; + DataTable dtData = new DataTable(); + try + { + + try + { + // 讀取InXml字串 + xmlDoc.LoadXml(InXml); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%InXmlError%]", stack: ex.StackTrace); + goto exitFun; + } + + // 組Identity字串 + try + { + strIdentity = modWS.CombineXMLIdentity(xmlDoc); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%IndentityError%]", stack: ex.StackTrace); + goto exitFun; + } + + if (xmlDoc.DocumentElement.GetElementsByTagName("Factory").Count > 0 && !string.IsNullOrEmpty(xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).InnerText)) + { + Factory = xmlDoc.DocumentElement.GetElementsByTagName("Factory").Item(0).InnerText; + } + + dtData.Columns.Add("RECEIPTNO", Type.GetType("System.String")); + dtData.Columns.Add("RECEIPTLINE", Type.GetType("System.String")); + dtData.Columns.Add("STORAGECODE", Type.GetType("System.String")); + dtData.Columns.Add("MCODE", Type.GetType("System.String")); + dtData.Columns.Add("MNAME", Type.GetType("System.String")); + dtData.Columns.Add("REELID", Type.GetType("System.String")); + dtData.Columns.Add("DATECODE", Type.GetType("System.String")); + + dtData.Columns.Add("SNSCALE", Type.GetType("System.String")); + dtData.Columns.Add("VENDERDATE", Type.GetType("System.String")); + dtData.Columns.Add("VENDORCODE", Type.GetType("System.String")); + dtData.Columns.Add("VENDORITEMCODE", Type.GetType("System.String")); + dtData.Columns.Add("VENDERLOTNO", Type.GetType("System.String")); + dtData.Columns.Add("MANUFACTURER", Type.GetType("System.String")); + dtData.Columns.Add("EXDATE", Type.GetType("System.String")); + dtData.Columns.Add("QTY", Type.GetType("System.String")); + dtData.Columns.Add("USERCODE", Type.GetType("System.String")); + + dtData.Columns.Add("MDATE", Type.GetType("System.String")); + dtData.Columns.Add("MTIME", Type.GetType("System.String")); + + + if (xmlDoc.DocumentElement.GetElementsByTagName("Detail").Count > 0) + { + xmlList = xmlDoc.GetElementsByTagName("Detail"); + var loopTo = xmlList.Count - 1; + for (int i = 0; i <= loopTo; i++) + { + if (xmlList[i].SelectNodes("RECEIPTNO").Count == 0 | xmlList[i].SelectNodes("RECEIPTLINE").Count == 0 | xmlList[i].SelectNodes("STORAGECODE").Count == 0 | xmlList[i].SelectNodes("REELID").Count == 0 | xmlList[i].SelectNodes("DATECODE").Count == 0 | xmlList[i].SelectNodes("VENDERDATE").Count == 0 | xmlList[i].SelectNodes("VENDERLOTNO").Count == 0 | + xmlList[i].SelectNodes("MANUFACTURER").Count == 0 | xmlList[i].SelectNodes("EXDATE").Count == 0 | xmlList[i].SelectNodes("QTY").Count == 0 | xmlList[i].SelectNodes("USERCODE").Count == 0 | xmlList[i].SelectNodes("MDATE").Count == 0 | xmlList[i].SelectNodes("MTIME").Count == 0) + { + throw new iMESException.MESException("0000-200001", "RECEIPTNO,RECEIPTLINE,STORAGECODE,REELID,VENDERDATE,VENDERLOTNO,MANUFACTURER,EXDATE,QTY,USERCODE,MDATE,MTIME,can not empty!"); + } + drData = dtData.NewRow(); + + drData["RECEIPTNO"] = xmlList[i].SelectNodes("RECEIPTNO").Item(0).InnerText; + drData["RECEIPTLINE"] = xmlList[i].SelectNodes("RECEIPTLINE").Item(0).InnerText; + drData["STORAGECODE"] = xmlList[i].SelectNodes("STORAGECODE").Item(0).InnerText; + drData["MCODE"] = xmlList[i].SelectNodes("MCODE").Item(0).InnerText; + drData["MNAME"] = xmlList[i].SelectNodes("MNAME").Item(0).InnerText; + drData["REELID"] = xmlList[i].SelectNodes("REELID").Item(0).InnerText; + drData["DATECODE"] = xmlList[i].SelectNodes("DATECODE").Item(0).InnerText; + drData["SNSCALE"] = xmlList[i].SelectNodes("SNSCALE").Item(0).InnerText; + drData["VENDERDATE"] = xmlList[i].SelectNodes("VENDERDATE").Item(0).InnerText; + drData["VENDORCODE"] = xmlList[i].SelectNodes("VENDORCODE").Item(0).InnerText; + drData["VENDORITEMCODE"] = xmlList[i].SelectNodes("VENDORITEMCODE").Item(0).InnerText; + drData["VENDERLOTNO"] = xmlList[i].SelectNodes("VENDERLOTNO").Item(0).InnerText; + drData["MANUFACTURER"] = xmlList[i].SelectNodes("MANUFACTURER").Item(0).InnerText; + drData["EXDATE"] = xmlList[i].SelectNodes("EXDATE").Item(0).InnerText; + + drData["QTY"] = xmlList[i].SelectNodes("QTY").Item(0).InnerText; + drData["USERCODE"] = xmlList[i].SelectNodes("USERCODE").Item(0).InnerText; + drData["MDATE"] = xmlList[i].SelectNodes("MDATE").Item(0).InnerText; + drData["MTIME"] = xmlList[i].SelectNodes("MTIME").Item(0).InnerText; + + dtData.Rows.Add(drData); + } + } + + // 檢查必要性欄位 + if (string.IsNullOrEmpty(Factory)) + clsERP.combineException(ref strException, mesmsg: "[%FactoryEmpty%]"); + if (strException.Count > 0) + goto exitFun; + + // KeyValue + strKeyValue = Factory; + + // 判斷成功與否 + if (strException.Count > 0) + goto exitFun; + + strResult = "success"; + + exitFun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%SendMaterial_RAWFail%]", stack: ex.StackTrace); + } + finally + { + // 將各部份之XML字串組起來並傳出 + string argReturnValue = null; + OutXml = modWS.CombineXMLResponse(strIdentity, argReturnValue, strException, strResult, strMessage); + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(modWS.GetXMLIdentityNode(xmlDoc, "transactionid"), modWS.GetXMLIdentityNode(xmlDoc, "moduleid"), modWS.GetXMLIdentityNode(xmlDoc, "functionid"), modWS.GetXMLIdentityNode(xmlDoc, "computername"), modWS.GetXMLIdentityNode(xmlDoc, "curuserno"), modWS.GetXMLIdentityNode(xmlDoc, "sendtime"), strResult, strKeyValue, strMessage, strException, InXml, OutXml, "AddMaterial_WIP", Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), LogClass: "ERP"); + SendMaterial_RAWs = OutXml; + + } + + return SendMaterial_RAWs; + } + #endregion + + + #region "WMS发料回传前,先回传发料明细关联reel信息,datahub调用MES服务,推送发料明细数据至MES;" + + /// + /// 校验JOSN权限,并解析出JOSN,目前账号只支持DS + /// + /// + public static string funCheckJson(object parameters) + { + string result = ""; + string transactionid = ""; + string moduleid = ""; + string functionid = ""; + string computername = ""; + string curuserno = "DS"; + string curusrpwd = "";//新增用户密码 SM2加密 + string sendtime = ""; + string languagemode = ""; + string outXml = ""; + string Json = ""; + + + + string ContentType = ""; + string SourceSystem = ""; + string TargetSystem = ""; + string Authorization = ""; + try + { + //转换为数组 + if (parameters is object[] paramArray && paramArray.Length >= 2) + { + if (paramArray[1] is API_Base.ServiceInfo serviceInfo) + { + Json = serviceInfo.InJson; + string headerText = serviceInfo.httpRequest.ToString(); + + // 解析逻辑 + var lines = headerText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + Dictionary headers = new Dictionary(); + foreach (var line in lines) + { + int index = line.IndexOf(':'); + if (index > 0) + { + string key = line.Substring(0, index).Trim(); + string value = line.Substring(index + 1).Trim(); + headers[key] = value; + } + } + // 结果 + //curuserno = headers.TryGetValue("curuserno", out var no) ? no : ""; + //curusrpwd = headers.TryGetValue("curusrpwd", out var pwd) ? pwd : ""; + + + ContentType = headers.TryGetValue("Content-Type", out var contp) ? contp : ""; + SourceSystem = headers.TryGetValue("Source-System", out var sous) ? sous : ""; + TargetSystem = headers.TryGetValue("Target-System", out var tars) ? tars : ""; + Authorization = headers.TryGetValue("Authorization", out var auth) ? auth : ""; + + curusrpwd = Authorization; + + + + + + } + } + + tcEAI_C.clsERP.funCheckUser(curuserno, curusrpwd); + + } + catch (Exception ex) + { + throw ex; + } + return Json; + } + + public static string funReceiveReelMaterialByWMS(object parameters) + { + string funSendReelMaterialByWMS = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + // 定义最终要组装的DataTable + DataTable dtReel = new DataTable(); + + // 先给DataTable创建所有列 + dtReel.Columns.Add("Factory", typeof(string)); + dtReel.Columns.Add("RECEIPTNO", typeof(string)); + dtReel.Columns.Add("RECEIPTLINE", typeof(int)); + dtReel.Columns.Add("STORAGECODE", typeof(string)); + dtReel.Columns.Add("MCODE", typeof(string)); + dtReel.Columns.Add("MNAME", typeof(string)); + dtReel.Columns.Add("REELID", typeof(string)); + dtReel.Columns.Add("DATECODE", typeof(string)); + dtReel.Columns.Add("SNSCALE", typeof(string)); + dtReel.Columns.Add("VENDERDATE", typeof(string)); + dtReel.Columns.Add("VENDORCODE", typeof(string)); + dtReel.Columns.Add("VENDORITEMCODE", typeof(string)); + dtReel.Columns.Add("VENDERLOTNO", typeof(string)); + dtReel.Columns.Add("MANUFACTURER", typeof(string)); + dtReel.Columns.Add("EXDATE", typeof(string)); + dtReel.Columns.Add("QTY", typeof(int)); + dtReel.Columns.Add("USERCODE", typeof(string)); + dtReel.Columns.Add("MDATE", typeof(string)); + dtReel.Columns.Add("MTIME", typeof(string)); + + //2.收集数据 + string factory = result.Data?.Factory ?? ""; + + // 遍历明细填充DataTable + if (result.Data.Detail != null && result.Data.Detail.Count > 0) + { + foreach (var item in result.Data.Detail) + { + // 新建一行 + DataRow dr = dtReel.NewRow(); + + // 赋值所有字段 + dr["Factory"] = factory; + dr["RECEIPTNO"] = item.RECEIPTNO ?? ""; + dr["RECEIPTLINE"] = item.RECEIPTLINE; + dr["STORAGECODE"] = item.STORAGECODE ?? ""; + dr["MCODE"] = item.MCODE ?? ""; + dr["MNAME"] = item.MNAME ?? ""; + dr["REELID"] = item.REELID ?? ""; + dr["DATECODE"] = item.DATECODE ?? ""; + dr["SNSCALE"] = item.SNSCALE ?? ""; + dr["VENDERDATE"] = item.VENDERDATE ?? ""; + dr["VENDORCODE"] = item.VENDORCODE ?? ""; + dr["VENDORITEMCODE"] = item.VENDORITEMCODE ?? ""; + dr["VENDERLOTNO"] = item.VENDERLOTNO ?? ""; + dr["MANUFACTURER"] = item.MANUFACTURER ?? ""; + dr["EXDATE"] = item.EXDATE ?? ""; + dr["QTY"] = item.QTY; + dr["USERCODE"] = item.USERCODE ?? ""; + dr["MDATE"] = item.MDATE ?? ""; + dr["MTIME"] = item.MTIME ?? ""; + + // 加入表 + dtReel.Rows.Add(dr); + } + } + + clsERP.funAddMaterial_WIP(factory, dtReel); + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + strMsg = ex.Message; + } + finally + { + //组装返回JOSN + var resModel = new ReceiveReelMaterialByWMS_Response(); + + + + if (strResult == "success") + { + resModel.result = "1"; + } + else + { + // 失败逻辑 + resModel.result = "0"; + resModel.msg = strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + funSendReelMaterialByWMS = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "INV", "funReceiveReelMaterialByWMS", + "WMS", "WMS", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "ReceiveReelMaterialByWMS", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "WMS"); + } + + return funSendReelMaterialByWMS; + } + + #endregion + + + #region "SPC 接收数据" + + /// + /// 计量 + /// + /// + /// + public static string funGetJLSPCData(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + //调 clsERP 传入参数 + string SPCSerial_QMS = ""; + string MaterialNo = ""; + string MTLVendor = ""; + string Employee = ""; + string LotNo = ""; + string OPNo = ""; + string QCItemNo = ""; + string DC = ""; + string PartNo = ""; + var listTest = new List(); + + + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //要因 没有值,则给 * + SPCSerial_QMS = GetSafeString(result.SPCSERIAL); + MaterialNo = GetSafeString(result.MaterialNo); + MTLVendor = GetSafeString(result.MTLVendor); + Employee = GetSafeString(result.UserNo); + LotNo = GetSafeString(result.LOTNO); + OPNo = GetSafeString(result.OPNO); + QCItemNo = GetSafeString(result.QCItemNo); + DC = GetSafeString(result.DC); + PartNo = GetSafeString(result.PARTNO); + + //实测值,转换成list + var list = result.TestResults; + foreach (var item in list) + { + //item.TestValue 防空 + if (item.TestValue.ToString() != "") + { + listTest.Add(item.TestValue); + } + + } + + + + clsERP.funGetJLSPCData(ref strMessage, ref strException, SPCSerial_QMS, MaterialNo, MTLVendor, Employee, LotNo, OPNo, QCItemNo, DC, PartNo, listTest); + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + SPC_GetJLSPCData_Response response = null; + + if (strResult == "success") + { + response = new SPC_GetJLSPCData_Response + { + code = 0, + message = "成功", + success = true, + data = null, + tradeNo = null, + notSuccess = false + }; + } + else + { + // 失败逻辑 + response = new SPC_GetJLSPCData_Response + { + code = 1, + message = strMsg, + success = false, + data = null, + tradeNo = null, + notSuccess = true + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "SPC", "funGetJLSPCData", + "QMS", "QMS", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "GetJLSPCData", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "QMS"); + } + + return GetJLSPCData; + } + + + /// + /// 计数 + /// + /// + /// + public static string funGetJSSPCData(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + //调 clsERP 传入参数 + string SPCSerial_QMS = ""; + string MaterialNo = ""; + string MTLVendor = ""; + string Employee = ""; + string LotNo = ""; + string ProDuct = ""; + string EquipMent = ""; + string DC = ""; + string PartNo = ""; + var listTest = new List(); + + + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //要因 没有值,则给 * + SPCSerial_QMS = GetSafeString(result.SPCSERIAL); + MaterialNo = GetSafeString(result.MaterialNo); + MTLVendor = GetSafeString(result.MTLVendor); + Employee = GetSafeString(result.UserNo); + LotNo = GetSafeString(result.LOTNO); + ProDuct = GetSafeString(result.PRODUCT); + EquipMent = GetSafeString(result.EQUIPMENT); + DC = GetSafeString(result.DC); + //PartNo = GetSafeString(result.PARTNO); + + + clsERP.funGetJSSPCData(ref strMessage, ref strException, SPCSerial_QMS, MaterialNo, MTLVendor, Employee, LotNo, ProDuct, EquipMent, DC, result.QCItemDetails); + + + + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + SPC_GetJSSPCData_Response response = null; + + if (strResult == "success") + { + response = new SPC_GetJSSPCData_Response + { + code = 0, + message = "成功", + success = true, + data = null, + tradeNo = null, + notSuccess = false + }; + } + else + { + // 失败逻辑 + response = new SPC_GetJSSPCData_Response + { + code = 1, + message = strMsg, + success = false, + data = null, + tradeNo = null, + notSuccess = true + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "SPC", "funGetJSSPCData", + "QMS", "QMS", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "GetJSSPCData", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "QMS"); + } + + return GetJLSPCData; + } + + + /// + /// 如果字符串为 null 或空字符串,返回默认值(默认*),否则返回原值 + /// + /// 要判断的字段 + /// 为空时替换的值,默认* + /// + public static string GetSafeString(string value, string defaultValue = "*") + { + return string.IsNullOrEmpty(value) ? defaultValue : value; + } + #endregion + + + #region "工单砍单、取消卡控接口" + public static string funCheckMONoCanEditCancel(object parameters) + { + string funCheckMONoCanEditCancel = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + + + decimal decQuantity = 0; //数量 + int intStatus = 0; //状态 + + decimal InputQty = 0;//工单投入 + decimal OutputQty = 0;//工单产出 + string CurrentStatus = defString;//当前状态 + + bool bolclsERP = false; //调用clsERP方法是否成功 + + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + + //检查 result.MONO 是否为空 + if (string.IsNullOrEmpty(result.MONo)) + { + throw new Exception("MONO不能为空"); + } + + //检查数据 result.Quantity 和 result.Status 如果不是数值型,则提示 + if (!decimal.TryParse(result.Quantity.ToString(), out decQuantity)) + { + throw new Exception("Quantity必须是数值型"); + + } + + if (!int.TryParse(result.Status.ToString(), out intStatus)) + { + throw new Exception("Status必须是数值型"); + + } + + //intStatus 只能是0和1 + if (intStatus != 0 && intStatus != 1) + { + throw new Exception("Status必须是0或1"); + } + + + + bolclsERP = clsERP.funCheckMONoCanEditCancel_M(ref strMessage, ref strException, ref InputQty, ref OutputQty, ref CurrentStatus, result.MONo, decQuantity, intStatus); + if (bolclsERP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + ERP_CheckMONoCanEditCancel_Response response = null; + + if (strResult == "success") + { + response = new ERP_CheckMONoCanEditCancel_Response + { + code = 200, + message = "check successfully", + data = new ERP_MOData + { + InputQty = InputQty, + OutputQty = OutputQty, + CurrentStatus = CurrentStatus, + Rusult = "PASS" + }, + requestId = "" + }; + } + else + { + // 失败逻辑 + response = new ERP_CheckMONoCanEditCancel_Response + { + code = 500, + message = strMsg, + data = null // 序列化后不显示data字段 + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + funCheckMONoCanEditCancel = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "OE", "funCheckMONoCanEditCancel", + "ERP", "ERP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CheckMONoCanEditCancel", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "ERP"); + } + + return funCheckMONoCanEditCancel; + } + #endregion + + + #region"Materialhold" + public static string Materialhold(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + //调 clsERP 传入参数 + string source = ""; + string materialno = ""; + string materiallotno = ""; + string holdstate = ""; + string creator = ""; + string date = ""; + string reasonno = "ERPhold"; + var listTest = new List(); + int REVERSALMETHOD = -1; + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //要因 没有值,则给 * + source = GetSafeString(result.source); + materialno = GetSafeString(result.materialno); + materiallotno = GetSafeString(result.materiallotno); + holdstate = GetSafeString(result.holdstate); + creator = GetSafeString(result.creator); + date = GetSafeString(result.date); + reasonno = GetSafeString(result.reasonno); + if (reasonno == "*") + { + reasonno = "ERPhold"; + } + bool bolclsERP = clsERP.funGetMaterialhold(ref strMessage, ref strException, source, materialno, materiallotno, holdstate, creator, date, reasonno); + + if (bolclsERP == true) + { + strResult = "success"; + } + else + { + strResult = "fail"; + } + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + MaterialHoldResponse response = null; + + if (strResult == "success") + { + + response = new MaterialHoldResponse + { + result = true, + msg = "" + }; + } + else + { + MaterialHoldError error = new MaterialHoldError(); + error.code = "RMQ-01-00-0001"; + error.message = strMsg; + // 失败逻辑 + response = new MaterialHoldResponse + { + result = false, + msg = strMsg, + error = error + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "Materialhold", + "ERP", "ERP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "Materialhold", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "ERP"); + } + + return GetJLSPCData; + } + + #endregion + + #region"工单bom" + /// + /// 计量 + /// + /// + /// + public static string PrdBomList(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + //调 clsERP 传入参数 + string Productid = ""; + string ProductVersion = ""; + + var listTest = new List(); + int REVERSALMETHOD = -1; + try + { + + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + //要因 没有值,则给 * + Productid = GetSafeString(result.PRODUCTNO); + ProductVersion = GetSafeString(result.PRODUCTVERSION); + + if (Productid == "*") + { + throw new Exception("未传产品信息!"); + } + if (ProductVersion == "*") + { + throw new Exception("未传产品版本信息!"); + } + if (result.Bomlist.Count == 0) + { + throw new Exception("未传产品Bom信息!"); + } + + bool bolclsERP = clsERP.GetProdBOMInfo(ref strMessage, ref strException, Productid, ProductVersion, result); + + if (bolclsERP == true) + { + strResult = "success"; + } + else + { + strResult = "fail"; + } + } + catch (Exception ex) + { + strResult = "fail"; + //翻译 + strMsg = modWS.TranslateMsg(ex.Message); + + } + finally + { + //组装返回JOSN + + + MappingResponse response = null; + + if (strResult == "success") + { + + response = new MappingResponse + { + code = "0000", + message = "success", + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = null, + extras = null, + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + else + { + // 失败逻辑 + response = new MappingResponse + { + code = "1111", + message = strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + data = null, + extras = null, + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "PrdBomList", + "ERP", "ERP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "PrdBomList", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "ERP"); + } + + return GetJLSPCData; + } + + + #endregion + + #region"钢片绑定" + /// + /// 钢片绑定接口:根据设备编号查询批号,绑定钢片 + /// + public static string CarrierTackIn(object parameters) + { + string GetJLSPCData = default(string); + string strResult = ""; + string strMsg = ""; + string strKeyValue = ""; + var strException = new List(); + var strMessage = new List(); + string strResponseJson = ""; + string strRequestJson = ""; + + string equipmentno = ""; + string steelno = ""; + string carrierno = ""; + string lotno = ""; + + try + { + strRequestJson = funCheckJson(parameters); + + var result = JsonConvert.DeserializeObject(strRequestJson); + equipmentno = GetSafeString(result.equipmentno); + steelno = GetSafeString(result.steelno); + carrierno = GetSafeString(result.carrierno); + + // 校验参数 + if (string.IsNullOrEmpty(equipmentno)) + { + throw new Exception("设备编号不能为空"); + } + if (string.IsNullOrEmpty(steelno)) + { + throw new Exception("钢片编号不能为空"); + } + if (string.IsNullOrEmpty(carrierno)) + { + throw new Exception("料盒不能为空"); + } + + bool bolResult = clsERP.funSteelBind(ref strMessage, ref strException, equipmentno, steelno, carrierno, ref lotno); + + if (bolResult) + { + + } + else + { + strResult = "fail"; + if (strException.Count > 0 && strException[0].Count > 1) + { + strMsg = strException[0][1].ToString(); + } + } + bool bolclsEAP = clsEAP.funTrackIn_InquirybyLot(ref strMessage, ref strException, carrierno, equipmentno); + if (bolclsEAP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + strResult = "success"; + + } + catch (Exception ex) + { + strResult = "fail"; + strMsg = modWS.TranslateMsg(ex.Message); + } + finally + { + SteelBindResponse response = null; + if (strResult == "success") + { + response = new SteelBindResponse + { + code = "0000", + data = new SteelBindData + { + message = "成功", + lotno = lotno, + steelno = steelno + }, + extras = null, + message = "成功", + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + else + { + response = new SteelBindResponse + { + code = "1111", + data = null, + extras = null, + message = "进站失败," + strMsg, + time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + logId = "", + requestId = DateTime.Now.ToString("yyyyMMddHHmmssss") + }; + } + + strResponseJson = JsonConvert.SerializeObject(response); + GetJLSPCData = strResponseJson; + + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "WIP", "CarrierTackIn", + "ERP", "ERP", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CarrierTackIn", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "ERP"); + } + + return GetJLSPCData; + } + #endregion + + + + + + #region Reel校验接口 + //public static string CheckReelQty(string jsonInput) + //{ + // JObject response = new JObject(); + // try + // { + // JObject requestJson = JObject.Parse(jsonInput); + // string factory = (string)requestJson["Data"]?["Factory"]; + // string reelId = (string)requestJson["Data"]?["Detail"]?["REELID"]; + // string qty = (string)requestJson["Data"]?["Detail"]?["QTY"]; + // bool isSuccess = true; + + // if (isSuccess) + // { + // response["result"] = 1; + // response["qty"] = qty; + // response["mcode"] = "111"; + // response["vendorcode"] = "123456"; + // response["vendordate"] = "20240512"; + // response["manufacturer"] = "龙旗"; + // response["vendorlotno"] = "123"; + // response["oraFacReel"] = "12"; + // response["snscale"] = "09"; + // response["mpn"] = ""; + // response["produceArea"] = ""; + // response["cnum"] = 0; + // response["msg"] = null; + // } + // else + // { + // response["result"] = 0; + // response["msg"] = $"未找到该料卷{reelId}"; + // response["qty"] = ""; + // } + // } + // catch (Exception ex) + // { + // response["result"] = 0; + // response["msg"] = "解析异常或系统错误: " + ex.Message; + // response["qty"] = ""; + + // // 此处可以加上你原来的记录 Log 的代码 + // } + + // return response.ToString(Newtonsoft.Json.Formatting.None ); + //} + + public static string CheckReelQty(object parameters) + { + JObject response = new JObject(); + string strResult = "fail"; //返回结果 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + try + { + //取得报文,并校验接口规范的Header四参数(Content-Type/Source-System/Target-System/Authorization) + strRequestJson = funCheckJson(parameters); + + JObject requestJson = JObject.Parse(strRequestJson); + string factory = requestJson["Data"]?["Factory"]?.ToString(); + string reelId = requestJson["Data"]?["Detail"]?["REELID"]?.ToString(); + string qty = requestJson["Data"]?["Detail"]?["QTY"]?.ToString(); + string STORAGECODE = requestJson["Data"]?["Detail"]?["STORAGECODE"]?.ToString(); + + if (string.IsNullOrEmpty(reelId)) + { + throw new Exception("[%料卷唯一码必须传入!%]"); + } + strKeyValue = reelId; + + bool isSuccess = false; + string mcode = ""; + string qty1 = ""; + string vendordate = ""; + string vendorcode = ""; + string manufacturer = ""; + string vendorlotno = ""; + string snscale = ""; + bool everExisted = false; + isSuccess = clsERP.CheckReelQty(ref strMessage, ref strException, reelId, STORAGECODE ?? "", ref mcode, ref qty1, ref vendordate, ref vendorcode, ref manufacturer, ref vendorlotno, ref snscale, ref everExisted); + if (isSuccess) + { + response["result"] = 1; + response["qty"] = qty1; + response["mcode"] = mcode; + //供应商编码、生产厂家、供应商批次、09条码四栏,取自线边仓表对应栏位 + response["vendorcode"] = vendorcode; + response["vendordate"] = vendordate; + response["manufacturer"] = manufacturer; + response["vendorlotno"] = vendorlotno; + response["oraFacReel"] = reelId; + response["snscale"] = snscale; + //MPN、产地两栏线边仓表无对应栏位、WMS进料报文亦未带入, + //本次维持回空值,俟数据来源确认后另案补做取数 + response["mpn"] = ""; + response["produceArea"] = ""; + response["cnum"] = 0; + response["msg"] = null; + strResult = "success"; + } + else + { + response["result"] = 0; + //区分「料卷已扣光」与「卷号根本不存在」,此两者现场处理方式不同 + if (everExisted) + { + response["msg"] = $"料卷{reelId}已扣光"; + } + else + { + response["msg"] = $"未找到该料卷{reelId}"; + } + response["qty"] = ""; + strResult = "fail"; + } + } + catch (Exception ex) + { + response["result"] = 0; + response["msg"] = "数据解析异常或系统错误: " + ex.Message; + response["qty"] = ""; + strResult = "fail"; + } + finally + { + strResponseJson = response.ToString(Newtonsoft.Json.Formatting.None); + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "INV", "CheckReelQty", + "WMS", "WMS", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "CheckReelQty", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "WMS"); + } + + return strResponseJson; + } + #endregion + + + #region "WMS退料,扣减线边仓料卷数量" + public static string ReelReturn(object parameters) + { + string ReelReturn = default(string); + string strResult = ""; //返回结果 + string strMsg = ""; //返回信息 + string strKeyValue = ""; + var strException = new List(); // Exception XML字串 + var strMessage = new List(); // Message XML字串 + string strResponseJson = "";//传出JOSN + string strRequestJson = ""; //传入JOSN + + try + { + //取得报文,并校验接口规范的Header四参数(Content-Type/Source-System/Target-System/Authorization) + strRequestJson = funCheckJson(parameters); + + // ====================== + // 1.反序列化 JSON + // ====================== + var result = JsonConvert.DeserializeObject(strRequestJson); + + if (result.Data == null || result.Data.Detail == null) + { + throw new Exception("[%无明细数据!%]"); + } + + var detail = result.Data.Detail; + + string mvdCode = detail.MVDCODE ?? ""; + string moCode = detail.MOCODE ?? ""; + string fromStorage = detail.FROMSTORAGE ?? ""; + string toStorage = detail.TOSTORAGE ?? ""; + string userCode = detail.USERCODE ?? ""; + string mDate = detail.MDATE ?? ""; + string mTime = detail.MTIME ?? ""; + + if (mvdCode == "" || fromStorage == "") + { + throw new Exception("[%退料单号,供应仓都必须传入!%]"); + } + strKeyValue = mvdCode; + + if (detail.REELINFO == null || detail.REELINFO.Count == 0) + { + throw new Exception("[%料卷信息必须传入!%]"); + } + + // 定义最终要组装的DataTable + DataTable dtReelInfo = new DataTable(); + + // 先给DataTable创建所有列 + dtReelInfo.Columns.Add("REELID", typeof(string)); + dtReelInfo.Columns.Add("MCODE", typeof(string)); + dtReelInfo.Columns.Add("QTY", typeof(string)); + + //2.收集数据:依REELINFO逐笔扣减,MLIST仅为汇总不参与扣减 + foreach (var item in detail.REELINFO) + { + // 新建一行 + DataRow dr = dtReelInfo.NewRow(); + + // 赋值所有字段 + dr["REELID"] = item.REELID ?? ""; + dr["MCODE"] = item.MCODE ?? ""; + dr["QTY"] = item.QTY ?? ""; + + // 加入表 + dtReelInfo.Rows.Add(dr); + } + + bool bolclsERP = false; + bolclsERP = clsERP.ReelReturn(ref strMessage, ref strException, mvdCode, moCode, fromStorage, toStorage, userCode, mDate, mTime, dtReelInfo); + if (bolclsERP == false) + { + //说明有提示 + modWS.ChgTranslateMessage(ref strMessage, ref strMsg); + throw new Exception(strMsg); + } + + strResult = "success"; + + + + exitFun: + ; + } + catch (Exception ex) + { + strResult = "fail"; + strMsg = ex.Message; + } + finally + { + //组装返回JOSN + var resModel = new ReelReturn_Response(); + + if (strResult == "success") + { + resModel.result = "1"; + } + else + { + // 失败逻辑 + resModel.result = "0"; + resModel.msg = strMsg; + } + + //resModel 转成JOSN返回 + strResponseJson = JsonConvert.SerializeObject(resModel); + ReelReturn = strResponseJson; + + // 紀錄Transaction Log + tcEAI_C.clsERP.addTransactionLog_ErrorCode(DateTime.Now.ToString("yyyyMMddHHmmssss"), + "INV", "ReelReturn", + "WMS", "WMS", DateTime.Now.ToString(), + strResult, strKeyValue, strMessage, strException, strRequestJson, strResponseJson, "ReelReturn", + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepLog"]), + Conversions.ToInteger(System.Configuration.ConfigurationManager.AppSettings["keepXML"]), + LogClass: "WMS"); + } + + return ReelReturn; + } + + #endregion + + } + +} diff --git a/MESEAI/EAICws/EAICws/modERPIntegrate.cs b/MESEAI/EAICws/EAICws/modERPIntegrate.cs new file mode 100644 index 0000000..740f816 --- /dev/null +++ b/MESEAI/EAICws/EAICws/modERPIntegrate.cs @@ -0,0 +1,16 @@ +using tcEAI_C; +using iMESCore.Settings; + +namespace EAIws_C +{ + + static class modERPIntegrate + { + + public static string strService = "ERPIntegrate"; + public static string strDataBaseType; + public static string strConnectionString; + + + } +} \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/modKMI.cs b/MESEAI/EAICws/EAICws/modKMI.cs new file mode 100644 index 0000000..4ce0867 --- /dev/null +++ b/MESEAI/EAICws/EAICws/modKMI.cs @@ -0,0 +1,37 @@ +using System; +using System.Xml; + +namespace EAIws_C +{ + + /// +/// +/// + static class modKMI + { + + private static string strService = "KMI"; + + private static string RequestKey = string.Empty; + private static string AccountID = string.Empty; + private static string SeesionID = string.Empty; + public const string SuccessCode = "0"; + + public static void GetXMLHeaderNode(XmlDocument xmlDoc) + { + + if (xmlDoc.SelectNodes("request").Item(0).SelectNodes("host").Count != 0) + { + AccountID = ((XmlElement)xmlDoc.SelectNodes("request").Item(0).SelectNodes("host").Item(0)).GetAttribute("acct"); + if (string.IsNullOrEmpty(AccountID)) + throw new Exception("GetXMLHeaderNode fail!", new Exception("acct is Empty!")); + } + else + { + throw new Exception("GetXMLHeaderNode fail!", new Exception("acct is not found!")); + } + + } + + } +} \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/modWS.cs b/MESEAI/EAICws/EAICws/modWS.cs new file mode 100644 index 0000000..ce93857 --- /dev/null +++ b/MESEAI/EAICws/EAICws/modWS.cs @@ -0,0 +1,1494 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using static System.Configuration.ConfigurationManager; +using System.Data; +using System.IO; +using System.Resources; +using System.Runtime.InteropServices; +using System.Web; +using System.Xml; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using static iMESCore.Base.iMESConst; + +namespace EAIws_C +{ + + static class modWS + { + #region --- Get Xml Value --- + + + public static string GetXMLIdentityNode(XmlDocument xmlDoc, string SelectNode) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes(SelectNode).Item(0).InnerXml; + } + catch (Exception e1) + { + return "IdentityError"; + } + + } + + public static string GetXMLTransactionID(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("transactionid").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetXMLModuleID(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("moduleid").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetXMLFunctionID(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("functionid").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetXMLComputerName(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("computername").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetXMLCurUserNo(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("curuserno").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetXMLSendTime(ref XmlDocument xmlDoc) + { + try + { + return xmlDoc.GetElementsByTagName("identity").Item(0).SelectNodes("sendtime").Item(0).InnerXml; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("modWS.GetXMLCurUserNo: " & e1.Message) + } + + public static string GetExceptionSysMsg(ref XmlDocument Xmldoc) + { + string GetExceptionSysMsgRet = default(string); + GetExceptionSysMsgRet = CInput(Xmldoc.DocumentElement.GetElementsByTagName("sysmsg").Item(0).InnerXml); + return GetExceptionSysMsgRet; + } + + public static string GetExceptionMesMsg(ref XmlDocument Xmldoc) + { + string GetExceptionMesMsgRet = default(string); + GetExceptionMesMsgRet = CInput(Xmldoc.DocumentElement.GetElementsByTagName("mesmsg").Item(0).InnerXml); + return GetExceptionMesMsgRet; + } + + public static bool chkExecutionSuccess(ref XmlDocument Xmldoc) + { + bool chkExecutionSuccessRet = default(bool); + if (Xmldoc.DocumentElement["result"].InnerXml == "success") + { + chkExecutionSuccessRet = true; + } + else + { + chkExecutionSuccessRet = false; + } + + return chkExecutionSuccessRet; + } + + + #endregion + + #region --- Combine Indentity Xml --- + + public static string CombineXMLIdentity(XmlDocument XMLDoc) + { + string CombineXMLIdentityRet = default(string); + CombineXMLIdentityRet = Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "transactionid") + "" + '\n'; + CombineXMLIdentityRet += Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "moduleid") + "" + '\n'; + CombineXMLIdentityRet += Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "functionid") + "" + '\n'; + CombineXMLIdentityRet += Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "computername") + "" + '\n'; + CombineXMLIdentityRet += Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "curuserno") + "" + '\n'; + CombineXMLIdentityRet += Conversions.ToString('\t') + '\t' + "" + GetXMLIdentityNode(XMLDoc, "sendtime") + ""; + return CombineXMLIdentityRet; + } + + public static string CombineXMLIdentity(ref string ComputerName, ref string CurUserNo, ref string SendTime) + { + string CombineXMLIdentityRet = default(string); + CombineXMLIdentityRet = "" + ComputerName + "" + "" + CurUserNo + "" + "" + SendTime + ""; + return CombineXMLIdentityRet; + } + + #endregion + + #region --- Combine Input Xml --- + + + public static string CombineXMLIdentity(ref string TransactionID, ref string ModuleID, ref string FunctionID, ref string ComputerName, ref string CurUserNo, ref string SendTime) + { + string CombineXMLIdentityRet = default(string); + CombineXMLIdentityRet = "" + TransactionID + "" + "" + ModuleID + "" + "" + FunctionID + "" + "" + ComputerName + "" + "" + CurUserNo + "" + "" + SendTime + ""; + return CombineXMLIdentityRet; + } + + public static string CombineXMLParameter(ref string value_name, ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterRet = default(string); + + CombineXMLParameterRet = "<" + value_name.ToLower() + ">" + "" + name + "" + "" + type + "" + "" + value + "" + "" + desc + "" + ""; + return CombineXMLParameterRet; + + } + + public static string CombineXMLParameter(ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterRet = default(string); + CombineXMLParameterRet = "<" + name.ToLower() + ">" + "" + name + "" + "" + type + "" + "" + value + "" + "" + desc + "" + ""; + return CombineXMLParameterRet; + } + + public static string CombineXMLValue(ref string TagName, ref string Value) + { + string CombineXMLValueRet = default(string); + CombineXMLValueRet = "<" + TagName + ">" + Value + ""; + return CombineXMLValueRet; + } + + public static string CombineXMLValueTag(ref string Value) + { + string CombineXMLValueTagRet = default(string); + CombineXMLValueTagRet = "" + Value + ""; + return CombineXMLValueTagRet; + } + + public static string CombineXMLRequest(ref string strIdentity, ref string strParameter) + { + string CombineXMLRequestRet = default(string); + + CombineXMLRequestRet = "" + "" + strIdentity + ""; + if (!string.IsNullOrEmpty(strParameter)) + { + CombineXMLRequestRet = CombineXMLRequestRet + "" + strParameter + ""; + } + CombineXMLRequestRet = CombineXMLRequestRet + ""; + return CombineXMLRequestRet; + + } + + public static string CombineXMLParameterMultiValue(ref string value_name, ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterMultiValueRet = default(string); + // Value不用加上Tag + CombineXMLParameterMultiValueRet = "<" + value_name.ToLower() + ">" + "" + name + "" + "" + type + "" + value + "" + desc + "" + ""; + return CombineXMLParameterMultiValueRet; + } + + public static string CombineXMLAdditional(ref string strAdditional) + { + string CombineXMLAdditionalRet = default(string); + CombineXMLAdditionalRet = "" + strAdditional; + CombineXMLAdditionalRet = CombineXMLAdditionalRet + ""; + return CombineXMLAdditionalRet; + } + + public static string CombineAddXML_Add(ref string name, ref string type, ref string value) + { + string CombineAddXML_AddRet = default(string); + CombineAddXML_AddRet = "" + "" + name + "" + "" + type + "" + "" + value + "" + ""; + return CombineAddXML_AddRet; + } + + public static string CombineAddXML_Edit(ref string name, ref string type, ref string value) + { + string CombineAddXML_EditRet = default(string); + CombineAddXML_EditRet = "" + "" + name + "" + "" + type + "" + "" + value + "" + ""; + return CombineAddXML_EditRet; + } + + public static string CombineAddXML_Field(ref string name) + { + string CombineAddXML_FieldRet = default(string); + CombineAddXML_FieldRet = "" + "" + name + "" + ""; + return CombineAddXML_FieldRet; + } + + public static string CombineAddXML_Condition(string condition) + { + string CombineAddXML_ConditionRet = default(string); + + // 2007/03/22,sammi.呼叫CombineAddXML_Condition時,不可加CInput. + // 因CInput會將單引號轉成二個單引號,若Condition為下述範例時,會Error. + // strAdditional = CombineXMLAdditional(CombineAddXML_Condition("ModuleType in ('REWORK','SLR')")) + // strParameter += strAdditional + + CombineAddXML_ConditionRet = "" + condition + ""; + return CombineAddXML_ConditionRet; + + } + + public static string CInput(string strInput) + { + string CInputRet = default(string); + // 將傳入值內的單引號轉換為可存入資料庫的格式 + // 將傳入值內的 &, >, < 三個特殊字元轉換為XmlDocument可解譯之代替符號 + // 傳入值: strInput包含特殊字元的字串 + // 傳回值: 將特殊字元變更為代替符號的字串 + + // 轉換 ' 為 '' (單引號轉為兩個單引號) + CInputRet = Strings.Replace(strInput, "'", "''"); + + // 轉換 & 為 & + CInputRet = Strings.Replace(CInputRet, "&", "&"); + + // CInput = Replace(CInput, """", "''") 'AddFlow的Xml字串不可將雙引號轉為兩個單引號,XMLToFlow會Error + + // 轉換 > 為 > + CInputRet = Strings.Replace(CInputRet, ">", ">"); + + // 轉換 < 為 < + CInputRet = Strings.Replace(CInputRet, "<", "<"); + return CInputRet; + + } + + #endregion + + #region --- Combine Output Xml --- + + public static bool ChgTranslateException(List Exception, ref string strExceptionSysmsg, ref string strExceptionMesmsg, ref string strExceptionStack) + { + bool ChgTranslateExceptionRet = default(bool); + + try + { + foreach (ArrayList al in Exception) + { + if (!string.IsNullOrEmpty(strExceptionSysmsg)) + strExceptionSysmsg += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[1])) == false) + strExceptionSysmsg += Conversions.ToString('\t') + '\t' + '\t' + al[1].ToString(); + if (string.IsNullOrEmpty(strExceptionMesmsg) == false) + strExceptionMesmsg += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[2])) == false) + { + // 翻譯錯誤訊息 + string strErrName_Rep = ""; + string ErrorName = al[2].ToString(); + if (Strings.InStr(ErrorName, "[%", CompareMethod.Text) > 0) + { + string strKey, strKeyValue; + int intStart, j, k, l; + + intStart = 1; + j = 1; + + while (j != 0) + { + j = Strings.InStr(intStart, ErrorName, "[%", CompareMethod.Text); + if (j == 0) + { + strErrName_Rep += Strings.Mid(ErrorName, intStart); + } + else + { + k = Strings.InStr(j + 2, ErrorName, "%]", CompareMethod.Text); + if (k == 0) + { + // 找不到對應的結束字元. + strErrName_Rep += Strings.Mid(ErrorName, intStart); + j = 0; + } + else + { + // 檢查是否有不對稱的情況. + l = Strings.InStr(j + 2, ErrorName, "[%", CompareMethod.Text); + if (l == 0 || l > k) + { + strErrName_Rep += Strings.Mid(ErrorName, intStart, j - intStart); + strKey = Strings.Mid(ErrorName, j + 2, k - j - 2); + // 將Key執行語系轉換 + try + { + strKeyValue = ""; + strKeyValue = TranslateMsg(strKey); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } // & "(" & strKey & ")" + // 下次截取字串的起始位置 + intStart = k + 2; + } + else + { + // 不對稱,找到最內層的[%%] + int m; + // 在前面的條件下,一定找得到. + m = Strings.InStrRev(ErrorName, "[%", k, CompareMethod.Text); + // 擷出不轉換的字串. + strErrName_Rep += Strings.Mid(ErrorName, intStart, m - intStart); + strKey = Strings.Mid(ErrorName, m + 2, k - m - 2); + // 將Key執行語系轉換 + try + { + strKeyValue = ""; + strKeyValue = TranslateMsg(strKey); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } // & "(" & strKey & ")" + // 下次截取字串的起始位置 + intStart = k + 2; + } + } + } + } + } + // strExceptionMesmsg += Chr(9) & Chr(9) & Chr(9) & Resources.Resource.ResourceManager.GetString(al.Item(2).ToString) & "(" & al.Item(2).ToString & ")" + strExceptionMesmsg += Conversions.ToString('\t') + '\t' + '\t' + strErrName_Rep; + } + + if (!string.IsNullOrEmpty(strExceptionStack)) + strExceptionStack += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[3])) == false) + strExceptionStack += Conversions.ToString('\t') + '\t' + '\t' + al[3].ToString(); + } + + ChgTranslateExceptionRet = true; + } + + catch (Exception e1) + { + throw; + ChgTranslateExceptionRet = false; + } + + return ChgTranslateExceptionRet; + + } + + public static bool ChgTranslateException_ByLanguage(ref List Exception, ref string strExceptionSysmsg, ref string strExceptionMesmsg, ref string strExceptionStack, bool ShowStack) + { + bool ChgTranslateException_ByLanguageRet = default(bool); + + try + { + // item content>> 0:code, 1:sysmsg, 2:mesmsg, 3:stack + foreach (ArrayList al in Exception) + { + if (!string.IsNullOrEmpty(strExceptionSysmsg)) + strExceptionSysmsg += Conversions.ToString(ControlChars.Cr); + if (!string.IsNullOrEmpty(strExceptionStack)) + strExceptionStack += Conversions.ToString(ControlChars.Cr); + // code + if (string.IsNullOrEmpty(Conversions.ToString(al[0])) == false) + { + strExceptionSysmsg += string.Format("[{0}]", TranslateMsg(al[0].ToString())); + } + if (string.IsNullOrEmpty(Conversions.ToString(al[1])) == false) + { + strExceptionSysmsg += "," + TranslateMsg(al[1].ToString()); + } + if (string.IsNullOrEmpty(strExceptionMesmsg) == false) + strExceptionMesmsg += Conversions.ToString(ControlChars.Cr); + if (string.IsNullOrEmpty(Conversions.ToString(al[2])) == false) + { + // 翻譯錯誤訊息 + string strErrName_Rep = ""; + string ErrorName = al[2].ToString(); + strErrName_Rep = TranslateMsg(ErrorName); + strExceptionMesmsg += "," + strErrName_Rep; + } + // stack + if (ShowStack == true && string.IsNullOrEmpty(Conversions.ToString(al[3])) == false) + { + strExceptionStack += ControlChars.Tab + al[3].ToString(); + } + } + + ChgTranslateException_ByLanguageRet = true; + } + + catch (Exception ex) + { + throw; + ChgTranslateException_ByLanguageRet = false; + } + + return ChgTranslateException_ByLanguageRet; + + } + + public static bool ChgTranslateException_ByLanguage(ref List Exception, ref string strExceptionSysmsg, ref string strExceptionMesmsg, ref string strExceptionStack) + { + bool ChgTranslateException_ByLanguageRet = default(bool); + + try + { + foreach (ArrayList al in Exception) + { + if (!string.IsNullOrEmpty(strExceptionSysmsg)) + strExceptionSysmsg += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[1])) == false) + strExceptionSysmsg += Conversions.ToString('\t') + '\t' + '\t' + TranslateMsg(al[1].ToString()); + if (string.IsNullOrEmpty(strExceptionMesmsg) == false) + strExceptionMesmsg += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[2])) == false) + { + // 翻譯錯誤訊息 + string strErrName_Rep = ""; + string ErrorName = al[2].ToString(); + strErrName_Rep = TranslateMsg(ErrorName); + strExceptionMesmsg += Conversions.ToString('\t') + '\t' + '\t' + strErrName_Rep; + } + + if (!string.IsNullOrEmpty(strExceptionStack)) + strExceptionStack += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[3])) == false) + strExceptionStack += Conversions.ToString('\t') + '\t' + '\t' + al[3].ToString(); + } + + ChgTranslateException_ByLanguageRet = true; + } + + catch (Exception e1) + { + throw; + ChgTranslateException_ByLanguageRet = false; + } + + return ChgTranslateException_ByLanguageRet; + + } + + public static bool ChgTranslateMessage(ref List Message, ref string strMmsg) + { + bool ChgTranslateMessageRet = default(bool); + + try + { + foreach (ArrayList al in Message) + { + if (!string.IsNullOrEmpty(strMmsg)) + strMmsg += Conversions.ToString('\n'); + if (string.IsNullOrEmpty(Conversions.ToString(al[2])) == false) + { + // 翻譯訊息 + string strErrName_Rep = ""; + string ErrorName = al[2].ToString(); + if (Strings.InStr(ErrorName, "[%", CompareMethod.Text) > 0) + { + // Replace[%%] + string strKey, strKeyValue; + int intStart, j, k, l; + + intStart = 1; + j = 1; + + while (j != 0) + { + j = Strings.InStr(intStart, ErrorName, "[%", CompareMethod.Text); + if (j == 0) + { + strErrName_Rep += Strings.Mid(ErrorName, intStart); + } + else + { + k = Strings.InStr(j + 2, ErrorName, "%]", CompareMethod.Text); + if (k == 0) + { + // 找不到對應的結束字元. + strErrName_Rep += Strings.Mid(ErrorName, intStart); + j = 0; + } + else + { + // 檢查是否有不對稱的情況. + l = Strings.InStr(j + 2, ErrorName, "[%", CompareMethod.Text); + if (l == 0 || l > k) + { + strErrName_Rep += Strings.Mid(ErrorName, intStart, j - intStart); + strKey = Strings.Mid(ErrorName, j + 2, k - j - 2); + // 將Key執行語系轉換 + try + { + strKeyValue = ""; + strKeyValue = TranslateMsg(strKey); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } // & "(" & strKey & ")" + // 下次截取字串的起始位置 + intStart = k + 2; + } + else + { + // 不對稱,找到最內層的[%%] + int m; + // 在前面的條件下,一定找得到. + m = Strings.InStrRev(ErrorName, "[%", k, CompareMethod.Text); + // 擷出不轉換的字串. + strErrName_Rep += Strings.Mid(ErrorName, intStart, m - intStart); + strKey = Strings.Mid(ErrorName, m + 2, k - m - 2); + // 將Key執行語系轉換 + try + { + strKeyValue = ""; + strKeyValue = TranslateMsg(strKey); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } // & "(" & strKey & ")" + // 下次截取字串的起始位置 + intStart = k + 2; + } + } + } + } + } + + // strMmsg += Resources.Resource.ResourceManager.GetString(al.Item(2).ToString) & "(" & al.Item(2).ToString & ")" + strMmsg += strErrName_Rep; + } + + } + + ChgTranslateMessageRet = true; + } + + catch (Exception e1) + { + throw; + + ChgTranslateMessageRet = false; + } + + return ChgTranslateMessageRet; + + } + + public static string CombineXMLReturnValue(ref string value_name, ref string name, ref string type, ref string schema, ref string value, ref string desc) + { + string CombineXMLReturnValueRet = default(string); + + try + { + CombineXMLReturnValueRet = "<" + value_name.Trim().ToLower() + ">" + "" + name + "" + "" + type + "" + "" + schema + "" + "" + value + "" + "" + desc + "" + ""; + } + + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("modWS.CombineXMLReturnValue: " & e1.Message) + + return CombineXMLReturnValueRet; + + } + + public static string CombineXMLException(ref string code, ref string sysmsg, ref string mesmsg, string stack = "") + { + string CombineXMLExceptionRet = default(string); + + // Edit by Yun 2006.8.9 加上 CInput + try + { + CombineXMLExceptionRet = "" + code + "" + "" + CInput(sysmsg) + "" + "" + CInput(mesmsg) + "" + "" + CInput(stack) + ""; + } + + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("modWS.CombineXMLException: " & e1.Message) + + return CombineXMLExceptionRet; + + } + + public static string CombineXMLMessage(string code, string type, string msg) + { + string CombineXMLMessageRet = default(string); + + try + { + CombineXMLMessageRet = "" + "" + code + "" + "" + type + "" + "" + msg + "" + ""; + } + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("modWS.CombineXMLMessage: " & e1.Message) + + return CombineXMLMessageRet; + + } + + public static string CombineXMLResponse(string Identity, string ReturnValue = null, List Exception = null, string Result = null, List Message = null) + { + string CombineXMLResponseRet = default(string); + + try + { + // + CombineXMLResponseRet = "" + '\n'; + + // + if (string.IsNullOrEmpty(Identity)) + { + CombineXMLResponseRet += '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += Identity + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + } + + // + if (string.IsNullOrEmpty(ReturnValue)) + { + CombineXMLResponseRet += '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + ReturnValue + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + } + + // + if (string.IsNullOrEmpty(Result)) + { + CombineXMLResponseRet += '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += '\t' + "" + Result + "" + '\n'; + } + + // + string strExceptionSysmsg = string.Empty; + string strExceptionMesmsg = string.Empty; + string strExceptionStack = string.Empty; + + if (Exception.Count == 0) + { + CombineXMLResponseRet += '\t' + "" + '\n'; + } + else + { + // 2016-12-01, Joe, Exception轉語系 + ChgTranslateException(Exception, ref strExceptionSysmsg, ref strExceptionMesmsg, ref strExceptionStack); + + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + AppSettings["defWSErrCode"] + "" + '\n'; + if (string.IsNullOrEmpty(strExceptionSysmsg) == true) + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n' + strExceptionSysmsg + '\n' + '\t' + '\t' + "" + '\n'; + } + if (string.IsNullOrEmpty(strExceptionMesmsg) == true) + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + strExceptionMesmsg + "" + '\n'; + } + else + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n' + strExceptionMesmsg + '\n' + '\t' + '\t' + "" + '\n'; + } + if (string.IsNullOrEmpty(strExceptionStack)) + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n' + strExceptionStack + '\n' + '\t' + '\t' + "" + '\n'; + } + CombineXMLResponseRet += '\t' + "" + '\n'; + } + + // + string strMmsg = string.Empty; + + if (Message.Count == 0) + { + CombineXMLResponseRet += '\t' + "" + '\n'; + } + else + { + CombineXMLResponseRet += '\t' + "" + '\n'; + // 2016-12-01, Joe, Message轉語系 + // Call ChgTranslateMessage(Message, strMmsg) + + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + AppSettings["defMSGCode"] + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + AppSettings["defMSGType"] + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + strMmsg + "" + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + } + + CombineXMLResponseRet += "" + '\n'; + } + + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + // Throw 'New Exception("modWS.CombineXMLResponse: " & e1.Message) + CombineXMLResponseRet = "" + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + '\t' + e1.Message + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + '\t' + "CombineXMLResponse;Fail" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += e1.StackTrace + '\n'; + CombineXMLResponseRet += Conversions.ToString('\t') + '\t' + "" + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += '\t' + "" + '\n'; + CombineXMLResponseRet += ""; + } + + return CombineXMLResponseRet; + + } + + public static string CombineXMLResponse(ref string Identity, ref string ReturnValue, ref string Exception, ref string Result, ref string Message) + { + string CombineXMLResponseRet = default(string); + + try + { + CombineXMLResponseRet = "" + Identity + ""; + + if (!string.IsNullOrEmpty(ReturnValue)) + { + CombineXMLResponseRet = CombineXMLResponseRet + "" + ReturnValue + ""; + } + + if (!string.IsNullOrEmpty(Exception)) + { + CombineXMLResponseRet = CombineXMLResponseRet + "" + Exception + ""; + } + + CombineXMLResponseRet = CombineXMLResponseRet + "" + Result + ""; + + if (!string.IsNullOrEmpty(Message)) + { + CombineXMLResponseRet = CombineXMLResponseRet + "" + Message + ""; + } + + CombineXMLResponseRet = CombineXMLResponseRet + ""; + } + + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("modWS.CombineXMLResponse: " & e1.Message) + + return CombineXMLResponseRet; + + } + + // 2016-02-03, Joe, 調整Response XML架構 + + public static string CombineXMLResponse_Parameter(string key = defString, string type = defString, DataTable[] dtTemp = null, bool IsDetail = false) + { + string CombineXMLResponse_ParameterRet = default(string); + + int i = 0; + var XmlDoc = new XmlDocument(); + XmlElement nodeParameter = null; + if ((key ?? "") != defString | (type ?? "") != defString) + { + nodeParameter = XmlDoc.CreateElement("parameter"); + if ((key ?? "") != defString) + nodeParameter.SetAttribute("key", key); + if ((type ?? "") != defString) + nodeParameter.SetAttribute("type", type); + XmlDoc.AppendChild(nodeParameter); + } + + if (!(dtTemp[0] == null)) + { + // For iTable As Integer = 0 To dtTemp.Length - 1 + // If dtTemp(iTable) Is Nothing Then Continue For + i = 0; + + XmlElement nodeData; + XmlElement nodeDetail = null; + XmlElement nodeTemp; + if (IsDetail == false) + { + nodeData = XmlDoc.CreateElement("data"); + nodeTemp = nodeData; + } + else + { + nodeDetail = XmlDoc.CreateElement("detail"); + nodeTemp = nodeDetail; + } + + // 除第一個table外其他視為第二階 + nodeTemp.SetAttribute("name", dtTemp[0].TableName); + XmlElement nodeField; + foreach (DataRow dr in dtTemp[0].Rows) + { + + var nodeRow = XmlDoc.CreateElement("row"); + i = i + 1; + nodeRow.SetAttribute("seq", i.ToString()); + foreach (DataColumn dc in dtTemp[0].Columns) + { + nodeField = XmlDoc.CreateElement("field"); + nodeField.SetAttribute("name", dc.ColumnName.ToLower()); + nodeField.SetAttribute("type", "string"); + nodeField.InnerText = dr[dc].ToString(); + nodeRow.AppendChild(nodeField); + } + if (IsDetail == false) + { + for (int iTable = 1, loopTo = dtTemp.Length - 1; iTable <= loopTo; iTable++) + CombineXMLResponse_Parameter(dtTemp: new DataTable[] { dtTemp[iTable] }, IsDetail: true); + } + nodeTemp.AppendChild(nodeRow); + } + if (IsDetail == false) + { + nodeParameter.AppendChild(nodeTemp); + } + else + { + nodeDetail.AppendChild(nodeTemp); + } + // Next + } + + CombineXMLResponse_ParameterRet = XmlDoc.InnerXml; + return CombineXMLResponse_ParameterRet; + + } + + public static string FormatXMLSchema(ref string XmlSchema) + { + string FormatXMLSchemaRet = default(string); + + int intTruncateLength; + + try + { + FormatXMLSchemaRet = ""; + + // 將Schema字串的前面一行刪除,以符合XML格式 + intTruncateLength = Strings.InStr(XmlSchema, "?>") + 1; + if (intTruncateLength != 1) + { + FormatXMLSchemaRet = Strings.Right(XmlSchema, Strings.Len(XmlSchema) - intTruncateLength); + } + else + { + FormatXMLSchemaRet = XmlSchema; + } + } + + catch (Exception e1) + { + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("modWS.FormatXMLSchema: " & e1.Message) + + return FormatXMLSchemaRet; + + } + + #endregion + + #region --- for Message Change Resource use--- + + /// + /// 2020/05/17 OwenLiu, Mantis:0071895, 讀取語系檔案到 Dictionary + /// + /// + /// + private static Dictionary funReadResourceFile_Dictionary(string ResourceFilePath) + { + + var oReturnResource = new Dictionary(); + + try + { + var reader = new ResourceReader(ResourceFilePath); + var en = reader.GetEnumerator(); + + while (en.MoveNext()) + oReturnResource.Add(Conversions.ToString(en.Key), Conversions.ToString(en.Value)); + reader.Close(); + } + catch (Exception ex) + { + throw; + } + + return oReturnResource; + + } + + /// + /// 2020/05/15 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + /// + /// + /// + /// + /// + private static bool funGetResouceValueText(string sourceFile, string pKey, ref string pResValue) + { + + bool blnResult = false; + ResourceSet rmGen = null; + + try + { + using (var fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + rmGen = new ResourceSet(fs); + fs.Close(); + } + + pResValue = rmGen.GetString(pKey.ToUpper()); + if (!string.IsNullOrEmpty(pResValue)) + blnResult = true; + } + catch (Exception ex) + { + throw; + } + + return blnResult; + + } + + /// + /// 2020/05/15 OwenLiu, Mantis:0071895, 取回所有語系檔案的 ResourceManager Array + /// + /// + /// + /// + /// + private static bool funGetMultiResourceManager(string pResourcePath, string pLanguageMode, ref ResourceManager oResourceManager, ref Dictionary[] oResourceDictionary) + { + + bool blnResult = false; + string strResourceFile = "mesresource"; + + try + { + + if (!string.IsNullOrEmpty(pLanguageMode)) + { + strResourceFile += "." + pLanguageMode; + } + else + { + strResourceFile += ".en"; + } + + if (new DirectoryInfo(pResourcePath).Exists == false) + { + oResourceManager = null; + return blnResult; + } + + // 一次性建立多個ResourceManager, 以節省控制項的語系轉換須多次開檔的時間(控制項一定會有多個) + int intIndex = 0; + short intResouceFileQty = 2; + if (intResouceFileQty == 1) + { + oResourceDictionary = null; + } + else if (intResouceFileQty > 1) + { + oResourceDictionary = new Dictionary[intResouceFileQty - 2 + 1]; + } + oResourceManager = ResourceManager.CreateFileBasedResourceManager(strResourceFile, pResourcePath, null); + oResourceDictionary[0] = funReadResourceFile_Dictionary(pResourcePath + @"\" + strResourceFile + ".resources91"); + + blnResult = true; + } + + catch (Exception ex) + { + throw; + } + + return blnResult; + + } + + + /// + /// 2020/05/15 OwenLiu, Mantis:0071895, 從所有語系檔案的 ResourceManager Array 取出對應的語系值 + /// + /// + /// + /// + private static string funGetResourceManager_Text(string pKey, ref ResourceManager oResourceManager, ref Dictionary[] oResourceDictionary) + { + string strResult = ""; + bool blnKeyExists = false; + + do + { + try + { + + // 先搜尋Dictionary 是否有對應的Key + if (oResourceDictionary != null) + { + foreach (Dictionary ResourceDic in oResourceDictionary) + { + if (ResourceDic.ContainsKey(pKey)) + { + strResult = ResourceDic[pKey]; + blnKeyExists = true; + break; + } + } + } + + if (!blnKeyExists) + { + // 未找到Key, 搜尋ResourceManager + strResult = oResourceManager.GetString(pKey); + if (!string.IsNullOrEmpty(strResult)) + break; + } + } + + catch (Exception ex) + { + } + } + // Throw + while (false); + + return strResult; + + } + + public static string TranslateMsg(string Message) + { + string TranslateMsgRet = default(string); + + // 1.Check LanguageMode + string strFileName, strGenFile; + string LanguageMode = AppSettings.Get("LanguageMode"); + if (string.IsNullOrEmpty(LanguageMode)) + { + strFileName = "mesresource.en"; + strGenFile = "mesresource.en"; + } + else + { + strFileName = "mesresource." + LanguageMode; + strGenFile = "mesresource." + LanguageMode; + } + + // 2.Get File Path + string strResourcePath = ""; + string strResourceDirectory = AppSettings.Get("ResourceDir"); + + // 2016/05/13 YF, 修改Server.MapPath取得實體路徑 + if (HttpContext.Current != null && HttpContext.Current.Server != null) + { + strResourcePath = HttpContext.Current.Server.MapPath("./" + strResourceDirectory); + } + + string strErrName_Rep = ""; + + // 檢查檔案是否存在 + if (File.Exists(strResourcePath + "/" + strFileName + ".resources") == true) + { + // 4.Replace原始訊息. + if (Strings.InStr(Message, "[%", CompareMethod.Text) > 0) + { + // Replace[%%] + // Dim rmGen As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, Nothing) + // 2014/03/20 Hank, 修正讀取Resources檔造成佔用的情形 + // Dim fs As New FileStream(strResourcePath.ToString & "/" & strFileName & ".resources", FileMode.Open, FileAccess.Read, FileShare.Read) + // Dim rmGen As New ResourceSet(fs) + // fs.Close() + + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + ResourceManager ResourceMgr = null; + Dictionary[] ResourceDictionary = null; + funGetMultiResourceManager(strResourcePath, LanguageMode, ref ResourceMgr, ref ResourceDictionary); + + string strKey, strKeyValue; + int intStart, j, k, l; + + intStart = 1; + j = 1; + + while (j != 0) + { + j = Strings.InStr(intStart, Message, "[%", CompareMethod.Text); + if (j == 0) + { + strErrName_Rep += Strings.Mid(Message, intStart); + } + else + { + k = Strings.InStr(j + 2, Message, "%]", CompareMethod.Text); + if (k == 0) + { + // 找不到對應的結束字元. + strErrName_Rep += Strings.Mid(Message, intStart); + j = 0; + } + else + { + // 檢查是否有不對稱的情況. + l = Strings.InStr(j + 2, Message, "[%", CompareMethod.Text); + if (l == 0 || l > k) + { + strErrName_Rep += Strings.Mid(Message, intStart, j - intStart); + strKey = Strings.Mid(Message, j + 2, k - j - 2); + // 將Key執行語系轉換 + try + { + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + strKeyValue = funGetResourceManager_Text(strKey.ToUpper(), oResourceManager: ref ResourceMgr, oResourceDictionary: ref ResourceDictionary); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } + // 下次截取字串的起始位置 + intStart = k + 2; + } + else + { + // 不對稱,找到最內層的[%%] + int m; + // 在前面的條件下,一定找得到. + m = Strings.InStrRev(Message, "[%", k, CompareMethod.Text); + // 擷出不轉換的字串. + strErrName_Rep += Strings.Mid(Message, intStart, m - intStart); + strKey = Strings.Mid(Message, m + 2, k - m - 2); + // 將Key執行語系轉換 + try + { + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + strKeyValue = funGetResourceManager_Text(strKey.ToUpper(), oResourceManager: ref ResourceMgr, oResourceDictionary: ref ResourceDictionary); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } + // 下次截取字串的起始位置 + intStart = k + 2; + } + } + } + } + + ResourceMgr = null; + ResourceDictionary = null; + } + else + { + strErrName_Rep = Message; + } + } + else + { + strErrName_Rep = Message.Replace("[%", "").Replace("%]", ""); + } + + TranslateMsgRet = strErrName_Rep; + return TranslateMsgRet; + + } + + public static string TranslateMsg(string Message, string pLanguage) + { + string TranslateMsgRet = default(string); + + // 1.Check LanguageMode + string strFileName, strGenFile; + string LanguageMode = pLanguage; + if (string.IsNullOrEmpty(LanguageMode)) + { + strFileName = "mesresource.en"; + strGenFile = "mesresource.en"; + } + else + { + strFileName = "mesresource." + LanguageMode; + strGenFile = "mesresource." + LanguageMode; + } + + // 2.Get File Path + string strResourcePath = ""; + string strResourceDirectory = AppSettings.Get("ResourceDir"); + + string strErrName_Rep = ""; + + if (HttpContext.Current != null && HttpContext.Current.Server != null) + { + strResourcePath = HttpContext.Current.Server.MapPath("./" + strResourceDirectory); + } + + // 檢查檔案是否存在 + if (File.Exists(strResourcePath + "/" + strFileName + ".resources") == true) + { + // 4.Replace原始訊息. + if (Strings.InStr(Message, "[%", CompareMethod.Text) > 0) + { + // Replace[%%] + // Dim rmGen As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, Nothing) + // 2014/03/20 Hank, 修正讀取Resources檔造成佔用的情形 + // Dim fs As New FileStream(strResourcePath.ToString & "/" & strFileName & ".resources", FileMode.Open, FileAccess.Read, FileShare.Read) + // Dim rmGen As New ResourceSet(fs) + // fs.Close() + + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + ResourceManager ResourceMgr = null; + Dictionary[] ResourceDictionary = null; + funGetMultiResourceManager(strResourcePath, pLanguage, ref ResourceMgr, ref ResourceDictionary); + + string strKey, strKeyValue; + int intStart, j, k, l; + + intStart = 1; + j = 1; + + while (j != 0) + { + j = Strings.InStr(intStart, Message, "[%", CompareMethod.Text); + if (j == 0) + { + strErrName_Rep += Strings.Mid(Message, intStart); + } + else + { + k = Strings.InStr(j + 2, Message, "%]", CompareMethod.Text); + if (k == 0) + { + // 找不到對應的結束字元. + strErrName_Rep += Strings.Mid(Message, intStart); + j = 0; + } + else + { + // 檢查是否有不對稱的情況. + l = Strings.InStr(j + 2, Message, "[%", CompareMethod.Text); + if (l == 0 || l > k) + { + strErrName_Rep += Strings.Mid(Message, intStart, j - intStart); + strKey = Strings.Mid(Message, j + 2, k - j - 2); + // 將Key執行語系轉換 + try + { + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + strKeyValue = funGetResourceManager_Text(strKey.ToUpper(), oResourceManager: ref ResourceMgr, oResourceDictionary: ref ResourceDictionary); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } + // 下次截取字串的起始位置 + intStart = k + 2; + } + else + { + // 不對稱,找到最內層的[%%] + int m; + // 在前面的條件下,一定找得到. + m = Strings.InStrRev(Message, "[%", k, CompareMethod.Text); + // 擷出不轉換的字串. + strErrName_Rep += Strings.Mid(Message, intStart, m - intStart); + strKey = Strings.Mid(Message, m + 2, k - m - 2); + // 將Key執行語系轉換 + try + { + // 2020/05/20 OwenLiu, Mantis:0071895, 增加多語系檔案的語系轉換機制 + strKeyValue = funGetResourceManager_Text(strKey.ToUpper(), oResourceManager: ref ResourceMgr, oResourceDictionary: ref ResourceDictionary); + } + catch (Exception ex) + { + strKeyValue = strKey; + } + if (string.IsNullOrEmpty(strKeyValue)) + { + strErrName_Rep += strKey; + } + else + { + strErrName_Rep += strKeyValue; + } + // 下次截取字串的起始位置 + intStart = k + 2; + } + } + } + } + + ResourceMgr = null; + ResourceDictionary = null; + } + else + { + strErrName_Rep = Message; + } + } + else + { + strErrName_Rep = Message.Replace("[%", "").Replace("%]", ""); + } + + TranslateMsgRet = strErrName_Rep; + return TranslateMsgRet; + + } + + #endregion + + public static string CInput_Singlequotation(string strInput) + { + string CInput_SinglequotationRet = strInput; + + // 若為空字串,導致傳入資料變為Nothing + if (string.IsNullOrEmpty(strInput)) + return CInput_SinglequotationRet; + + // 將傳入值內的單引號轉換為可存入資料庫的格式 + // 傳入值: strInput包含特殊字元的字串 + // 傳回值: 將特殊字元變更為代替符號的字串 + + // 轉換 ' 為 '' (單引號轉為兩個單引號) + CInput_SinglequotationRet = Strings.Replace(strInput, "'", "''"); + return CInput_SinglequotationRet; + + // 17046 20230110 因EAI等接口,已接收InXML字串做 xmlDoc.LoadXml(InXml)解析通過,因此不需再各function做CInput,會將轉換後特殊字又處理一次造成寫入後端錯誤, + // 增加一支轉換函式CInput_Singlequotation,僅做單引號轉換,EAI接口中原本呼叫CInput的地方取代為CInput_Singlequotation + + } + + } +} \ No newline at end of file diff --git a/MESEAI/EAICws/EAICws/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs b/MESEAI/EAICws/EAICws/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs new file mode 100644 index 0000000..edc4647 --- /dev/null +++ b/MESEAI/EAICws/EAICws/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs @@ -0,0 +1,4 @@ +// +using System; +using System.Reflection; +[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] diff --git a/MESEAI/EAICws/EAICws/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/MESEAI/EAICws/EAICws/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache new file mode 100644 index 0000000..e382d80 Binary files /dev/null and b/MESEAI/EAICws/EAICws/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache differ diff --git a/MESEAI/EAICws/EAICws/obj/Debug/EAIws_C.csproj.AssemblyReference.cache b/MESEAI/EAICws/EAICws/obj/Debug/EAIws_C.csproj.AssemblyReference.cache new file mode 100644 index 0000000..bf62767 Binary files /dev/null and b/MESEAI/EAICws/EAICws/obj/Debug/EAIws_C.csproj.AssemblyReference.cache differ diff --git a/MESEAI/EAICws/EAICws/packages.config b/MESEAI/EAICws/EAICws/packages.config new file mode 100644 index 0000000..719b370 --- /dev/null +++ b/MESEAI/EAICws/EAICws/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/MESEAI/EAItc/EAItc_C.csproj b/MESEAI/EAItc/EAItc_C.csproj new file mode 100644 index 0000000..a5c5da1 --- /dev/null +++ b/MESEAI/EAItc/EAItc_C.csproj @@ -0,0 +1,275 @@ + + + + + Debug + AnyCPU + {443394E0-F618-0D60-04C0-E207199604A2} + Library + tcEAI_C + tcEAI_C + 512 + Windows + v4.6.2 + SAK + SAK + SAK + SAK + + $(DefaultItemExcludes);$(ProjectDir)**\*.vb + + + true + full + true + true + ..\..\MES_S_DLL\ + ..\..\MES_S_DLL\tcEAI_C.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + AnyCPU + false + + + pdbonly + false + true + true + ..\..\MES_S_DLL\ + ..\..\MES_S_DLL\tcEAI_C.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + false + + + On + + + Binary + + + Off + + + On + + + + False + ..\..\MES_S_DLL\Apache.NMS.dll + False + + + False + ..\..\MES_S_DLL\Apache.NMS.ActiveMQ.dll + False + + + False + ..\..\MES_S_DLL\BouncyCastle.Crypto.dll + False + + + False + ..\..\MES_S_DLL\data_access_service.dll + False + + + False + ..\..\MES_S_DLL\iMESAppSetting.dll + False + + + False + ..\..\MES_S_DLL\iMESCIOC.dll + + + False + ..\..\MES_S_DLL\iMESComSubroutine.dll + False + + + False + ..\..\MES_S_DLL\iMESComXML.dll + False + + + False + ..\..\MES_S_DLL\iMESConst.dll + False + + + False + ..\..\..\..\环境\MESws_API\bin\iMESUserManager.dll + + + False + ..\..\MES_S_DLL\iMESWIPReleaseLogHandler.dll + + + False + ..\..\..\..\环境\MESws_API\bin\kcEAP.dll + + + False + ..\..\..\..\环境\MESws_API\bin\kcEMS.dll + + + False + ..\..\MES_S_DLL\\kcENT.dll + + + False + ..\..\MES_S_DLL\kcEQP.dll + + + False + ..\..\MES_S_DLL\\kcOE.dll + + + False + ..\..\MES_S_DLL\\kcOP.dll + + + False + ..\..\MES_S_DLL\\kcSMD.dll + + + False + ..\..\MES_S_DLL\\kcSYS.dll + + + False + ..\..\..\..\环境\MESws_API\bin\kcUSR.dll + + + False + ..\..\MES_S_DLL\kcWIP.dll + + + + ..\..\MES_S_DLL\iMESCIO.dll + False + + + ..\..\MES_S_DLL\iMESDataObject.dll + False + + + ..\..\MES_S_DLL\iMESException.dll + False + + + False + ..\..\MES_S_DLL\iMESLog.dll + + + ..\..\MES_S_DLL\kcMTL.dll + False + + + ..\..\MES_S_DLL\kcPRD.dll + False + + + ..\..\MES_S_DLL\kcQC.dll + False + + + ..\..\MES_S_DLL\kcSPC.dll + + + False + + + + + + + + + + + False + ..\..\MES_S_DLL\tcEAI.dll + + + False + ..\..\MES_S_DLL\tcSPC_IC.dll + + + False + ..\..\MES_S_DLL\tcWIP_IC.dll + + + False + ..\..\MES_S_DLL\udReverse.dll + + + False + ..\..\MES_S_DLL\udSPC.dll + + + False + ..\..\MES_S_DLL\udSYS.dll + + + False + ..\..\MES_S_DLL\udSYS_Customer.dll + + + False + ..\..\MES_S_DLL\\udUnitTransferFunction.dll + + + False + ..\..\MES_S_DLL\udWIP.dll + + + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + Settings.settings + True + + + + + MyApplicationCodeGenerator + Application.Designer.cs + + + SettingsSingleFileGenerator + tcEAI_C.My + Settings.Designer.cs + + + + + \ No newline at end of file diff --git a/MESEAI/EAItc/EAItc_C.csproj.user b/MESEAI/EAItc/EAItc_C.csproj.user new file mode 100644 index 0000000..99e946b --- /dev/null +++ b/MESEAI/EAItc/EAItc_C.csproj.user @@ -0,0 +1,6 @@ + + + + D:\iMES\LQ\环境\DefaultSite\MESws_STD\bin\ + + \ No newline at end of file diff --git a/MESEAI/EAItc/My Project/Application.Designer.cs b/MESEAI/EAItc/My Project/Application.Designer.cs new file mode 100644 index 0000000..299bbe3 --- /dev/null +++ b/MESEAI/EAItc/My Project/Application.Designer.cs @@ -0,0 +1,11 @@ +// ------------------------------------------------------------------------------ +// +// 這段程式碼是由工具產生的。 +// 執行階段版本:4.0.30319.42000 +// +// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, +// 變更將會遺失。 +// +// ------------------------------------------------------------------------------ + + diff --git a/MESEAI/EAItc/My Project/Application.myapp b/MESEAI/EAItc/My Project/Application.myapp new file mode 100644 index 0000000..758895d --- /dev/null +++ b/MESEAI/EAItc/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 1 + true + diff --git a/MESEAI/EAItc/My Project/AssemblyInfo.cs b/MESEAI/EAItc/My Project/AssemblyInfo.cs new file mode 100644 index 0000000..805a6dd --- /dev/null +++ b/MESEAI/EAItc/My Project/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +// 組件的一般資訊是由下列的屬性集控制。 +// 變更這些屬性的值即可修改組件的相關 +// 資訊。 + +// 檢閱組件屬性的值 + +[assembly: AssemblyTitle("EAItc_C")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("EAItc")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] + +[assembly: ComVisible(false)] + +// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID +[assembly: Guid("c6f5bc9b-8482-4694-8df4-0b0a3f7b9707")] + +// 組件的版本資訊由下列四個值所組成: +// +// 主要版本 +// 次要版本 +// 組建編號 +// 修訂編號 +// +// 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號 +// 指定為預設值: +// + +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MESEAI/EAItc/My Project/Resources.resx b/MESEAI/EAItc/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MESEAI/EAItc/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MESEAI/EAItc/My Project/Settings.Designer.cs b/MESEAI/EAItc/My Project/Settings.Designer.cs new file mode 100644 index 0000000..d651d7b --- /dev/null +++ b/MESEAI/EAItc/My Project/Settings.Designer.cs @@ -0,0 +1,88 @@ +// ------------------------------------------------------------------------------ +// +// 這段程式碼是由工具產生的。 +// 執行階段版本:4.0.30319.42000 +// +// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, +// 變更將會遺失。 +// +// ------------------------------------------------------------------------------ + +using System.Diagnostics; +using Microsoft.VisualBasic; + + +namespace tcEAI_C.My +{ + + [System.Runtime.CompilerServices.CompilerGenerated()] + [System.CodeDom.Compiler.GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + internal sealed partial class MySettings : System.Configuration.ApplicationSettingsBase + { + + private static MySettings defaultInstance = (MySettings)Synchronized(new MySettings()); + + #region My.Settings 自動儲存功能 + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + #endregion + + public static MySettings Default + { + get + { + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + return defaultInstance; + } + } + } +} + +namespace tcEAI_C.My +{ + + [HideModuleName()] + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + internal static class MySettingsProperty + { + + [System.ComponentModel.Design.HelpKeyword("My.Settings")] + internal static MySettings Settings + { + get + { + return MySettings.Default; + } + } + } +} \ No newline at end of file diff --git a/MESEAI/EAItc/My Project/Settings.settings b/MESEAI/EAItc/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/MESEAI/EAItc/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MESEAI/EAItc/clsCom.cs b/MESEAI/EAItc/clsCom.cs new file mode 100644 index 0000000..23c6719 --- /dev/null +++ b/MESEAI/EAItc/clsCom.cs @@ -0,0 +1,340 @@ +using System; +using System.Reflection; +using Apache.NMS; +using Microsoft.VisualBasic; + +namespace tcEAI_C +{ + + /// +/// 20211027 13871,共用功能 +/// + public class clsCom + { + + /// + /// 20211027 13871,Reflection方法 + /// + /// DLL Name + /// Class Name + /// Function Name + /// + /// + /// + public static bool DetermineCustomized_Constructor(string strComponent, string strClassName, string strMethodName, ref MethodInfo mi, ref object obj) + { + bool DetermineCustomized_ConstructorRet = default(bool); + bool blnResult = false; + + DetermineCustomized_ConstructorRet = false; + try + { + blnResult = DetermineMethod_Constructor(strComponent, strClassName, strMethodName, ref mi, ref obj); + } + catch (Exception ex) + { + } + + finally + { + DetermineCustomized_ConstructorRet = blnResult; + } + + return DetermineCustomized_ConstructorRet; + + } + + /// + /// 20211027 13871,Reflection找出Method + /// + public static bool DetermineMethod_Constructor(string strComponent, string strClassName, string strMethodName, ref MethodInfo mi, ref object obj) + { + string strAppBase = AppDomain.CurrentDomain.BaseDirectory; + string strFilePath = ""; + Assembly mainAssembly; + Type t; + Type[] argumentTypes; + ConstructorInfo ctor; + + MethodInfo[] aryMethos; + + try + { + strFilePath = strAppBase.TrimEnd('\\') + @"\bin\" + strComponent; + mainAssembly = Assembly.LoadFrom(strFilePath); + t = mainAssembly.GetType(mainAssembly.GetName().Name + "." + strClassName, true, true); + // 20211211 13871,支援Module + if (t.GetConstructors().Length > 0) + { + argumentTypes = Type.EmptyTypes; + ctor = t.GetConstructor(argumentTypes); + obj = ctor.Invoke(new object[] { }); + } + strMethodName = Strings.Replace(strMethodName, ".", "_"); + aryMethos = t.GetMethods(); + foreach (MethodInfo item in aryMethos) + { + if ((strMethodName.ToUpper() ?? "") == (item.Name.ToUpper() ?? "")) + { + mi = item; + return true; + } + } + + if (mi == null) + { + return false; + } + else + { + return true; + } + } + catch (Exception ex) + { + return false; + } + } + + /// + /// 20211027 13871,取得Method的參數預設值陣列 + /// + /// DLL Name,可不傳副檔名,會自動補.dll + /// Class Name + /// Method Name + /// + public static object[] funGetMethodParameters(string strComponent, string strClassName, string strMethodName) + { + object[] funGetMethodParametersRet = default(object[]); + try + { + var mi = default(MethodInfo); + var obj = default(object); + if (!strComponent.ToUpper().Contains(".DLL")) + { + strComponent = strComponent + ".dll"; + } + + if (!DetermineCustomized_Constructor(strComponent, strClassName, strMethodName, ref mi, ref obj)) + { + throw new iMESException.MESException("0000-200003", strComponent + "." + strClassName + "," + strMethodName + " [%METHOD%] [%NOT FOUND%]"); + } + + int iParameterLength = mi.GetParameters().Length; + var aryParameter = new object[iParameterLength]; + for (int i = 0, loopTo = mi.GetParameters().Length - 1; i <= loopTo; i++) + { + try + { + aryParameter[i] = mi.GetParameters()[i].DefaultValue; + } + catch (Exception) + { + if (mi.GetParameters()[i].ParameterType == typeof(DateTime)) + aryParameter[i] = default(DateTime); + else + throw; + } + } + funGetMethodParametersRet = aryParameter; + } + catch (Exception ex) + { + throw; + } + + return funGetMethodParametersRet; + } + + /// + /// 20211027 13871,執行指定DLL、Class、Method,無法執行多載Method + /// + /// DLL Name,可不傳副檔名,會自動補.dll + /// Class Name + /// Method Name + /// + public static object funExecuteMethod(string strComponent, string strClassName, string strMethodName, ref object[] aryParameters) + { + object funExecuteMethodRet = default(object); + try + { + var mi = default(MethodInfo); + var obj = default(object); + if (!strComponent.ToUpper().Contains(".DLL")) + { + strComponent = strComponent + ".dll"; + } + + if (!DetermineCustomized_Constructor(strComponent, strClassName, strMethodName, ref mi, ref obj)) + { + throw new iMESException.MESException("0000-200003", strComponent + "." + strClassName + "," + strMethodName + " [%METHOD%] [%NOT FOUND%]"); + } + + funExecuteMethodRet = mi.Invoke(obj, aryParameters); + } + + catch (Exception ex) + { + ex = funGetRealException(ex); + throw ex; + } + + return funExecuteMethodRet; + } + + // 20211208 13871,從clsEAP移植 + public static Exception funGetRealException(Exception ex) + { + Exception funGetRealExceptionRet = default(Exception); + try + { + funGetRealExceptionRet = ex; + + if (ex is TargetInvocationException && ex.InnerException != null) + { + funGetRealExceptionRet = funGetRealException(ex.InnerException); + } + } + catch (Exception ex2) + { + throw; + } + + return funGetRealExceptionRet; + } + + + + #region --- Combine Input Xml --- + + + public static string CombineXMLIdentity(ref string TransactionID, ref string ModuleID, ref string FunctionID, ref string ComputerName, ref string CurUserNo, ref string SendTime) + { + string CombineXMLIdentityRet = default(string); + CombineXMLIdentityRet = "" + TransactionID + "" + "" + ModuleID + "" + "" + FunctionID + "" + "" + ComputerName + "" + "" + CurUserNo + "" + "" + SendTime + ""; + return CombineXMLIdentityRet; + } + + public static string CombineXMLParameter(ref string value_name, ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterRet = default(string); + + CombineXMLParameterRet = "<" + value_name.ToLower() + ">" + "" + name + "" + "" + type + "" + "" + value + "" + "" + desc + "" + ""; + return CombineXMLParameterRet; + + } + + public static string CombineXMLParameter(ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterRet = default(string); + CombineXMLParameterRet = "<" + name.ToLower() + ">" + "" + name + "" + "" + type + "" + "" + value + "" + "" + desc + "" + ""; + return CombineXMLParameterRet; + } + + public static string CombineXMLValue(ref string TagName, ref string Value) + { + string CombineXMLValueRet = default(string); + CombineXMLValueRet = "<" + TagName + ">" + Value + ""; + return CombineXMLValueRet; + } + + public static string CombineXMLValueTag(ref string Value) + { + string CombineXMLValueTagRet = default(string); + CombineXMLValueTagRet = "" + Value + ""; + return CombineXMLValueTagRet; + } + + public static string CombineXMLRequest(ref string strIdentity, ref string strParameter) + { + string CombineXMLRequestRet = default(string); + + CombineXMLRequestRet = "" + "" + strIdentity + ""; + if (!string.IsNullOrEmpty(strParameter)) + { + CombineXMLRequestRet = CombineXMLRequestRet + "" + strParameter + ""; + } + CombineXMLRequestRet = CombineXMLRequestRet + ""; + return CombineXMLRequestRet; + + } + + public static string CombineXMLParameterMultiValue(ref string value_name, ref string name, ref string type, ref string value, ref string desc) + { + string CombineXMLParameterMultiValueRet = default(string); + // Value不用加上Tag + CombineXMLParameterMultiValueRet = "<" + value_name.ToLower() + ">" + "" + name + "" + "" + type + "" + value + "" + desc + "" + ""; + return CombineXMLParameterMultiValueRet; + } + + public static string CombineXMLAdditional(ref string strAdditional) + { + string CombineXMLAdditionalRet = default(string); + CombineXMLAdditionalRet = "" + strAdditional; + CombineXMLAdditionalRet = CombineXMLAdditionalRet + ""; + return CombineXMLAdditionalRet; + } + + public static string CombineAddXML_Add(ref string name, ref string type, ref string value) + { + string CombineAddXML_AddRet = default(string); + CombineAddXML_AddRet = "" + "" + name + "" + "" + type + "" + "" + value + "" + ""; + return CombineAddXML_AddRet; + } + + public static string CombineAddXML_Edit(ref string name, ref string type, ref string value) + { + string CombineAddXML_EditRet = default(string); + CombineAddXML_EditRet = "" + "" + name + "" + "" + type + "" + "" + value + "" + ""; + return CombineAddXML_EditRet; + } + + public static string CombineAddXML_Field(ref string name) + { + string CombineAddXML_FieldRet = default(string); + CombineAddXML_FieldRet = "" + "" + name + "" + ""; + return CombineAddXML_FieldRet; + } + + public static string CombineAddXML_Condition(string condition) + { + string CombineAddXML_ConditionRet = default(string); + + // 2007/03/22,sammi.呼叫CombineAddXML_Condition時,不可加CInput. + // 因CInput會將單引號轉成二個單引號,若Condition為下述範例時,會Error. + // strAdditional = CombineXMLAdditional(CombineAddXML_Condition("ModuleType in ('REWORK','SLR')")) + // strParameter += strAdditional + + CombineAddXML_ConditionRet = "" + condition + ""; + return CombineAddXML_ConditionRet; + + } + + public static string CInput(string strInput) + { + string CInputRet = default(string); + // 將傳入值內的單引號轉換為可存入資料庫的格式 + // 將傳入值內的 &, >, < 三個特殊字元轉換為XmlDocument可解譯之代替符號 + // 傳入值: strInput包含特殊字元的字串 + // 傳回值: 將特殊字元變更為代替符號的字串 + + // 轉換 ' 為 '' (單引號轉為兩個單引號) + CInputRet = Strings.Replace(strInput, "'", "''"); + + // 轉換 & 為 & + CInputRet = Strings.Replace(CInputRet, "&", "&"); + + // CInput = Replace(CInput, """", "''") 'AddFlow的Xml字串不可將雙引號轉為兩個單引號,XMLToFlow會Error + + // 轉換 > 為 > + CInputRet = Strings.Replace(CInputRet, ">", ">"); + + // 轉換 < 為 < + CInputRet = Strings.Replace(CInputRet, "<", "<"); + return CInputRet; + + } + + #endregion + } +} \ No newline at end of file diff --git a/MESEAI/EAItc/clsEAP.cs b/MESEAI/EAItc/clsEAP.cs new file mode 100644 index 0000000..8dd770d --- /dev/null +++ b/MESEAI/EAItc/clsEAP.cs @@ -0,0 +1,12080 @@ +using System; +using System.Data; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using static iMESCore.Base.iMESConst; +using static iMESCore.Base.iMESComXML; +using static iMESCore.Base.iMESComSubroutine; +using System.Collections.Generic; +using System.Collections; +using iMESCore.Settings; +using kcSYS; +using kcWIP; +using System.Data.Common; +using System.Linq; +using static iMESCore.DataBase.iMESSql; +using System.Xml; +using kcOP; +using kcUSR; +using Org.BouncyCastle.Asn1; +using static kcWIP.clsMaterialHandler; +using System.Net.NetworkInformation; +using System.IO; +using System.Reflection; +using System.Text; +using Newtonsoft.Json; +using iMESCIOC.Response.EAP; + +namespace tcEAI_C +{ + + public class clsEAP + { + + public static string strDataBaseType; + public static string strConnectionString; + private kcWIP.clsLot objLot = new kcWIP.clsLot(); + + + private static System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // 用以讀取Xml字串 + + public static iMESWIPReleaseLogHandler.clsLotReleaseLogHandle objLotLog; + + private static udReverse.clsReverse objReverse = new udReverse.clsReverse(); + + private static clsDBCom objDBCom = new clsDBCom(); + + public static string strSQL = ""; + + #region 共用功能 ConbineXMLFunction + public static void SaveLog1(string LogMsg, string LogPath = "", string Json = "") + { + DateTime datLogTime = DateTime.Now; + string strLogFileName; + try + { + if (LogPath.Equals("")) + { + if (DriveExists("D")) + { + LogPath = @"D:\MESLOG"; + } + else + { + LogPath = System.IO.Directory.GetCurrentDirectory(); + } + + } + else if (!LogPath.EndsWith(@"\")) + LogPath += @"\Log"; + else + LogPath += "Log"; + + if (!Directory.Exists(LogPath)) + Directory.CreateDirectory(LogPath); + + string head = datLogTime.ToString("yyyy/MM/dd HH:mm:ss fff"); + LogMsg = head + System.Environment.NewLine + Json + System.Environment.NewLine + LogMsg + System.Environment.NewLine; + strLogFileName = LogPath + @"\" + "" + datLogTime.ToString("yyyyMMdd") + ".log"; + + using (System.IO.StreamWriter SW = new System.IO.StreamWriter(strLogFileName, true)) + { + SW.WriteLine(LogMsg); // 输出并换行 + SW.Flush(); // 刷新 + SW.Close(); // 关闭输出流 + } + } + catch (Exception ex) + { + } + } + public static bool DriveExists(string driveLetter) + { + try + { + // 获取所有驱动器信息 + DriveInfo[] allDrives = DriveInfo.GetDrives(); + foreach (DriveInfo drive in allDrives) + { + // 检查驱动器名称是否匹配 + if (drive.Name.StartsWith(driveLetter + ":")) + { + return true; // 找到匹配的驱动器,返回true + } + } + } + catch (Exception ex) + { + Console.WriteLine("发生错误:" + ex.Message); + } + return false; // 未找到匹配的驱动器,返回false + } + public static string CombineXMLRequest_AutoExecutionLot(string InXml, string functionid, string computername, DataTable dtLotInfo, string OPNo, string CurUserNo, string SendTime, bool blnRuleChk = true) + { + string CombineXMLRequest_AutoExecutionLotRet = default(string); + + string strLotXML = ""; + string strLotNoColumnName = ""; + if (dtLotInfo.Columns.Contains("Lot_ID")) + { + strLotNoColumnName = "Lot_ID"; + } + else if (dtLotInfo.Columns.Contains("LotNo")) + { + strLotNoColumnName = "LotNo"; + } + + string strrulecheckTag = ""; + if (!blnRuleChk) + { + strrulecheckTag = "false"; + } + + foreach (DataRow drTemp in dtLotInfo.Rows) + strLotXML = Conversions.ToString(strLotXML + Operators.ConcatenateObject(Operators.ConcatenateObject("", drTemp[strLotNoColumnName]), "")); + strLotXML += ""; + CombineXMLRequest_AutoExecutionLotRet = "" + " " + "" + Strings.Format(DateTime.Now, "yyyyMMddHHmmssfff") + "" + "" + functionid + "" + strLotXML + "" + computername + "" + "" + OPNo + "" + "" + CurUserNo + "" + "" + SendTime + "" + strrulecheckTag + "" + "" + InXml + "" + ""; + return CombineXMLRequest_AutoExecutionLotRet; + } + + #endregion + + #region ReverseTriggerOP + + public static bool ExeReverseTriggerOP_NotUseUndo(string pUserNo, string pLotNo, string pLotSerial = defString, int pLotStamp = defInteger, string ComputreName = "EAI") + { + + string InXml, OutXml, strIdentity, strParameter; + bool blnExecResult = false; + + // 2020/3/17 Ning, Mantis: 0068960, WIP_Kit 增加ExeReverseTriggerOP_NotUseUndo共用函式 + try + { + // 檢查此 BR 是否此站第一次執行,若是第一次執行則以刪除Temp, Cont, LotLog...的方式取消Trigger OP的動作 + strIdentity = CombineXMLIdentity(ComputreName, pUserNo, DateTime.Now.ToString(defDateTimeFormat)); + + strParameter = CombineXMLParameter("lotno", "LotNo", "String", CInput(pLotNo), ""); + // 因FormLoad不見得會成功取得Lot的資料,有可能失敗,故使用變數來決定是否傳出參數. + if ((pLotSerial ?? "") != defString) + { + strParameter += CombineXMLParameter("lotserial", "LotSerial", "String", CInput(pLotSerial), ""); + } + if (pLotStamp != defInteger) + { + strParameter += CombineXMLParameter("lotstamp", "LotStamp", "Long", pLotStamp.ToString(), ""); + } + InXml = CombineXMLRequest(strIdentity, strParameter); + // OutXml = InvokeSrv("wsWIP.ReverseTriggerOP_NotUseUndo", InXml) + + object[] aryPars = clsCom.funGetMethodParameters("wsSTD", "wsWIP", "ReverseTriggerOP_NotUseUndo"); + aryPars[0] = InXml; + OutXml = clsCom.funExecuteMethod("wsSTD", "wsWIP", "ReverseTriggerOP_NotUseUndo", ref aryPars) as string; + + blnExecResult = true; + } + catch (Exception ex) + { + + } + + return blnExecResult; + } + + #endregion + + #region "测试工序进出站" + public string Execute_CI_LOT(Dictionary dicPars, Dictionary dicPars_DataTable, string UserNo, string LanguageMode, ref List aryMessage) + { + string Execute_CI_LOTRet = default(string); + + var datSendTime = default(DateTime); + string strComputerName = string.Empty; + string strCurUserNo = UserNo; + + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string LotNo = ""; + DataSet dsTemp = new DataSet(); + IDbConnection cnnTemp = null; + AppSettings objSetting = new AppSettings(); + var CollectionSQL = new Collection(); + string strSQL = ""; + string LotResult = ""; + string ComputerName = Environment.MachineName; + DateTime sendTime = DateTime.Now; + DbDataReader drTemp = null; + DbDataReader drTemp1 = null; + int Curqty = 0; + string ProductNo = ""; + string ProductVersion = ""; + string MONO = ""; + long LotStamp = 0; + string UnitNo = ""; + string OPNO = ""; + + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + //首先根据unitid(子批批号)查出来当前批次 + strSQL = $@"SELECT * FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTTYPE=1 AND PRODUCTID='{dicPars["unitid"]}' AND STATE=1"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + LotNo = drTemp["LOTNO"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200002", "[%LOTNO%] [%NOT FOUND%]"); + } + drTemp.Close(); + + strSQL = $"SELECT A.*,B.MONO FROM TBLWIPLOTSTATE A LEFT JOIN TBLWIPLOTBASIS B ON A.LOTNO=B.BASELOTNO WHERE A.LOTNO='{LotNo}' "; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLWIPLOTSTATE", cnnTemp); + if (dsTemp.Tables["TBLWIPLOTSTATE"].Rows.Count > 0) + { + Curqty = Convert.ToInt32(dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["Curqty"].ToString()); + if (!dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["STATUS"].ToString().Equals("0")) + { + throw new iMESException.MESException("0000-12561", $"母批批次{LotNo}状态不为待进站!"); + } + MONO = dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["MONO"].ToString(); + LotStamp = Convert.ToInt64(dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["LotStamp"].ToString()); + UnitNo = dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["CURUNITNO"].ToString(); + OPNO = dsTemp.Tables["TBLWIPLOTSTATE"].Rows[0]["OPNO"].ToString(); + } + else + { + throw new iMESException.MESException("0000-12561", $"批次{LotNo }找不到在制信息!"); + } + + strSQL = $"SELECT * FROM TBLOEMOBASIS WHERE MONO='{MONO }'"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLOEMOBASIS", cnnTemp); + if (dsTemp.Tables["TBLOEMOBASIS"].Rows.Count > 0) + { + ProductNo = dsTemp.Tables["TBLOEMOBASIS"].Rows[0]["ProductNo"].ToString(); + ProductVersion = dsTemp.Tables["TBLOEMOBASIS"].Rows[0]["ProductVersion"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200001", $"工单{MONO}不存在!"); + } + + #region 分批逻辑,子批进出站 + if (Curqty > 1) + { + string splitLotNo = ""; + using (var objSYSEng = new kcSYS.clsSYSEng()) + { + splitLotNo = objSYSEng.GetSplitLotNo(true, LotNo, ""); + } + + //新建分批表 + DataTable dtSplitLot; + dtSplitLot = new DataTable("SplitLot"); + dtSplitLot.Columns.Add("SplitLotNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("SplitLotQty", Type.GetType("System.Decimal")); + dtSplitLot.Columns.Add("SplitSysQty", Type.GetType("System.Decimal")); + dtSplitLot.Columns.Add("Action", Type.GetType("System.Int32")); + dtSplitLot.Columns.Add("NodeID", Type.GetType("System.String")); + dtSplitLot.Columns.Add("ReturnType", Type.GetType("System.Int32")); + dtSplitLot.Columns.Add("FromProductNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("FromProductVersion", Type.GetType("System.String")); + dtSplitLot.Columns.Add("ProductNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("ProductVersion", Type.GetType("System.String")); + dtSplitLot.Columns.Add("UnitNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("OPNo", Type.GetType("System.String")); + //加入母批 + DataRow drData; + drData = dtSplitLot.NewRow(); + drData["SplitLotNo"] = LotNo; + drData["SplitLotQty"] = Curqty - 1; + drData["SplitSysQty"] = Curqty - 1; + drData["Action"] = 0; + drData["NodeID"] = ""; + drData["ReturnType"] = 0; + drData["FromProductNo"] = ProductNo; + drData["FromProductVersion"] = ProductVersion; + drData["ProductNo"] = ProductNo; + drData["ProductVersion"] = ProductVersion; + drData["UnitNo"] = UnitNo; + drData["OPNo"] = OPNO; + dtSplitLot.Rows.Add(drData); + //加入子批 + DataRow drData2; + drData2 = dtSplitLot.NewRow(); + drData2["SplitLotNo"] = splitLotNo; + drData2["SplitLotQty"] = 1; + drData2["SplitSysQty"] = 1; + drData2["Action"] = 0; + drData2["NodeID"] = ""; + drData2["ReturnType"] = 0; + drData2["FromProductNo"] = ProductNo; + drData2["FromProductVersion"] = ProductVersion; + drData2["ProductNo"] = ProductNo; + drData2["ProductVersion"] = ProductVersion; + drData2["UnitNo"] = UnitNo; + drData2["OPNo"] = OPNO; + dtSplitLot.Rows.Add(drData2); + //获取返回结果 + string returnSplitResult = ""; + try + { + using (var objLot = new kcWIP.clsLot()) + { + returnSplitResult = objLot.BR_Manual_LotSplit(LotStamp, LotNo, 0, UserNo, dtSplitLot); + //执行分批后查询分批的在制情况 + //未查询到表示分批失败,返回,否则继续后续逻辑 + strSQL = $"SELECT * FROM TBLWIPLOTSTATE WHERE LOTNO='{splitLotNo}' "; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLWIPLOTSTATE2", cnnTemp); + if (dsTemp.Tables["TBLWIPLOTSTATE2"].Rows.Count > 0) + { + //执行子批自动进出站 + dicPars.Add("lotno", splitLotNo); + Execute_CI_LOTRet = Convert.ToString(AutoexecutionLot_Lot_CS(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CI", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck))); + if (Execute_CI_LOTRet.Contains("success")) + { + strSQL = $@"UPDATE TBLWIPPRDSTATE_LQ SET STATE=0 WHERE PRODUCTTYPE=1 AND PRODUCTID='{dicPars["unitid"]}' AND STATE=1"; + CollectionSQL.Add(strSQL); + + strSQL = $@"INSERT INTO TBLWIPPRDSTATE_LQ(LOTNO,PRODUCTID,EQPID,STATE,OPNO,CARRIERID,PRODUCTTYPE,CREATEDATE) VALUES('{dicPars["lotno"]}','{dicPars["unitid"]}','',1,'{OPNO }','',1,To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'))"; + CollectionSQL.Add(strSQL); + + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + } + else + { + throw new iMESException.MESException("0000-12561", $"分批失败!"); + } + } + } + catch (Exception e) + { + returnSplitResult = "执行分批失败--" + e.Message; + throw new iMESException.MESException("0000-12561", returnSplitResult); + } + } + #endregion + #region 母批标准进出站逻辑 + else + { + //只有确定批号后再传入 + dicPars.Add("lotno", LotNo); + Execute_CI_LOTRet = Convert.ToString(AutoexecutionLot_Lot_CS(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CI", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck))); + } + #endregion + + return Execute_CI_LOTRet; + } + catch (Exception) + { + + throw; + } + finally + { + + CloseConnection(cnnTemp); + } + } + + public string Execute_CO_LOT(Dictionary dicPars, Dictionary dicPars_DataTable, string UserNo, string LanguageMode, ref List aryMessage) + { + string Execute_CO_LOTRet = default(string); + + var datSendTime = default(DateTime); // 送達時間 + string strFunctionID = "CO"; // 執行類型 'CI(進站)、CO (出站) 、SPC(SPC資料 + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = UserNo; // Request User -紀錄操作人員 + + string strSQL = ""; + + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string LotNo; + DbDataReader drTemp = null; + IDbConnection cnnTemp = null; + AppSettings objSetting = new AppSettings(); + DataSet dsLotTemp; + DataSet dsTemp = new DataSet(); + string LotSerial = "", OPNO = "", InventoryNo = "", MONo = "", CurUnitNo = "", ProductNo, ProductVersion, BaseLotNo = "", BRNo, LogGroupSerial = ""; + int intOPReference, intOPStatus; // OPReference參數要參考0:Product,1:Module. OPStatus 0:站間,1:站中 + string ReferenceNo, ReferenceVersion, NodeVersion, ModProcessNo, ModProcessVersion, CurModuleNo, CurModuleVersion, CurNodeId, AreaNo, OPGroupNo, strGOLinkName; + double CurQty; + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + //首先根据unitid(子批批号)查出来当前批次 + strSQL = $@"SELECT * FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTTYPE=1 AND PRODUCTID='{dicPars["unitid"]}' AND STATE=1"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + LotNo = drTemp["LOTNO"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200002", "[%LOTNO%] [%NOT FOUND%]"); + } + drTemp.Close(); + + using (var ds = new DataSet()) + { + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_Attrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = 2) And B.AllowNull = 0 And A.LotNo ='" + LotNo + "'", + ds.Tables.Add("TempAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dicPars_DataTable.Add("lotattrib", ds.Tables[0]); + } + + // 2.2 取得所有傳入Lot的AttribPhase = PhaseNo並且為99 的Keyin TempCopmonentAttrib + using (var ds = new DataSet()) + { + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_ComponentAttrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = 2) And B.AllowNull = 0 And A.LotNo ='" + LotNo + "'", + ds.Tables.Add("TempCopmonentAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dicPars_DataTable.Add("lotcomponentattrib", ds.Tables[0]); + } + + strSQL = "Select C.LotSerial, A.ProcessNo, A.OPNo, A.NodeId, A.AreaNo, A.HaveComponent, A.CurUnitNo, A.CurQty, A.GoStatus, A.HaveLevel, " + " A.OPReference, A.ModuleNo, A.ModuleVersion, A.LogGroupSerial, A.OPStatus,A.BRNo,A.GoLinkName, " + " B.BaseLotNo, B.ProductNo, B.ProductVersion,A.OPGroupNo,B.MONo,C.INVENTORYNO From tblWIPTemp_LotState C,tblWIPLotState A, tblWIPLotBasis B " + " Where A.LotNo ='" + LotNo + "'" + " And A.BaseLotNo = B.BaseLotNo AND C.LOTNO=A.LOTNO"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + intOPReference = Conversions.ToInteger(drTemp["OPReference"]); + if (intOPReference == 0) // 參考Product + { + ReferenceNo = drTemp["ProductNo"].ToString(); + ReferenceVersion = drTemp["ProductVersion"].ToString(); + } + else if (intOPReference == 1) // 參考Module + { + ReferenceNo = drTemp["ModuleNo"].ToString(); + ReferenceVersion = drTemp["ModuleVersion"].ToString(); + } + else + { + throw new iMESException.MESException("0000-202001", "[%LotNo%] : " + LotNo); + } + + LotSerial = drTemp["LotSerial"].ToString(); + ProductNo = drTemp["ProductNo"].ToString(); + ProductVersion = drTemp["ProductVersion"].ToString(); + CurModuleNo = drTemp["ModuleNo"].ToString(); + CurModuleVersion = drTemp["ModuleVersion"].ToString(); + OPNO = drTemp["OPNo"].ToString(); + BaseLotNo = drTemp["BaseLotNo"].ToString(); + InventoryNo = Conversions.ToString(drTemp["InventoryNo"]); + CurNodeId = drTemp["NodeID"].ToString(); + AreaNo = drTemp["AreaNo"].ToString(); + // HaveComponent = drTemp("HaveComponent") + CurUnitNo = drTemp["CurUnitNo"].ToString(); + CurQty = Convert.ToDouble(drTemp["CurQty"]); + // SetWait時會有資料,故不會Null + LogGroupSerial = drTemp["LogGroupSerial"].ToString(); + intOPStatus = Conversions.ToInteger(drTemp["OPStatus"]); + BRNo = drTemp["BRNo"].ToString(); + OPGroupNo = drTemp["OPGroupNo"].ToString(); + strGOLinkName = drTemp["GoLinkName"].ToString(); // 2012/02/22 + MONo = drTemp["MONo"].ToString(); // 2020/06/05 Elvis 0072943: 回填完工數量 + // 2022/2/25 0104829: SDD211216_02-01 / HaveComponent、HaveLevel判斷抽換成共用function + } + else + { + throw new iMESException.MESException("0000-202002", "[%LotNo%] : " + LotNo); + } + drTemp.Close(); + + dicPars.Add("lotno", LotNo); + dicPars.Add("opno", OPNO); + + using (var objkcWIP_clsLot = new clsLot()) + { + dsLotTemp = objkcWIP_clsLot.ShowLotBasisJoinState(LotNo); + } + if (dsLotTemp.Tables[0].Rows.Count < 1) + { + throw new iMESException.MESException("0000-200001", "[%LOTNO%][%NOT FOUND%]"); + } + + using (var obj = new kcEAP.clsWIP()) + { + if (obj.ChkCO_UseMaterial(LotNo) == false) + { + throw new iMESException.MESException("0000-200001", "ChkCO_UseMaterial Fail!"); + } + } + //(xg)检查请求报文是否增加了errorcode、errorvalue参数 + var errorcode = ""; + var errorvalue = ""; + if (dicPars.ContainsKey("errorcode")) + { + errorcode = dicPars["errorcode"].ToString(); + errorvalue = dicPars["errorvalue"].ToString(); + } + + // 1. 检查字典中是否存在这个key + if (dicPars_DataTable.ContainsKey("lotattrib")) + { + if (dicPars_DataTable["lotattrib"] != null) + { + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'")[0]["ATTRIBVALUE"] = CurQty; + } + + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'")[0]["ATTRIBVALUE"] = 0; + } + } + } + + //查询当前的作业站的属性中是否有【测试工序】属性,若有的话,将socketid存到进站的参数中,执行进站逻辑。 + strSQL = "SELECT * FROM TBLOPPROPERTY WHERE ISSUESTATE=2 AND PROPERTYNO='测试工序' AND OPNO='" + OPNO + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (dicPars["result"].ToString().ToUpper() == "NG") + { + // 1. 检查字典中是否存在这个key + if (dicPars_DataTable.ContainsKey("lotattrib")) + { + if (dicPars_DataTable["lotattrib"] != null) + { + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'")[0]["ATTRIBVALUE"] = 0; + } + + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'")[0]["ATTRIBVALUE"] = CurQty; + } + } + } + + Collection CollectionSQL = new Collection(); + //直接入不良品库 + strSQL = "Insert into tblINVWIP_Scrap(LogGroupSerial,InventoryNo,LotSerial,LotNo,OPNo,UnitNo,ScrapQty,LossQty,BaseLotNo, InputDate)" + " Values ('" + LogGroupSerial + "','" + InventoryNo + "','" + LotSerial + "', '" + LotNo + "','" + OPNO + "','" + CurUnitNo + "'," + CurQty + ",0,'" + BaseLotNo + "'," + " To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + ")"; + CollectionSQL.Add(strSQL); + // 加入ReverseUpdateContent + strSQL = "Delete From tblINVWIP_Scrap Where LotSerial='" + LotSerial + "'"; + Collection argcolSQL_Rows9 = null; + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows9); + + // 變更LotSate + // 2012/02/22,新增GoLinkName + strSQL = "Update tblWIPLotState Set LotSerial = '" + LotSerial + "'," + " Status = 12 ," + " GoStatus = null , " + " GoLinkName = null , " + " EventTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + " EventUserNo='" + UserNo + "'," + " EventDescription='测试工序入不良品仓'," + " ArriveTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),"; + if (intOPStatus == 1) // 站中Wait才須給EndTime + { + strSQL = strSQL + " PreOPEndTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),"; + } + strSQL = strSQL + " OPStatus = 0 Where LotNo = '" + LotNo + "'"; + CollectionSQL.Add(strSQL); + + // 執行本站結束的相關處理,站中才須處理 + decimal decGoodQty = default(decimal), decFailQty = default(decimal), decLossQty = default(decimal); + if (intOPStatus == 1) + { + // 檢查是否已有產出 + string strGoodUnitNo = ""; + + objLot.SHR_CalOutput(ref cnnTemp, ref decGoodQty, ref decFailQty, ref decLossQty, ref strGoodUnitNo, LogGroupSerial, (decimal)CurQty, CurUnitNo); + + // 結算工時. + decimal FinalGoodQtyTmp = defInteger, FinalFailQtyTmp = defInteger; + objLot.EndOP(ref FinalGoodQtyTmp, ref FinalFailQtyTmp, LotNo, LotSerial, DateTime.Now, CollectionSQL, UserNo, true, EventDescription: "测试工序入不良品仓", GoodQty: 0m, FailQty: decGoodQty + decFailQty, LossQty: decLossQty, UnitNo: strGoodUnitNo, CalculateEMP: true); + } + else + { + // 由EndModule內自行處理 + decGoodQty = defInteger; + decFailQty = defInteger; + } + + // 不正常結束,CompleteFlag=0. + if (intOPReference == 1) + { + if (decGoodQty == defInteger) + { + objLot.EndModule(LotNo, LotSerial, DateTime.Now, CollectionSQL, EventUserNo: UserNo, EventDescription: "测试工序入不良品仓", CompleteFlag: 0, UnUpdateFailQty: (decimal)CurQty, FinalGoodQty: 0m); + } + else + { + objLot.EndModule(LotNo, LotSerial, DateTime.Now, CollectionSQL, EventUserNo: UserNo, EventDescription: "测试工序入不良品仓", CompleteFlag: 0, UnUpdateFailQty: decGoodQty + decFailQty, FinalGoodQty: 0m); + } + } + + // 2017/09/25 YF, 叫用工單達交率處理者,判斷是否回寫實際完工日 + // 2020/03/17 OwenLiu, Mantis:0068929 工單實際開工日/工單實際完工日 調整還原機制的共用處理 + new kcOE.WorkOrderRateHandler().ActualFinishDateProcess(pLotNo: LotNo, pLotSerial: LotSerial , pEventTime: DateTime .Now , pCollectionSQL: CollectionSQL, objReverse: objReverse); + //(xg)20260722 + if (errorcode != "") + { + //更改表TBLPCSDIELOG_LQ + strSQL = $"update TBLPCSDIELOG_LQ set BADFLAG = 1,REASONNO = '{errorcode}' where unitid='{dicPars["unitid"].ToString()}'"; + CollectionSQL.Add(strSQL); + //更改表TBLPCSDIELOG_LQ + strSQL = $"update tblwipprdstate_LQ set STATE=2 where LOTNO='{LotNo}' AND state= 1"; + CollectionSQL.Add(strSQL); + } + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + else if (dicPars["result"].ToString().ToUpper() == "FAIL") + { + strSQL = $@"select * from TBLCUSTESTOPRESULT where lotno ='{LotNo }' and opno ='{OPNO }' and eqpid='{dicPars["eqp_id"]}'"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLCUSTESTOPRESULT", cnnTemp); + if (dsTemp.Tables["TBLCUSTESTOPRESULT"].Rows.Count + 1 < int.Parse(drTemp["DefaultValue"].ToString())) + { + Collection CollectionSQL = new Collection(); + //走cycle节点,回到原站点 + strSQL = $@"INSERT INTO TBLCUSTESTOPRESULT(ErrorNo,ReasonName,LOTNO,OPNO,EQPID,RESULT,TESTTIME) VALUES('{errorcode}','{errorvalue}','{dicPars["lotno"]}','{dicPars["opno"]}','{dicPars["eqp_id"]}','{dicPars["result"]}',To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'))"; + CollectionSQL.Add(strSQL); + + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + Execute_CO_LOTRet = Convert.ToString(AutoexecutionLot_Lot_CS(ref blnEXETriggerOP, dicPars, dicPars_DataTable, strFunctionID, datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck), "CYCLE")); + } + else + { + // 1. 检查字典中是否存在这个key + if (dicPars_DataTable.ContainsKey("lotattrib")) + { + if (dicPars_DataTable["lotattrib"] != null) + { + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='GoodQty'")[0]["ATTRIBVALUE"] = 0; + } + + if (dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'").Length > 0) + { + dicPars_DataTable["lotattrib"].Select("ATTRIBNO='DefectQty'")[0]["ATTRIBVALUE"] = CurQty; + } + } + } + //直接入不良品库 + Collection CollectionSQL = new Collection(); + //直接入不良品库 + strSQL = "Insert into tblINVWIP_Scrap(LogGroupSerial,InventoryNo,LotSerial,LotNo,OPNo,UnitNo,ScrapQty,LossQty,BaseLotNo, InputDate)" + " Values ('" + LogGroupSerial + "','" + InventoryNo + "','" + LotSerial + "', '" + LotNo + "','" + OPNO + "','" + CurUnitNo + "'," + CurQty + ",0,'" + BaseLotNo + "'," + " To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + ")"; + CollectionSQL.Add(strSQL); + // 加入ReverseUpdateContent + strSQL = "Delete From tblINVWIP_Scrap Where LotSerial='" + LotSerial + "'"; + Collection argcolSQL_Rows9 = null; + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows9); + + // 變更LotSate + // 2012/02/22,新增GoLinkName + strSQL = "Update tblWIPLotState Set LotSerial = '" + LotSerial + "'," + " Status = 12 ," + " GoStatus = null , " + " GoLinkName = null , " + " EventTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + " EventUserNo='" + UserNo + "'," + " EventDescription='测试工序入不良品仓'," + " ArriveTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),"; + if (intOPStatus == 1) // 站中Wait才須給EndTime + { + strSQL = strSQL + " PreOPEndTime = To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),"; + } + strSQL = strSQL + " OPStatus = 0 Where LotNo = '" + LotNo + "'"; + CollectionSQL.Add(strSQL); + + // 執行本站結束的相關處理,站中才須處理 + decimal decGoodQty = default(decimal), decFailQty = default(decimal), decLossQty = default(decimal); + if (intOPStatus == 1) + { + // 檢查是否已有產出 + string strGoodUnitNo = ""; + + objLot.SHR_CalOutput(ref cnnTemp, ref decGoodQty, ref decFailQty, ref decLossQty, ref strGoodUnitNo, LogGroupSerial, (decimal)CurQty, CurUnitNo); + + // 結算工時. + decimal FinalGoodQtyTmp = defInteger, FinalFailQtyTmp = defInteger; + objLot.EndOP(ref FinalGoodQtyTmp, ref FinalFailQtyTmp, LotNo, LotSerial, DateTime.Now, CollectionSQL, UserNo, true, EventDescription: "测试工序入不良品仓", GoodQty: 0m, FailQty: decGoodQty + decFailQty, LossQty: decLossQty, UnitNo: strGoodUnitNo, CalculateEMP: true); + } + else + { + // 由EndModule內自行處理 + decGoodQty = defInteger; + decFailQty = defInteger; + } + + // 不正常結束,CompleteFlag=0. + if (intOPReference == 1) + { + if (decGoodQty == defInteger) + { + objLot.EndModule(LotNo, LotSerial, DateTime.Now, CollectionSQL, EventUserNo: UserNo, EventDescription: "测试工序入不良品仓", CompleteFlag: 0, UnUpdateFailQty: (decimal)CurQty, FinalGoodQty: 0m); + } + else + { + objLot.EndModule(LotNo, LotSerial, DateTime.Now, CollectionSQL, EventUserNo: UserNo, EventDescription: "测试工序入不良品仓", CompleteFlag: 0, UnUpdateFailQty: decGoodQty + decFailQty, FinalGoodQty: 0m); + } + } + + // 2017/09/25 YF, 叫用工單達交率處理者,判斷是否回寫實際完工日 + // 2020/03/17 OwenLiu, Mantis:0068929 工單實際開工日/工單實際完工日 調整還原機制的共用處理 + new kcOE.WorkOrderRateHandler().ActualFinishDateProcess(pLotNo: LotNo, pLotSerial: LotSerial, pEventTime: DateTime.Now, pCollectionSQL: CollectionSQL, objReverse: objReverse); + //(xg)20260722 + if (errorcode != "") + { + //更改表TBLPCSDIELOG_LQ + strSQL = $"update TBLPCSDIELOG_LQ set BADFLAG = 1,REASONNO = '{errorcode}' where unitid='{dicPars["unitid"].ToString()}'"; + CollectionSQL.Add(strSQL); + //更改表TBLPCSDIELOG_LQ + strSQL = $"update tblwipprdstate_LQ set STATE=2 where LOTNO='{LotNo}' AND state= 1"; + CollectionSQL.Add(strSQL); + } + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + } + else if (dicPars["result"].ToString().ToUpper() == "PASS") + { + Collection CollectionSQL = new Collection(); + strSQL = $@"INSERT INTO TBLCUSTESTOPRESULT(LOTNO,OPNO,EQPID,RESULT,TESTTIME) VALUES('{dicPars["lotno"]}','{dicPars["opno"]}','{dicPars["eqp_id"]}','{dicPars["result"]}',To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'))"; + CollectionSQL.Add(strSQL); + + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + //正常出站 + Execute_CO_LOTRet = Convert.ToString(AutoexecutionLot_Lot_CS(ref blnEXETriggerOP, dicPars, dicPars_DataTable, strFunctionID, datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck))); + } + } + else + { + Execute_CO_LOTRet = Convert.ToString(AutoexecutionLot_Lot_CS(ref blnEXETriggerOP, dicPars, dicPars_DataTable, strFunctionID, datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck))); + } + drTemp.Close(); + + return Execute_CO_LOTRet; + } + + // 0102096: [6.0.5] EAP自動報工架構_SDD210906_05-01/ Execute_CI_LOT + public object AutoexecutionLot_Lot_CS(ref bool blnEXETriggerOP, Dictionary dicPars, Dictionary dicPars_DataTable, string FunctionID, DateTime ArriveTime, string UserNo, string ComputerName, bool blnRuleCheck = true, string LinkName = defString) + { + object AutoexecutionLot_LotRet = default(object); + var dtLotState = new DataTable(); // Load Afer TriggerOP + var objLot = new clsLot(); + var objSYS = new clsSYSUserLog(); + var objWIP = new kcWIP.clsWIP(); + var objUSR = new iMESUserManager.clsUSRSecurity(); + var objclsWIP = new clsWIP(); + var objEMS = new kcEMS.clsEMSEquipment(); + var objReverse = new udReverse.clsReverse(); + DataRow drAdd; + IDbConnection cnnTemp = null; + var drTemp = default(DbDataReader); + //OleDbCommand cmmTemp; + AppSettings objSetting = new AppSettings(); + + string strException; + string strResult; + int PhaseNo; + string AreaNo = defString; + string OPNo = defString; + string PSNo = defString; + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); // Create connection + + string strServiceName = "ExecuteLot"; + + + var dtLotNo = new DataTable(); + dtLotNo.Columns.Add("LotNo", System.Type.GetType("System.String")); + var drLotAdd = dtLotNo.NewRow(); + drLotAdd["LotNo"] = dicPars["lotno"]; + dtLotNo.Rows.Add(drLotAdd); + string LotNo = dtLotNo.Rows[0]["LotNo"].ToString(); + + string InXML = ""; + string OutXML = ""; + + string strRetrunMsg = ""; + + var dtChkRuleLot2 = new DataTable("ChkRuleLot"); // minya 20200315 + string strEquipmentNo = defString; + string strERFMsg = ""; + try + { + + // 1.依InXml資料與Lot目前狀態比對是否符合 + DataRow drLotState = null; + var strKernelModule = default(string); + var strKernelFunctionName = default(string); + + // 檢查USER過帐权限 + DataRow drUser; + if (!string.IsNullOrEmpty(UserNo)) + { + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + UserNo = "EAP_AGENT"; + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + throw new iMESException.MESException("0000-200015", "[%Please provide curuser or set EAP_Agent correct, then execute Lot%] !"); + } + } + } + else + { + UserNo = "EAP_AGENT"; + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + throw new iMESException.MESException("0000-200015", "[%Please provide curuser or set EAP_Agent correct, then execute Lot%] !"); + } + } + + strEquipmentNo = dicPars["eqp_id"]; + + // 2.取得生產批現況資訊 + string refBRNO = defString; + string refBRExecutionFile = defString; + + string strLots = "("; + foreach (DataRow drTempLotNo in dtLotNo.Rows) + strLots += "'" + drTempLotNo["LotNo"].ToString() + "',"; + strLots = strLots.TrimEnd(','); + strLots += ")"; + + if (tcEAI.clsEAP.funLoadLotStatusJoinOPBusinessRule(strLots, ref dtLotNo) < 0) + { + throw new iMESException.MESException("0000-200091", "[%funLoadLotStatusJoinOPBusinessRule fail%]!"); + } + if (!(dtLotNo == null) && dtLotNo.Rows.Count > 0) // 取出區域與作業站 + { + OPNo = dtLotNo.Rows[0]["OPNo"].ToString(); + AreaNo = dtLotNo.Rows[0]["AreaNo"].ToString(); + PSNo = dtLotNo.Rows[0]["PSNo"].ToString(); + } + + // 檢查User是否有此OP的權限------------------------------------------------------------------------------------------------ + // Gary Lu 20121114:這個作業站不在群組內才要進行權限檢查 + if (objUSR.ChkUserOPPriv(UserNo, OPNo) == false) + { + throw new iMESException.MESException("0000-202015", "[%UserNo%]:" + UserNo + "[%NOTHINGSTATE%][%OPPRIVILEGE%], [%OPNo%]:" + OPNo); + } + + // 檢查User是否有產品區段設定權限------------------------------------------------------------------------------------------------ + if (objUSR.ChkUserPSPriv(UserNo, PSNo) == false) + { + throw new iMESException.MESException("0000-200062", "[%EmployeeNo%]:" + UserNo + "[%has no PS Privilege%], [%PSNo%]:" + PSNo); + } + + objUSR = null; + + // 6.取得班別 + string ShiftNo = "N/A"; + using (var obj = new clsUSRDepartment()) + { + ShiftNo = obj.GetShift(UserNo); + } + + // 0 : Sucess + // -1 : Program Error + // -2 : LotInfo Error + // -3 : Each Lot Has Different BR + // -4 : RefLotNo Didn't Setting KERNELMODULE(tblOPBusinessRuleBasis) + // -5 : RefLotNo Didn't Setting KERNELFUNCTIONNAME(tblOPBusinessRuleBasis) + // -6 : LotStatus Error + switch (tcEAI.clsEAP.ChkLotStateAndBRNo(strLots, FunctionID, OPNo)) + { + case -1: + { + throw new iMESException.MESException("0000-200091", "[%ChkLotStateAndBRNo fail%]!"); + } + case -2: + { + throw new iMESException.MESException("0000-200091", "[%LotNo And OPNo fail!%]"); + } + case -3: + { + throw new iMESException.MESException("0000-200091", "[%Each Lot Has Different BR%]"); + } + case -4: + { + throw new iMESException.MESException("0000-200091", "[%RefLotNo%] " + LotNo + "; [%Not Setting KERNELMODULE(tblOPBusinessRuleBasis)%]"); + } + case -5: + { + throw new iMESException.MESException("0000-200091", "[%RefLotNo%] " + LotNo + "; [%Not Setting KERNELFUNCTIONNAME(tblOPBusinessRuleBasis)%]"); + } + case -6: + { + throw new iMESException.MESException("0000-200091", "[%LotStatus Error%]"); + } + } + + foreach (DataRow drTempLotNo in dtLotNo.Rows) + { + if (dtLotNo.Rows.IndexOf(drTempLotNo) == 0) + { + refBRNO = drTempLotNo["BRNO"].ToString(); + refBRExecutionFile = drTempLotNo["EXECUTIONFILE"].ToString(); + } + else if (drTempLotNo["BRNO"].ToString() != refBRNO) + { + // LotBR 與首批不一致 + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + drTempLotNo["LotNo"].ToString() + " [%BR%] [%Is Not THE SAME%]"); + } + + funCheckStateByLot(ref strKernelModule, ref strKernelFunctionName, drTempLotNo["LotNo"].ToString(), drTempLotNo, FunctionID, OPNo); + } + + if (FunctionID == "CO") + { + if (refBRExecutionFile.ToUpper() != "BR_L_CO_GEN.DLL" && refBRExecutionFile.ToUpper() != "BR_L_CO_GEN_M.DLL") + { + //0156845: [6.0.7]调整EAP接口查核支援BR逻辑,增加查核brno + if (!tcEAI.clsEAP.ExeBrnoIfSupport(refBRExecutionFile.ToUpper(), refBRNO)) + { + throw new iMESException.MESException("0000-200091", "[%Only Support L_CO_GEN Now%] [%NOWUSE%]:" + refBRNO + ""); + } + + } + } + else if (refBRExecutionFile.ToUpper() != "BR_L_CI_GEN.DLL" && refBRExecutionFile.ToUpper() != "BR_L_CI_GEN_M.DLL") + { + //0156845: [6.0.7]调整EAP接口查核支援BR逻辑,增加查核brno + if (!tcEAI.clsEAP.ExeBrnoIfSupport(refBRExecutionFile.ToUpper(), refBRNO)) + { + throw new iMESException.MESException("0000-200091", "[%Only Support L_CI_GEN Now%] [%NOWUSE%]:" + refBRNO + ""); + } + } + + // 3.Execution Trigger OP + if (!dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + using (var dcTemp = new DataColumn()) + { + dcTemp.ColumnName = "blnEXETriggerOP"; + dcTemp.DataType = Type.GetType("System.Boolean"); + dcTemp.DefaultValue = false; + dtLotNo.Columns.Add(dcTemp); + } + } + + foreach (DataRow drTempLot in dtLotNo.Rows) + { + // If drTempLot("Status") = 0 Then + string DescriptionTmp = defString; + long NewLotStampTmp = defInteger; + switch (objLot.TriggerOP(ref DescriptionTmp, ref NewLotStampTmp, Convert.ToString(drTempLot["LotNo"]), UserNo: UserNo)) + { + + case "hold_exceedtime": + { + tcEAI.clsWIP.BRERFCreateExecute(pUserId: UserNo, pLotNo: Convert.ToString(drTempLot["LotNo"]), pERFType: 1, pHoldTime: 0, pRuleNo: "EXCEEDTIME"); + throw new iMESException.MESException("0000-200091", "LotNO:" + + drTempLot["LotNo"] + "[%VIOLATE TIME CONTROL,CREATE ERF%]!"); + } + case "futurehold": + { + tcEAI.clsWIP.BRERFCreateExecute(pUserId: UserNo, pLotNo: Convert.ToString(drTempLot["LotNo"]), pERFType: 3, pHoldTime: 0); + throw new iMESException.MESException("0000-200091", "LotNO:" + + drTempLot["LotNo"] + "[%FUTUREHOLD SET,CREATE ERF%]!"); + } + case "futurewait": + { + throw new iMESException.MESException("0000-200091", "LotNO:" + drTempLot["LotNo"] + "[%FUTUREWAIT%]!"); + } + case "futureos": + { + throw new iMESException.MESException("0000-200091", "LotNO:" + drTempLot["LotNo"] + "[%FUTURE OS%]!"); + } + + default: + { + // 2020/03/11 Shih Kai, 68676 :自动进出站BR检核-TriggerOP後增加補做TriggerPhase + // Trigger Phase + drLotState = objLot.GetLotBasisJoinState(LotNo: drTempLot["LotNo"].ToString()); // 取得最新的LotState + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 0, false))) // by Product + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ProductNo"].ToString(), drLotState["ProductVersion"].ToString(), drLotState["OPNo"].ToString(), drLotState["BRNo"].ToString()); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 1, false))) // by Module + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ModuleNo"].ToString(), drLotState["ModuleVersion"].ToString(), drLotState["OPNo"].ToString(), drLotState["BRNo"].ToString()); + } + else + { + throw new iMESException.MESException("0000-200015", "LotNo:" + + drTempLot["LotNo"] + ",[%OPREFERENCE ERROR%]!"); + } + + // 剛做完TriggerOP,不用再執行Attrib的變更 + objLot.TriggerPhase_LotState(Convert.ToString(drTempLot["LotNo"]), PhaseNo, UserNo); + + drTempLot["blnEXETriggerOP"] = true; + break; + } + } + } + + var drLotRow = objLot.GetLotBasisJoinState(LotNo: LotNo); // 取得最新的LotState + + string strLotStamp = drLotRow["LotStamp"].ToString(); + string strLotSerial = drLotRow["LotSerial"].ToString(); + string strLogGroupSerial = drLotRow["LogGroupSerial"].ToString(); + int intPhaseNo = Conversions.ToInteger(drLotRow["PhaseNo"]); + + blnEXETriggerOP = true; + + // 4.ReLoad Lotstate Afer Trigger OP In dtLotState + tcEAI.clsEAP.funLoadLotStatusJoinOPBusinessRule(strLots, ref dtLotState); + + + // 20200309 Edison Mantis : 68289: [SEMI WAFER]通用性CI/CO BR檢核 + // 區域設備檢核 Key in Lot Attrib檢核 Component Attrib檢核, Check Control Rule + // =============================================== 68289 Start =============================================== + + // 5.Xml轉Table + DataTable dtLotList = new DataTable(), dtLotAttrib = new DataTable(), dtLotError = new DataTable(), dtLotComponent = new DataTable(), dtLotCompAttrib = new DataTable(), dtEquipment = new DataTable(), dtTempAttrib = new DataTable(), dtComponentError = new DataTable(); + DataTable dtAccessory = null; + + // 將批號加入資料表以便檢查設備 + dtLotList.Columns.Add("LotNo"); + DataRow drLotNo; + drLotNo = dtLotList.NewRow(); + drLotNo["LotNo"] = LotNo; + dtLotList.Rows.Add(drLotNo); + + if (dicPars_DataTable.Keys.Contains("lotattrib")) + { + //查询当前的作业站的属性中是否有【测试工序】属性,若有的话,将socketid存到进站的参数中,执行进站逻辑。 + string strSQL = "SELECT * FROM TBLOPPROPERTY WHERE ISSUESTATE=2 AND PROPERTYNO='测试工序' AND OPNO='" + OPNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + dtLotAttrib = dicPars_DataTable["lotattrib"]; + } + drTemp.Close(); + } + + if (dicPars_DataTable.Keys.Contains("loterror")) + { + dtLotError = dicPars_DataTable["loterror"]; + } + + if (dicPars_DataTable.Keys.Contains("lotcompoment")) + { + dtLotComponent = dicPars_DataTable["lotcompoment"]; + } + if (dicPars_DataTable.Keys.Contains("lotcomponentattrib")) + { + dtLotCompAttrib = dicPars_DataTable["lotcomponentattrib"]; + } + + if (dicPars_DataTable.Keys.Contains("equipment")) + { + dtEquipment = dicPars_DataTable["equipment"]; + } + else + { + dtEquipment.Columns.Add("EquipmentNo"); + DataRow drEQP; + drEQP = dtEquipment.NewRow(); + drEQP["EquipmentNo"] = strEquipmentNo; + dtEquipment.Rows.Add(drEQP); + } + + if (dicPars_DataTable.Keys.Contains("tempattrib")) + { + dtTempAttrib = dicPars_DataTable["tempattrib"]; + } + if (dicPars_DataTable.Keys.Contains("componenterror")) + { + dtComponentError = dicPars_DataTable["componenterror"]; + } + if (dicPars_DataTable.Keys.Contains("accessorylist")) + { + dtAccessory = dicPars_DataTable["accessorylist"]; + } + + if (dtAccessory == null) + { + dtAccessory = objEMS.LoadEQPACCStateJoinAccState_EAP(EquipmentNo: strEquipmentNo); + } + + string strCANodeName, strComponentNodeName; + string strLinkName = "PASS"; + string strMailGroupNo = ""; + string strMsg = ""; + string strRuleNo = defString; + int intERFType = 0; + DataTable dtLotRuleData = default(DataTable); + //DataTable dtLotRuleData = default(DataTable), dtCompRuleData = default(DataTable); + + var dtLotAttrib_Temp = new DataTable(); + //dtLotAttrib_Temp.Columns.Add("LotNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("AttribNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("AttribType", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribSequence", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribSource", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribPhase", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribValue", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("SaveToLotPropertyNo", Type.GetType("System.String")); + // 2021/12/1 缺少QCItemNo,於標準BRcheckin會出錯 + dtLotAttrib_Temp.Columns.Add("TestValue", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("Result", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("Result_INT", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("FactorSerial", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("SerialNo", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("MEMO", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("ComponentNo", Type.GetType("System.String")); + // SPC + dtLotAttrib_Temp.Columns["TestValue"].Expression = "AttribValue"; + + var dtLotCompAttrib_Temp = new DataTable(); + dtLotCompAttrib_Temp.Columns.Add("LotNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("ComponentNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribValue", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribType", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribSequence", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribSource", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribPhase", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("SaveToLotPropertyNo", Type.GetType("System.String")); + + if (blnRuleCheck) + { + + // 預設 + strCANodeName = "componentattrib"; + strComponentNodeName = "component"; + // Call XmlToTable(InXML, dtEquipment, dtLotList, dtLotAttrib, dtLotError, dtLotComponent, dtLotCompAttrib, strLots, LotNo, strCANodeName, strComponentNodeName, refBRNO) 'refBRNO minya 20200312 + + // dtLotAttrib若不包含欄位:LotNo,會出錯誤 + if (!(dtLotAttrib == null)) + { + if (!dtLotAttrib.Columns.Contains("LotNo")) + { + dtLotAttrib.Columns.Add("LotNo"); + if (!(dtLotNo == null) && dtLotNo.Rows.Count > 0) + { + foreach (DataRow dr in dtLotAttrib.Rows) + dr["LotNo"] = dtLotNo.Rows[0]["LotNo"].ToString(); + } + } + } + // 6. 基本檢查 + funBasisCheck(CIorCO: FunctionID, dtLotNo: dtLotNo, dtEquipment: dtEquipment, dtLotList: dtLotList, dtLotAttrib: dtLotAttrib, dtLotError: dtLotError, dtLotComponent: dtLotComponent, dtLotCompAttrib: dtLotCompAttrib, dtTempAttrib: ref dtTempAttrib, strLots: strLots); + + // 7.格式化Rule Check 資料 並進行ChkControlRule---------------------------------------------------------------------------------------------- + string strBatchComponent = ""; + string strAttrib = ""; + string strCAttrib = ""; + string strError = ""; + string strTemp = ""; + + // 7.1 需要判 Rule 的生產批 + var dtChkRuleLot = new DataTable("ChkRuleLot"); + string strRuleLot = ""; + dtChkRuleLot.Columns.Add("LotNo", Type.GetType("System.String")); + + foreach (DataRow rL in dtLotNo.Rows) + { + strRuleLot += CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rL["LotNo"].ToString()))); + dtChkRuleLot.Rows.Add(rL["LotNo"].ToString()); + } + + // 7.2 格式化資料Component + foreach (DataRow rC in dtLotComponent.Rows) + { + strBatchComponent += CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rC["LotNo"].ToString())) + + CombineXMLValue("componentno", CInput(rC["ComponentNo"].ToString()))); + } + + // 7.3 格式化-Key In Attrib + // KeyIn Attrib + //20240102,13871,0155146: [6.0.7]EAP接口Execute_CO_LOT,出站输入特性参数时,EAP和产品作业站输入一致,但是会提示报错 + DataTable attribtemp = null; + using (var obj = new clsLot()) + { + attribtemp = obj.ShowTemp_Attrib(LotNo).Tables[0]; + } + //foreach (DataRow rLA in dtLotAttrib.Rows) + //{ + // for (int x = 0, loopTo = attribtemp.Rows.Count - 1; x <= loopTo; x++) + // { + // if (rLA["AttribNo"].ToString() == attribtemp.Rows[x]["AttribNo"].ToString()) + // { + // attribtemp.Rows[x]["AttribValue"] = rLA["AttribValue"].ToString(); + // } + // } + //} + //20240102,13871,0155146,註解此 + //for (var i = 0; i < dtLotAttrib_Temp.Rows.Count - 1; i++) + //{ + // for (var j = 0; j < attribtemp.Rows.Count - 1; j++) + // { + // if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(attribtemp.Rows[j]["AttribNo"], dtLotAttrib_Temp.Rows[i]["AttribNo"], false))) + // { + // attribtemp.Rows[j]["AttribValue"] = CInput(dtLotAttrib_Temp.Rows[i]["AttribValue"].ToString()); + // } + // } + //} + //dtLotAttrib_Temp.Clear(); + //for (var p = 0; p < attribtemp.Rows.Count; p++) + //{ + // strAttrib = strAttrib + CombineXMLValueTag( + // CombineXMLValue("lotno", LotNo) + + // CombineXMLValue("attribno", CInput(attribtemp.Rows[p]["AttribNo"].ToString())) + + // CombineXMLValue("attribtype", attribtemp.Rows[p]["AttribType"].ToString()) + + // CombineXMLValue("attribsequence", attribtemp.Rows[p]["AttribSequence"].ToString()) + + // CombineXMLValue("attribsource", attribtemp.Rows[p]["AttribSource"].ToString()) + + // CombineXMLValue("attribphase", attribtemp.Rows[p]["AttribPhase"].ToString()) + + // CombineXMLValue("attribvalue", CInput(attribtemp.Rows[p]["AttribValue"].ToString())) + + // CombineXMLValue("savetolotpropertyno", CInput(attribtemp.Rows[p]["SaveToLotPropertyNo"].ToString())) + + // CombineXMLValue("qcitemno", CInput(attribtemp.Rows[p]["QCItemNo"].ToString()))); + // DataRow drTemp_Rows; + // drTemp_Rows = dtLotAttrib_Temp.NewRow(); + // drTemp_Rows["LotNo"] = LotNo; + // drTemp_Rows["AttribNo"] = attribtemp.Rows[p]["AttribNo"]; + // drTemp_Rows["AttribType"] = attribtemp.Rows[p]["AttribType"]; + // drTemp_Rows["AttribSequence"] = attribtemp.Rows[p]["AttribSequence"]; + // drTemp_Rows["AttribSource"] = attribtemp.Rows[p]["AttribSource"]; + // drTemp_Rows["AttribPhase"] = attribtemp.Rows[p]["AttribPhase"]; + // drTemp_Rows["AttribValue"] = attribtemp.Rows[p]["AttribValue"].ToString(); + // drTemp_Rows["SaveToLotPropertyNo"] = attribtemp.Rows[p]["SaveToLotPropertyNo"]; + // drTemp_Rows["QCItemNo"] = attribtemp.Rows[p]["QCItemNo"]; + // dtLotAttrib_Temp.Rows.Add(drTemp_Rows); + //} + + if (!(attribtemp == null)) + { + attribtemp.DefaultView.RowFilter = "(AttribPhase = " + intPhaseNo + " or AttribPhase = 99) And AttribSource <> 0"; // CurPhase & All的所有Attrib,除了KeyIn + for (int i = 0; i <= attribtemp.DefaultView.Count - 1; i++) + { + strTemp = CombineXMLValue("lotno", LotNo) + + CombineXMLValue("attribno", CInput(attribtemp.DefaultView[i]["AttribNo"].ToString())) + + CombineXMLValue("attribtype", attribtemp.DefaultView[i]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", attribtemp.DefaultView[i]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", attribtemp.DefaultView[i]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", attribtemp.DefaultView[i]["AttribPhase"].ToString()) + + CombineXMLValue("savetolotpropertyno", CInput(attribtemp.DefaultView[i]["SaveToLotPropertyNo"].ToString())); + if (attribtemp.DefaultView[i]["AttribValue"] is DBNull) + strTemp += CombineXMLValue("attribvalue", ""); + else + strTemp += CombineXMLValue("attribvalue", CInput(attribtemp.DefaultView[i]["AttribValue"].ToString())); + strAttrib += CombineXMLValueTag(strTemp); + } + //還原顯示 + attribtemp.DefaultView.RowFilter = "AttribSource <> 0 And AttribSource <> 1 And (AttribPhase = " + intPhaseNo + " or AttribPhase = 99)"; // Source = Not KeyIn, Not Calculate ,CurPhase and All + + //Temp:Attrib_KeyIn + for (int i = 0; i <= dtLotAttrib.Rows.Count - 1; i++) + { + if (dtLotAttrib.Rows[i]["AttribValue"] is DBNull) + dtLotAttrib.Rows[i]["AttribValue"] = ""; + + DataRow[] drChk = attribtemp.Select("AttribNo='" + dtLotAttrib.Rows[i]["AttribNo"] + "'"); + if (drChk.Length == 0) + { + throw new iMESException.MESException("0000-203010", "[%AttribNo%]:" + dtLotAttrib.Rows[i]["AttribNo"].ToString()); + } + else + { + strTemp = CombineXMLValue("lotno", LotNo) + + CombineXMLValue("attribno", CInput(dtLotAttrib.Rows[i]["AttribNo"].ToString())) + + CombineXMLValue("attribtype", drChk[0]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", drChk[0]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", drChk[0]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", drChk[0]["AttribPhase"].ToString()) + + CombineXMLValue("attribvalue", CInput(dtLotAttrib.Rows[i]["AttribValue"].ToString())) + + CombineXMLValue("savetolotpropertyno", CInput(drChk[0]["SaveToLotPropertyNo"].ToString())); + if (drChk[0]["QCItemNo"] is DBNull) + strTemp += CombineXMLValue("qcitemno", ""); + else + strTemp += CombineXMLValue("qcitemno", CInput(drChk[0]["QCItemNo"].ToString())); + + SaveLog1(strTemp, @"D:\MESLog\Execute_CO_LOT"); + + strAttrib += CombineXMLValueTag(strTemp); + } + } + } + + + // 7.4.格式化 Component Attrib + foreach (DataRow rCA in dtLotCompAttrib.Rows) + { + DataSet dsTemp; + using (var obj = new clsLot()) + { + dsTemp = obj.ShowTemp_ComponentAttrib(LotNo); + } + + for (int x = 0, loopTo1 = dsTemp.Tables[0].Rows.Count - 1; x <= loopTo1; x++) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(rCA["AttribNo"], dsTemp.Tables[0].Rows[x]["AttribNo"], false))) + { + strCAttrib = strCAttrib + CombineXMLValueTag( + CombineXMLValue("lotno", LotNo) + + CombineXMLValue("componentno", CInput(dsTemp.Tables[0].Rows[x]["ComponentNo"].ToString())) + + CombineXMLValue("attribno", CInput(rCA["AttribNo"].ToString())) + + CombineXMLValue("attribtype", dsTemp.Tables[0].Rows[x]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", dsTemp.Tables[0].Rows[x]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", dsTemp.Tables[0].Rows[x]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", dsTemp.Tables[0].Rows[x]["AttribPhase"].ToString()) + + CombineXMLValue("attribvalue", CInput(rCA["AttribValue"].ToString())) + + CombineXMLValue("savetolotpropertyno", CInput(dsTemp.Tables[0].Rows[x]["SaveToLotPropertyNo"].ToString()))); + + DataRow drTemp_Rows; + drTemp_Rows = dtLotCompAttrib_Temp.NewRow(); + drTemp_Rows["LotNo"] = LotNo; + drTemp_Rows["ComponentNo"] = dsTemp.Tables[0].Rows[x]["ComponentNo"]; + drTemp_Rows["AttribNo"] = rCA["AttribNo"]; + drTemp_Rows["AttribType"] = dsTemp.Tables[0].Rows[x]["AttribType"]; + drTemp_Rows["AttribSequence"] = dsTemp.Tables[0].Rows[x]["AttribSequence"]; + drTemp_Rows["AttribSource"] = dsTemp.Tables[0].Rows[x]["AttribSource"]; + drTemp_Rows["AttribPhase"] = dsTemp.Tables[0].Rows[x]["AttribPhase"]; + drTemp_Rows["AttribValue"] = rCA["AttribValue"].ToString(); + drTemp_Rows["SaveToLotPropertyNo"] = dsTemp.Tables[0].Rows[x]["SaveToLotPropertyNo"]; + dtLotCompAttrib_Temp.Rows.Add(drTemp_Rows); + } + } + } + + // 7.5 格式化不良原因 + foreach (DataRow rE in dtLotError.Rows) + { + strError = strError + CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rE["LotNo"].ToString())) + + CombineXMLValue("componentno", CInput(rE["ComponentNo"].ToString())) + + CombineXMLValue("errorno", CInput(rE["ErrorNo"].ToString())) + + CombineXMLValue("errorqty", rE["ErrorQty"].ToString()) + + CombineXMLValue("errorlevel", rE["ErrorLevel"].ToString())); + } + + // 7.6 Control Rule Check------------------------------------------------------------------------------------------------------------- + DataSet dsTestValue = null; + + //if (ChkControlRule_BatchComponent(dtChkRuleLot, true, UserNo, strRuleLot, strBatchComponent, ref strAttrib, ref strCAttrib, ref strLinkName, ref strMsg, ref strRuleNo, ref intERFType, ref dtLotRuleData, ref dtCompRuleData, ref strMailGroupNo, ref dsTestValue, strError) < 0) + if (tcEAI.clsEAP.ChkControlRule(ref dsTestValue, ref dtChkRuleLot, LotNo, UserNo, Conversions.ToLong(strLotStamp), ref strAttrib, ref strLinkName, ref strMsg, ref strRuleNo, ref intERFType, ref strMailGroupNo, strError) < 0) + + { + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + LotNo + ",Check Control Rule [%FUNCTION%][%Fail%]."); + } + + // Check SPC Contorl + if (funChkSPCControl_Var(UserNo, LotNo, ref strAttrib, dsTestValue, ref strLinkName, ref intERFType, ref strERFMsg, dtEquipment) < 0) + { + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + LotNo + ",Check SPC Contorl [%FUNCTION%][%Fail%]."); + } + strERFMsg = tcEAI.clsEAP.TranslateMsg(strERFMsg); + + //strAttrib to dtLotAttrib_Temp + dtLotAttrib_Temp = ConvertXmlToDataTable(dtLotAttrib_Temp, strAttrib); + + // 取得RuleNo + DataRow[] drSelHoldRule; + if (!(dtLotRuleData == null) && dtLotRuleData.Rows.Count > 0) + { + if (strLinkName == "HOLD") + { + drSelHoldRule = dtLotRuleData.Select("Linkname= 'HOLD'"); + if (drSelHoldRule.Length > 0) + { + strRuleNo = drSelHoldRule[0]["RuleNo"].ToString(); + } + } + } + + // 2020/03/12 Lena, 將 InXml 中的 LiknName、Lot Attrib、Component Attrib 置換為 Control Rule Check 後的結果 + string strLinkNameTagName = "linkname".ToLower(); + string strLAttribTagName = "attrib".ToLower(); + string strCAttribTagName = strCANodeName.ToLower(); + + int intStartIndex, intEndIndex; + string strHand, strLast, strChang; + string strInXml = InXML; + DataRow[] drSel; + + // LinkName + if (!string.IsNullOrEmpty(strLinkName)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strLinkNameTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLinkNameTagName.Length + 3); + string argname = "LinkName"; + string argtype = "String"; + string argdesc = ""; + strChang = CombineXMLParameter(strLinkNameTagName, argname, argtype, strLinkName, argdesc); + strInXml = strHand + strChang + strLast; + } + } + + // Lot Attrib + if (!string.IsNullOrEmpty(strAttrib)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strLAttribTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLAttribTagName.Length + 3); // strLAttribTagName.Length + 3 = 的長度 + string argtype1 = "String"; + string argdesc1 = ""; + strChang = CombineXMLParameterMultiValue(strLAttribTagName, strLAttribTagName, argtype1, strAttrib, argdesc1); + strInXml = strHand + strChang + strLast; + } + } + + // Component Attrib + if (!string.IsNullOrEmpty(strCAttrib)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strCAttribTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strCAttribTagName.Length + 3); // strCAttribTagName.Length + 3 = 的長度 + string argtype2 = "String"; + string argdesc2 = ""; + strChang = CombineXMLParameterMultiValue(strCAttribTagName, strCAttribTagName, argtype2, strCAttrib, argdesc2); + strInXml = strHand + strChang + strLast; + } + } + + InXML = strInXml; + + dtChkRuleLot2 = dtChkRuleLot.Copy(); + + //var drSelRule = default(DataRow[]); + //foreach (DataRow drTempComponent in dtCompRuleData.Rows) + //{ + // if (Strings.Right(drTempComponent["RuleAction"].ToString(), 4) == "HOLD") + // { + // drSelRule = dtLotRuleData.Select("LotNo = '" + drTempComponent["LotNo"].ToString() + "'"); + // if (drSelRule.Length > 0) + // { + // drSelRule[0]["LinkName"] = Strings.Right(drTempComponent["RuleAction"].ToString(), 4); + // if (string.IsNullOrEmpty(drSelRule[0]["RuleNo"].ToString())) + // { + // drSelRule[0]["RuleNo"] = drTempComponent["RuleNo"].ToString(); + // } + // else + // { + // drSelRule[0]["RuleNo"] = drSelRule[0]["RuleNo"] + "," + drTempComponent["RuleNo"].ToString(); + // } + // } + // } + // else if (drTempComponent["RuleAction"].ToString() == "WAIT") + // { + // drSelRule = dtLotRuleData.Select("LotNo = '" + drTempComponent["LotNo"].ToString() + "'"); + // if (drSelRule.Length > 0) + // { + // if (drSelRule[0]["LinkName"].ToString() != "PASS") + // { + // drSelRule[0]["LinkName"] = "WAIT"; + // if (string.IsNullOrEmpty(drSelRule[0]["RuleNo"].ToString())) + // { + // drSelRule[0]["RuleNo"] = drTempComponent["RuleNo"].ToString(); + // } + // else + // { + // drSelRule[0]["RuleNo"] = drSelRule[0]["RuleNo"] + "," + drTempComponent["RuleNo"].ToString(); + // } + // } + // } + // } + //} + + // =============================================== 68289 End =============================================== + } + + // 將LotStamp替換為TriggerOP後的LotStamp + if (blnEXETriggerOP) + { + string strLotStampTagName = "lotstamp".ToLower(); + + int intStartIndex, intEndIndex; + string strHand, strLast, strChang; + string strInXml = InXML; + DataRow[] drSel; + + // 取得LotStamp + intStartIndex = Strings.InStr(strInXml, "<" + strLotStampTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLotStampTagName.Length + 3); + string argname1 = "LotStamp"; + string argtype3 = "Long"; + string argvalue = Conversions.ToInteger(dtLotState.Rows[0]["LotStamp"]).ToString(); + string argdesc3 = ""; + strChang = CombineXMLParameter(strLotStampTagName, argname1, argtype3, argvalue, argdesc3); + strInXml = strHand + strChang + strLast; + InXML = strInXml; + } + } + + if (LinkName != defString) + { + strLinkName = LinkName; + } + + string strcheckinresult = ""; // BR_CheckIn回傳success or fail + using (var obj = new clsLot()) + { + if (FunctionID == "CO") + { + // 5.取出GoodQty,GoodUnitNo--------------------------------------------------------------------------------------------------- + DataRow[] drSel; + double GoodQty = 0d; + + drSel = dtLotAttrib_Temp.Select("AttribNo='GoodQty'"); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200001", "[%CheckOut%] [%GoodQty%] [%not found%]"); + } + else + { + GoodQty = Convert.ToDouble(drSel[0]["AttribValue"]); + } + // 進站之前已扣料過。 + strcheckinresult = obj.BR_CheckOut(Conversions.ToLong(strLotStamp), LotNo, strLinkName, dtLotAttrib_Temp, dtEquipment, null, null, (decimal)GoodQty, UserNo); + + strRetrunMsg = strcheckinresult; + // 9.Return Value + if (!string.IsNullOrEmpty(strRetrunMsg)) + { + strResult = "fail"; + throw new iMESException.MESException("0000-200011", "[%LotNo%] : " + LotNo + "[%Execute%] [%Fail%]."); + } + else + { + strException = ""; + strResult = "success"; + } + } + + else + { + strcheckinresult = obj.BR_CheckIn(Conversions.ToLong(strLotStamp), LotNo, strLinkName, dtLotAttrib_Temp, dtEquipment, UserNo, ShiftNo, dtAccessory: dtAccessory); + strRetrunMsg = strcheckinresult; + + // 9.Return Value + if (strRetrunMsg == "success") + { + strException = ""; + strResult = "success"; + } + else + { + strResult = "fail"; + throw new iMESException.MESException("0000-200011", "[%LotNo%] : " + LotNo + "[%Execute%] [%Fail%]."); + } + } + } + + + + objSYS.AddEventLog(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, "ExecuteLot", ComputerName: ComputerName); + // Call BRTransferLot(LotNo, UserNo, strLinkName, 1) + tcEAI.clsEAP.BRTransferLot_Bin(LotNo, UserNo, strLinkName, intERFType, strRuleNo, ComputerName: ComputerName, RuleMsg: strERFMsg); + + + lblExitProcedure: + ; + } + + + catch (iMESException.MESException ex) + { + + if (FunctionID == "CI") + { + if (dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + // CheckIn失敗將狀態變更回Queue + foreach (DataRow drTempLotInfo in dtLotNo.Rows) + { + if (Convert.ToBoolean(drTempLotInfo["blnEXETriggerOP"])) + { + DataRow[] drSel = dtLotState.Select("LotNO='" + drTempLotInfo["LotNo"] + "'".ToString()); + // Call objReverse.ExecuteReverse(drSel(0)("LotNo"), "AutoExe", Now, , , , , drSel(0)("LotStamp")) + // Call objLot.ExeReverseTriggerOP(drSel(0)("LotNo"), drSel(0)("LotSerial"), drSel(0)("LogGroupSerial"), drSel(0)("LotStamp")) + ExeReverseTriggerOP_NotUseUndo(UserNo, Convert.ToString(drSel[0]["LotNo"]), Convert.ToString(drSel[0]["LotSerial"]), Conversions.ToInteger(drSel[0]["LotStamp"]), ComputerName); + } + } + } + } + + strResult = "fail"; + strRetrunMsg = ex.Message; + + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, ex.Message + " : " + ex.StackTrace, ComputerName: ComputerName, ErrorCode: Convert.ToString(ex.ErrorCode)); + + throw ex; + } + + catch (Exception ex) + { + + if (FunctionID == "CI") + { + // CheckIn失敗將狀態變更回Queue + if (dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + foreach (DataRow drTempLotInfo in dtLotNo.Rows) + { + if (Convert.ToBoolean(drTempLotInfo["blnEXETriggerOP"])) + { + DataRow[] drSel = dtLotState.Select("LotNO='" + drTempLotInfo["LotNo"] + "'".ToString()); + // Call objReverse.ExecuteReverse(drSel(0)("LotNo"), "AutoExe", Now, , , , , drSel(0)("LotStamp")) + // Call objLot.ExeReverseTriggerOP(drSel(0)("LotNo"), drSel(0)("LotSerial"), drSel(0)("LogGroupSerial"), drSel(0)("LotStamp")) + ExeReverseTriggerOP_NotUseUndo(UserNo, Convert.ToString(drSel[0]["LotNo"]), Convert.ToString(drSel[0]["LotSerial"]), Conversions.ToInteger(drSel[0]["LotStamp"]), ComputerName); + } + } + } + } + + strResult = "fail"; + strRetrunMsg = ex.Message; + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, ex.Message + " : " + ex.StackTrace, ComputerName: ComputerName); + + throw ex; + } + + finally + { + if (!(drTemp == null)) + drTemp.Close(); + if (!(objLot == null)) + { + objLot.Dispose(); + objLot = null; + } + if (!(objSYS == null)) + { + objSYS.Dispose(); + objSYS = null; + } + AutoexecutionLot_LotRet = strRetrunMsg; + CloseConnection(cnnTemp); + } + + return AutoexecutionLot_LotRet; + } + + private static short funCheckStateByLot(ref string strKernelModule, ref string strKernelFunctionName, string strLotNo, DataRow drLotState, string strFunctionId = defString, string strOPNo = defString) + { + + try + { + // C1:檢查狀態是否符合 + if (strFunctionId == "CI") + { + // CI,狀態必須是0. + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drLotState["Status"], 0, false))) + { + // 生產批狀態不可執行此動作! + throw new iMESException.MESException("0000-217001", "[%LotNo%]:" + strLotNo + ",[%Status%] [%is not%] [%Queue%]!"); + } + // ElseIf strFunctionId = "CO" Then + // 'CO,狀態必須是1. + // If drLotState("Status") <> 1 Then + // Throw New iMESException.MESException("0000-217001", "[%LotNo%]:" & strLotNo & ",[%Status%] [%is not%] [%Running%]!") + // End If + } + + // C2:檢查作業站是否符合 + if (strOPNo != defString) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(strOPNo, drLotState["OPNo"], false))) + { + throw new iMESException.MESException("0000-203029", "[%LotNo%]:" + strLotNo + ",[%CurOPNo%] [%is not%] " + strOPNo + "!"); + } + } + + // 取得BR設定之KernelModule,KernelFunctionName + using (var objOP = new clsOpBasis()) + { + DataRow drBR; + drBR = objOP.GetBusinessRule(drLotState["BRNo"].ToString()); + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drBR["BRNo"], "", false))) + { + throw new iMESException.MESException("0000-200003", "[%BRNo%]:" + drLotState["BRNo"]); + } + } + } + + + catch (Exception ex) + { + throw; + } + + return default(short); + + + } + private static int funChkSPCControl_Var(string UserNo, string LotNo, ref string strAttrib, DataSet dsTestValue, ref string strLinkName, ref int intERFType, ref string strERFMsg, DataTable Equipment = default(DataTable)) + { + int funChkSPCControl_VarRet = default(int); + + funChkSPCControl_VarRet = -1; + + string InXml, OutXml, strIdentity, strParameter; + XmlDocument XmlDoc = new XmlDocument(); + string strTemp; + + string strEquipmentNo = defString; + string strQCItemNo = defString; + + try + { + // 檢查設備是不是1台 + if (!(Equipment == null)) + { + if (Equipment.Rows.Count == 1) + strEquipmentNo = Equipment.Rows[0]["EquipmentNo"].ToString(); + else + throw new iMESException.MESException("0000-103010", "[%SAVETOQCITEM%],[%ONLY SINGLE EQUIPMENT%]"); + } + + // 檢查有無需要拋SPC + if (dsTestValue == null || dsTestValue.Tables[0].Select(" QCItemNo <> '' ").Length <= 0) + { + funChkSPCControl_VarRet = 0; + return funChkSPCControl_VarRet; + } + + // 新增check spc拋回的資料欄 + dsTestValue.Tables[0].Columns.Add("Result", System.Type.GetType("System.String")); + dsTestValue.Tables[0].Columns.Add("Result_INT", System.Type.GetType("System.Int32")); + dsTestValue.Tables[0].Columns.Add("FactorSerial", System.Type.GetType("System.String")); + dsTestValue.Tables[0].Columns.Add("ERFMsg", System.Type.GetType("System.String")); + + // 檢查SPC管制規格 + strIdentity = CombineXMLIdentity("EAI", UserNo, Convert.ToString(DateTime.Now)); + strParameter = CombineXMLParameter("lotno", "LotNo", "String", CInput(LotNo), ""); + if (strEquipmentNo != defString) + { + strParameter += CombineXMLParameter("equipmentno", "EquipmentNo", "String", CInput(strEquipmentNo), ""); + } + InXml = CombineXMLRequest(strIdentity, strParameter); + + object[] aryPars = clsCom.funGetMethodParameters("wsSTD", "wsSPC", "CheckSPCContorl_Var"); + aryPars[0] = InXml; + aryPars[1] = dsTestValue; + OutXml = clsCom.funExecuteMethod("wsSTD", "wsSPC", "CheckSPCContorl_Var", ref aryPars) as string; + + XmlDoc.LoadXml(OutXml); + if (chkExecutionSuccess(XmlDoc)) + { + strLinkName = funGetFinalLinkName(strLinkName, dsTestValue.Tables[0], intERFType); + dsTestValue.Tables[0].DefaultView.Sort = "QCItemNo"; + if (!(dsTestValue.Tables[0] == null) && dsTestValue.Tables[0].DefaultView.ToTable().Rows.Count > 0) + { + strERFMsg = ""; + strAttrib = ""; + foreach (DataRow dr in dsTestValue.Tables[0].Rows) + { + strTemp = CombineXMLValue("attribno", CInput(dr["AttribNo"].ToString())) + + CombineXMLValue("attribtype", dr["AttribType"].ToString()) + + CombineXMLValue("attribsequence", dr["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", dr["AttribSource"].ToString()) + + CombineXMLValue("attribphase", dr["AttribPhase"].ToString()) + + CombineXMLValue("attribvalue", CInput(dr["AttribValue"].ToString())) + + CombineXMLValue("savetolotpropertyno", CInput(dr["SaveToLotPropertyNo"].ToString())); + + if (!(dr["QCItemNo"] is DBNull)) + { + strTemp += CombineXMLValue("qcitemno", CInput(dr["QCItemNo"].ToString())); + + if ((strQCItemNo == defString || strQCItemNo != dr["QCItemNo"].ToString()) && !(dr["ERFMsg"] is DBNull)) + { + strQCItemNo = dr["QCItemNo"].ToString(); + strERFMsg += dr["ERFMsg"].ToString() + ControlChars.Lf; + } + } + else + { + strTemp += CombineXMLValue("qcitemno", ""); + } + if (!(dr["Result"] is DBNull)) + strTemp += CombineXMLValue("result", CInput(dr["Result"].ToString())); + else + strTemp += CombineXMLValue("result", ""); + if (!(dr["Result_INT"] is DBNull)) + strTemp += CombineXMLValue("result_int", CInput(dr["Result_INT"].ToString())); + else + strTemp += CombineXMLValue("result_int", ""); + if (!(dr["FactorSerial"] is DBNull)) + strTemp += CombineXMLValue("factorserial", CInput(dr["FactorSerial"].ToString())); + else + strTemp += CombineXMLValue("factorserial", ""); + if (!(dr["SerialNo"] is DBNull)) + strTemp += CombineXMLValue("serialno", CInput(dr["SerialNo"].ToString())); + else + strTemp += CombineXMLValue("serialno", ""); + + strAttrib += CombineXMLValueTag(strTemp); + } + } + + funChkSPCControl_VarRet = 0; + } + } + catch (Exception ex) + { + throw; + } + return funChkSPCControl_VarRet; + } + private static string funGetFinalLinkName(string strLinkName, DataTable dtKeyIn, int intERFType = defInteger) + { + string funGetFinalLinkNameRet = default(string); + + try + { + // ===== 整理生產批品管項目結果 ========= + string strSPCLinkName = ""; + if (dtKeyIn.Select(" Result = 'HOLD' ").Length > 0) + strSPCLinkName = "HOLD"; + else if (dtKeyIn.Select(" Result = 'WAIT' ").Length > 0) + strSPCLinkName = "WAIT"; + else if (dtKeyIn.Select(" Result = 'WARNING' ").Length > 0) + strSPCLinkName = "WARNING"; + else if (dtKeyIn.Select(" Result = 'ALARM' ").Length > 0) + strSPCLinkName = "ALARM"; + else if (dtKeyIn.Select(" Result = 'ALERT' ").Length > 0) + strSPCLinkName = "ALERT"; + if (funGetLinkNamePriority(strLinkName) < funGetLinkNamePriority(strSPCLinkName)) + { + strLinkName = strSPCLinkName; + if (strLinkName == "HOLD") + intERFType = 1; + } + + funGetFinalLinkNameRet = strLinkName; + } + catch (Exception ex) + { + throw; + } + return funGetFinalLinkNameRet; + } + + // 取得Link Name權重 + private static int funGetLinkNamePriority(string strLinkName) + { + int funGetLinkNamePriorityRet = default(int); + + try + { + int intResult = -1; + // ===== 整理生產批(各品管項目綜合)結果,並存入資料庫 ========= + if (Strings.InStr(strLinkName, "HOLD") > 0) + intResult = 5; + else if (Strings.InStr(strLinkName, "WAIT") > 0) + intResult = 4; + else if (Strings.InStr(strLinkName, "ALARM") > 0) + intResult = 0; + else if (Strings.InStr(strLinkName, "ALERT") > 0) + intResult = 0; + else + intResult = 0; + + funGetLinkNamePriorityRet = intResult; + } + catch (Exception ex) + { + throw; + } + return funGetLinkNamePriorityRet; + } + public static DataTable ConvertXmlToDataTable(DataTable dataTable, string xmlString) + { + XmlDocument XmlDoc = new XmlDocument(); + + if (!(xmlString.Contains("") && xmlString.Contains(""))) + { + xmlString = "" + xmlString + ""; + } + + XmlDoc.LoadXml(xmlString); + + foreach (XmlNode node in XmlDoc.DocumentElement.ChildNodes) + { + DataRow row = dataTable.NewRow(); + foreach (XmlNode childNode in node.ChildNodes) + { + if (dataTable.Columns.Contains(childNode.Name)) + { + switch (dataTable.Columns[childNode.Name].DataType.ToString()) + { + case "System.Int32": + { + row[childNode.Name] = Conversions.ToInteger(childNode.InnerText); + break; + } + default: + { + row[childNode.Name] = childNode.InnerText; + break; + } + } + } + } + dataTable.Rows.Add(row); + } + + return dataTable; + } + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// 0:預設檢察區域設備,非0不檢察區域設備 + private static void funBasisCheck(string CIorCO, DataTable dtLotNo, DataTable dtEquipment, DataTable dtLotList, DataTable dtLotAttrib, DataTable dtLotError, DataTable dtLotComponent, DataTable dtLotCompAttrib, ref DataTable dtTempAttrib, string strLots, string Type = defString, short pRunningMdoe = 0) + { + + DataRow[] drSel; + DataTable dtTempCopmonentAttrib; + try + { + + // 判斷PhaseNo + int PhaseNo = 99; + if (CIorCO == "CI") + { + PhaseNo = 1; + } + else if (CIorCO == "CO") + { + PhaseNo = 2; + } + + // 1.設備檢查 + if (pRunningMdoe == 0 && CIorCO == "CI") + { + + // 1.1 載入區域設備可用設備 + foreach (DataRow r in dtLotNo.Rows) + { + DataTable dtAvailableEquipment_All; + DataTable dtAvailableEquipment_Chamber; + using (var objLot = new clsLot()) + { + dtAvailableEquipment_All = objLot.ShowAvailableEquipment_All(r["LotNo"].ToString()).Tables[0]; + dtAvailableEquipment_Chamber = objLot.ShowAvailableEquipment_All(r["LotNo"].ToString()).Tables["Chamber"]; + } + + drSel = dtAvailableEquipment_All.Select(" AllowExecute=1 "); + + // 1.2 若區域內無可用設備,但卻傳入設備編號則拋出錯誤訊息 + if (drSel.Length == 0) + { + if (dtEquipment.Rows.Count > 0) + { + throw new iMESException.MESException("0000-003000", "[%Area has none Available Equipment%]"); + } + } + else + { + + // 1.3 若傳入設備編號不在區域可用設備中則拋出錯誤訊息 + foreach (DataRow rE in dtEquipment.Rows) + { + drSel = dtAvailableEquipment_All.Select(" AllowExecute=1 And EquipmentNo = '" + rE["EquipmentNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + //判断子设备是否存在 + if (!(dtAvailableEquipment_Chamber is null) && dtAvailableEquipment_Chamber.Rows.Count > 0) + { + drSel = dtAvailableEquipment_Chamber.Select(" AllowExecute=1 And EquipmentNo = '" + rE["EquipmentNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-003000", "[%EquipmentNo%]: " + rE["EquipmentNo"] + " [%Not In Available Equipment%]"); + } + } + else + { + throw new iMESException.MESException("0000-003000", "[%EquipmentNo%]: " + rE["EquipmentNo"] + " [%Not In Available Equipment%]"); + } + } + } + } + + } + + } + + // 2.檢查KeyInAttrib + // 2.1 取得所有傳入Lot的AttribPhase = PhaseNo並且為99 的Keyin TempAttrib + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + //string argstrDataBaseType = "Null"; + //using (var cn = new OleDbConnection(objSetting.GetConnectionString(strDataBaseType: ref argstrDataBaseType))) + //{ + // using (var da = new OleDbDataAdapter("Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + " From tblWIPTemp_Attrib A, tblSYSElementBasis B " + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, cn)) + // { + // da.Fill(ds.Tables.Add("TempAttrib")); + // } + //} + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_Attrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, + ds.Tables.Add("TempAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtTempAttrib = ds.Tables[0]; + } + + // 2.2 取得所有傳入Lot的AttribPhase = PhaseNo並且為99 的Keyin TempCopmonentAttrib + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + //string argstrDataBaseType1 = "Null"; + //using (var cn = new OleDbConnection(objSetting.GetConnectionString(strDataBaseType: ref argstrDataBaseType1))) + //{ + // using (var da = new OleDbDataAdapter("Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + " From tblWIPTemp_ComponentAttrib A, tblSYSElementBasis B " + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, cn)) + // { + // da.Fill(ds.Tables.Add("TempCopmonentAttrib")); + // } + //} + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_ComponentAttrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, + ds.Tables.Add("TempCopmonentAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtTempCopmonentAttrib = ds.Tables[0]; + } + + foreach (DataRow rL in dtLotNo.Rows) + { + + switch (Type) + { + case "ASM": // //因為欄位大小寫問題,且以XML檢查為主 + { + + foreach (DataRow rLA in dtLotAttrib.Rows) + { + drSel = dtTempAttrib.Select(" AttribNo = '" + rLA["attribno"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["attribno"] + " ,[%AttribNo%]: " + rLA["attribno"] + " [%NOT PASS ARGUMENTS%]"); + } + } + + + foreach (DataRow rCA in dtLotCompAttrib.Rows) + { + drSel = dtTempCopmonentAttrib.Select(" AttribNo = '" + rCA["attribno"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rCA["attribno"] + " ,[%AttribNo%]: " + rCA["attribno"] + " [%NOT PASS ARGUMENTS%]"); + } + + // 2.3 若為CPASS,並且傳入值為1時,必須存在相對應的Error + else if (drSel[0]["AttribNo"].ToString().ToUpper() == "CPASS" && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drSel[0]["AttribValue"], 1, false))) + { + drSel = dtLotError.Select(" LotNo = '" + + rCA["LotNo"] + "' And ComponentNo = '" + rCA["ComponentNo"] + "' "); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rCA["LotNo"] + " ,[%AttribNo%]: " + rCA["AttribNo"] + " Error Data "); + } + } + } + + break; + } + + case "LotAttrib": //只檢查 LotAttrib + { + // 2.3 LotAttrib 若為not null Attrib未傳入則拋出錯誤訊息 + foreach (DataRow rLA in dtTempAttrib.Select("LotNo = '" + rL["LotNo"] + "' And AttribType = 0 ".ToString())) + { + drSel = dtLotAttrib.Select(" LotNo = '" + rLA["LotNo"] + "' And AttribNo = '" + rLA["AttribNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["LotNo"] + " ,[%AttribNo%]: " + rLA["AttribNo"] + " [%NOT PASS ARGUMENTS%]"); + } + } + break; + } + + default: + { + + // 2.3 LotAttrib 若為not null Attrib未傳入則拋出錯誤訊息 + foreach (DataRow rLA in dtTempAttrib.Select("LotNo = '" + rL["LotNo"] + "' And AttribType = 0 ".ToString())) + { + drSel = dtLotAttrib.Select(" LotNo = '" + rLA["LotNo"] + "' And AttribNo = '" + rLA["AttribNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["LotNo"] + " ,[%AttribNo%]: " + rLA["AttribNo"] + " [%NOT PASS ARGUMENTS%]"); + } + } + + // 2.4 ComponentAttrib 若為not null Attrib未傳入則報錯 + foreach (DataRow rCA in dtTempCopmonentAttrib.Select("LotNo = '" + rL["LotNo"] + "' And AttribType = 1 ".ToString())) + { + drSel = dtLotCompAttrib.Select(" LotNo = '" + + rCA["LotNo"] + "' And AttribNo = '" + rCA["AttribNo"] + "' "); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rCA["LotNo"] + " ,[%AttribNo%]: " + rCA["AttribNo"] + " [%NOT PASS ARGUMENTS%]"); + } + + // 2.3 若為CPASS,並且傳入值為1時,必須存在相對應的Error + else if (drSel[0]["AttribNo"].ToString().ToUpper() == "CPASS" && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drSel[0]["AttribValue"], 1, false))) + { + drSel = dtLotError.Select(" LotNo = '" + + rCA["LotNo"] + "' And ComponentNo = '" + rCA["ComponentNo"] + "' "); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rCA["LotNo"] + " ,[%AttribNo%]: " + rCA["AttribNo"] + " Error Data "); + } + } + } + + break; + } + } + + } + } + + catch (iMESException.MESException ex) + { + throw ex; + } + catch (Exception ex) + { + throw ex; + } + finally + { + } + + } + + private void funBasisCheck(string CIorCO, DataTable dtLotNo, DataTable dtEquipment, DataTable dtLotList, DataTable dtLotAttrib, DataTable dtLotError, ref DataTable dtTempAttrib, string strLots, string Type = defString, short pRunningMdoe = 0) + { + + DataRow[] drSel; + DataTable dtTempCopmonentAttrib; + try + { + // 判斷PhaseNo + int PhaseNo = 99; + if (CIorCO == "CI") + { + PhaseNo = 1; + } + else if (CIorCO == "CO") + { + PhaseNo = 2; + } + + // 1.設備檢查 + if (pRunningMdoe == 0 && CIorCO == "CI") + { + // 1.1 載入區域設備可用設備 + foreach (DataRow r in dtLotNo.Rows) + { + DataTable dtAvailableEquipment_All; + using (var objLot = new clsLot()) + { + dtAvailableEquipment_All = objLot.ShowAvailableEquipment_All(r["LotNo"].ToString()).Tables[0]; + } + + drSel = dtAvailableEquipment_All.Select(" AllowExecute=1 "); + + // 1.2 若區域內無可用設備,但卻傳入設備編號則拋出錯誤訊息 + if (drSel.Length == 0) + { + if (dtEquipment.Rows.Count > 0) + throw new iMESException.MESException("0000-003000", "[%Area has none Available Equipment%]"); + + } + else + { + // 1.3 若傳入設備編號不在區域可用設備中則拋出錯誤訊息 + foreach (DataRow rE in dtEquipment.Rows) + { + drSel = dtAvailableEquipment_All.Select(" AllowExecute=1 And EquipmentNo = '" + rE["EquipmentNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-003000", "[%EquipmentNo%]: " + + rE["EquipmentNo"] + " [%Not In Available Equipment%]"); + } + } + } + } + } + + // 2.檢查KeyInAttrib + // 2.1 取得所有傳入Lot的AttribPhase = PhaseNo並且為99 的Keyin TempAttrib + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_Attrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, + ds.Tables.Add("TempAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtTempAttrib = ds.Tables[0]; + } + + // 2.2 取得所有傳入Lot的AttribPhase = PhaseNo並且為99 的Keyin TempCopmonentAttrib + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + ExecuteSQLQuery_Adapter( + "Select A.*,B.ElementName As AttribName, B.InputType, B.DataType, B. ValueType " + + " From tblWIPTemp_ComponentAttrib A, tblSYSElementBasis B " + + " Where A.AttribNo=B.ElementNo And A.AttribSource = 0 " + + " and (AttribPhase = 99 or AttribPhase = " + PhaseNo + ") And B.AllowNull = 0 And A.LotNo In " + strLots, + ds.Tables.Add("TempCopmonentAttrib"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtTempCopmonentAttrib = ds.Tables[0]; + } + + foreach (DataRow rL in dtLotNo.Rows) + { + switch (Type) + { + case "ASM": // //因為欄位大小寫問題,且以XML檢查為主 + { + foreach (DataRow rLA in dtLotAttrib.Rows) + { + drSel = dtTempAttrib.Select(" AttribNo = '" + rLA["attribno"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["attribno"] + " ,[%AttribNo%]: " + rLA["attribno"] + " [%NOT PASS ARGUMENTS%]"); + } + } + + break; + } + + case "LotAttrib": //只檢查 LotAttrib + { + // 2.3 LotAttrib 若為not null Attrib未傳入則拋出錯誤訊息 + foreach (DataRow rLA in dtTempAttrib.Select("LotNo = '" + rL["LotNo"] + "' And AttribType = 0 ".ToString())) + { + drSel = dtLotAttrib.Select(" LotNo = '" + rLA["LotNo"] + "' And AttribNo = '" + rLA["AttribNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["LotNo"] + " ,[%AttribNo%]: " + rLA["AttribNo"] + " [%NOT PASS ARGUMENTS%]"); + } + } + break; + } + + default: + { + // 2.3 LotAttrib 若為not null Attrib未傳入則拋出錯誤訊息 + foreach (DataRow rLA in dtTempAttrib.Select("LotNo = '" + rL["LotNo"] + "' And AttribType = 0 ".ToString())) + { + drSel = dtLotAttrib.Select(" LotNo = '" + rLA["LotNo"] + "' And AttribNo = '" + rLA["AttribNo"] + "' ".ToString()); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200002", "[%LotNo%]:" + + rLA["LotNo"] + " ,[%AttribNo%]: " + rLA["AttribNo"] + " [%NOT PASS ARGUMENTS%]"); + } + } + + break; + } + } + } + + } + catch (iMESException.MESException ex) + { + throw ex; + } + catch (Exception ex) + { + throw ex; + } + finally + { + } + + } + #endregion + + + + #region EAP 客制接口 + /// + /// 首站进站 + /// + /// + /// + /// + /// + /// + public static bool funTrackIn_Inquiry(ref List aryMessage, ref List aryException, string MONO, string EQPID) + { + bool funTrackIn_Inquiry = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + + + + + + + int EQPSTATE = 0; //设备管控闲置状态 + + int nowEQPSTATE = 0; //现在设备管控闲置状态 + + string strLotNo = "";//生产批号 + + try + { + //先检查 设备状态是否是闲置 + + //检查设备是否存在 + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + //throw new iMESException.MESException("0000-202001", +" :设备不存在!"); + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + //获取设备管控闲置状态是多少 + strSQL = "Select EQUIPMENTSTATE From TBLEQPSTATECONTROL Where CONTROLNO Is Not Null AND CONTROLTYPE ='EQP Break Down' AND CONTROLNO='Idle'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + EQPSTATE = Conversions.ToInteger(drTemp["EQUIPMENTSTATE"]); + } + else + { + //throw new iMESException.MESException("0000-202001", "闲置状态未设定!"); + clsERP.combineMessage(ref aryMessage, mmsg: "[%设备闲置状态未设定!%]"); + return false; + } + drTemp.Close(); + + + //获取现在设备的状态 + strSQL = "Select EQUIPMENTSTATE From tblEMSEquipmentState WHERE EQUIPMENTNO='" + EQPID + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + nowEQPSTATE = Conversions.ToInteger(drTemp["EQUIPMENTSTATE"]); + } + else + { + //throw new iMESException.MESException("0000-202001", "闲置状态未设定!"); + + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:状态未设定!%]"); + return false; + } + drTemp.Close(); + + //比较现在的状态和闲置状态是否一致 + if (nowEQPSTATE != EQPSTATE) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备非闲置状态,不能进站!%]"); + return false; + } + + + //根据工单获取生产批 + strSQL = $"SELECT A.BASELOTNO,B.STATUS,B.LotStamp FROM TBLWIPLOTBASIS A INNER JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.MONO='{MONO}' AND B.STATUS IN (0,1,2,3,4,5) AND A.LotState = '1'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS", cnnTemp); + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: MONO + "[%:无在制生产批!%]"); + return false; + } + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count > 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: MONO + "[%:该工单有多个批次存在,请检查是否已上料!%]"); + return false; + } + + + strLotNo = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS"].Rows[0]["BASELOTNO"]); + + //调用标准进站 + var datSendTime = default(DateTime); // 送達時間 + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = string.Empty; // Request User -紀錄操作人員 + Dictionary dicPars = new Dictionary(); //固定引數,Request傳入的一般參數 + Dictionary dicPars_DataTable = new Dictionary(); //固定引數,Request傳入的DataTable參數 + + //添加批号 + dicPars.Add("lotno", strLotNo); + dicPars.Add("equipmentno", EQPID); + + + AutoexecutionLot_Lot(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CI", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck)); + + funTrackIn_Inquiry = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + + + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funTrackIn_Inquiry; + + } + + public static bool funTrackIn_InquirybyLot(ref List aryMessage, ref List aryException, string Lotid, string EQPID) + { + bool funTrackIn_Inquiry = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + + + + + + + int EQPSTATE = 0; //设备管控闲置状态 + + int nowEQPSTATE = 0; //现在设备管控闲置状态 + + string strLotNo = "";//生产批号 + + try + { + //先检查 设备状态是否是闲置 + + //检查设备是否存在 + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + //throw new iMESException.MESException("0000-202001", +" :设备不存在!"); + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + //获取设备管控闲置状态是多少 + strSQL = "Select EQUIPMENTSTATE From TBLEQPSTATECONTROL Where CONTROLNO Is Not Null AND CONTROLTYPE ='EQP Break Down' AND CONTROLNO='Idle'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + EQPSTATE = Conversions.ToInteger(drTemp["EQUIPMENTSTATE"]); + } + else + { + //throw new iMESException.MESException("0000-202001", "闲置状态未设定!"); + clsERP.combineMessage(ref aryMessage, mmsg: "[%设备闲置状态未设定!%]"); + return false; + } + drTemp.Close(); + + + //获取现在设备的状态 + strSQL = "Select EQUIPMENTSTATE From tblEMSEquipmentState WHERE EQUIPMENTNO='" + EQPID + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + nowEQPSTATE = Conversions.ToInteger(drTemp["EQUIPMENTSTATE"]); + } + else + { + //throw new iMESException.MESException("0000-202001", "闲置状态未设定!"); + + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:状态未设定!%]"); + return false; + } + drTemp.Close(); + + //比较现在的状态和闲置状态是否一致 + if (nowEQPSTATE != EQPSTATE) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备非闲置状态,不能进站!%]"); + return false; + } + + + //根据工单获取生产批 + strSQL = $"SELECT A.BASELOTNO,B.STATUS,B.LotStamp FROM TBLWIPLOTBASIS A INNER JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.BASELOTNO='{Lotid}' AND B.STATUS IN (0,1,2,3,4,5) AND A.LotState = '1'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS", cnnTemp); + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: Lotid + "[%:无在制生产批!%]"); + return false; + } + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count > 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: Lotid + "[%:请检查是否已上料!%]"); + return false; + } + + + strLotNo = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS"].Rows[0]["BASELOTNO"]); + + //调用标准进站 + var datSendTime = default(DateTime); // 送達時間 + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = string.Empty; // Request User -紀錄操作人員 + Dictionary dicPars = new Dictionary(); //固定引數,Request傳入的一般參數 + Dictionary dicPars_DataTable = new Dictionary(); //固定引數,Request傳入的DataTable參數 + + //添加批号 + dicPars.Add("lotno", strLotNo); + dicPars.Add("equipmentno", EQPID); + + + AutoexecutionLot_Lot(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CI", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck)); + funTrackIn_Inquiry = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + + + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funTrackIn_Inquiry; + + } + /// + /// 首站出站 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// 来料不良图谱,第 k 位为 '0' 表示该位置不良;不传则不打不良 + /// + public static bool funTrackOut_Inquiry(ref List aryMessage, ref List aryException, string MONO, string EQPID, string PanleId, string Column, string Line, string carrierId, decimal Qty, string MapData = "") + { + bool funTrackOut_Inquiry = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + + + string strMLotNo = "";//母生产批号 + string strNLotNo = "";//子生产批号 + string strProductNo = "";//产品号 + string strProductVersion = "";//产品版本 + string strSeqNoRule = "";//序号规则 + string strSeqNoType = "";//序号类别 + string strSeqNoSize = "";//起始位置 + string strDirection = "";//走向 + string strOPNO = ""; + + string strUnitIdOrPannid = "";//UnitId或者Pannid + + bool bolLastLot = false;//是否是最后一笔 + + DataSet dataSetLotNo = new DataSet(); + + kcWIP.clsLot objLot = new kcWIP.clsLot(); + + Collection CollectionSQL = new Collection(); + + bool bolInsertMONoProperty = false; //插入工单属性 + + decimal decMQTY = 0; //母批数量 + + try + { + //先检查 设备状态是否是闲置 + + //检查设备是否存在 + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + + + + //根据工单获取生产批 + strSQL = $"SELECT A.BASELOTNO,B.STATUS FROM TBLWIPLOTBASIS A INNER JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.MONO='{MONO}' AND B.STATUS IN (0,1,2,3,4,5) AND A.LotState = '1'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS", cnnTemp); + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: MONO + "[%:无在制生产批!%]"); + return false; + } + + + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count > 1) + { + //存在多个生产批,如果查出来多个批次,则查找工单属性中的批次进行分批 + strSQL = "SELECT PROPERTYVALUE FROM TBLOEMOPROPERTY WHERE MONO='" + MONO + "' AND LOWER(PROPERTYNO) = LOWER('firstlotno')"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: MONO + "[%:不能存在firstlotno工单属性!%]"); + return false; + } + else + { + strMLotNo = Conversions.ToString(drTemp["PROPERTYVALUE"]); + } + drTemp.Close(); + } + else + { + //只有一笔 + strMLotNo = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS"].Rows[0]["BASELOTNO"]); + + //只有一笔则插入工单属性 + bolInsertMONoProperty = true; + } + + + if (string.IsNullOrEmpty(strMLotNo)) + { + clsERP.combineMessage(ref aryMessage, mmsg: MONO + "[%:无在制母生产批!%]"); + return false; + } + + + //获取母批的基本信息 + strSQL = $"SELECT A.PRODUCTNO,A.PRODUCTVERSION,B.STATUS,B.CURQTY,B.OPNO,B.LOTSTAMP FROM TBLWIPLOTBASIS A LEFT JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.BASELOTNO ='{strMLotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS_MLOT", cnnTemp); + + if (dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:批次状态不是执行中,不允许出站!%]"); + return false; + } + + //检查母批状态是否是执行中 STATUS 是否为 1 + if (Conversions.ToInteger(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["STATUS"]) != 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:母生产批状态不是执行中!%]"); + return false; + } + + + //判断母批是否够分 + if (Convert.ToDecimal(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"]) <= Qty) + { + //不够分或者刚好 + bolLastLot = true; //母批则作为最后一批出站,保留母批分批 + + decMQTY = Convert.ToDecimal(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"]); + } + + + //判断产品是否绑定了panleid&unit序号规则 + + strProductNo = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["PRODUCTNO"]); + strProductVersion = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["PRODUCTVERSION"]); + strOPNO = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["OPNO"]); + + strSQL = "SELECT PANLEID,UNITID,STARTPOINT,DIRECTION FROM TBLPRDPRODUCTBASIS WHERE PRODUCTNO='" + strProductNo + "' AND PRODUCTVERSION='" + strProductVersion + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (drTemp["PANLEID"].ToString().Trim() != "") + { + strSeqNoRule = drTemp["PANLEID"].ToString().Trim(); + strSeqNoType = "PANLEID"; + strSeqNoSize = drTemp["STARTPOINT"].ToString().Trim(); + strDirection = drTemp["DIRECTION"].ToString().Trim(); + } + + //优先选择UNITID规则 + if (drTemp["UNITID"].ToString().Trim() != "") + { + strSeqNoRule = drTemp["UNITID"].ToString().Trim(); + strSeqNoType = "UNITID"; + strSeqNoSize = drTemp["STARTPOINT"].ToString().Trim(); + strDirection = drTemp["DIRECTION"].ToString().Trim(); + } + } + else + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%产品编号%] :" + strProductNo + " [%产品版本%] :" + strProductVersion + "[%未panleid&unit序号规则%]"); + return false; + } + drTemp.Close(); + + if (strSeqNoRule == "") + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%产品编号%] :" + strProductNo + " [%产品版本%] :" + strProductVersion + "[%未panleid&unit序号规则%]"); + return false; + } + if (strSeqNoSize == "" || strDirection == "") + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%产品编号%] :" + strProductNo + " [%产品版本%] :" + strProductVersion + "[%未维护初始位置和走向%]"); + return false; + } + + + + + + //检查母批是否可以分批 + objLot.ChkLotStamp(strMLotNo, Convert.ToInt32(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["LOTSTAMP"]), pOPNo: Convert.ToString(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["OPNO"]), pStatus: Convert.ToInt32(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["STATUS"])); + + + + //先生成序号 + int intColumn = int.Parse(Column); + int intLine = int.Parse(Line); + + string[,] unitIdOrPannids = new string[intLine, intColumn]; + string[,] locations = new string[intLine, intColumn]; + + //产生位置号与序号(原地逐字抽出为公共方法,行为不变) + if (!funInitDieSerial(ref aryMessage, ref aryException, PanleId, strMLotNo, strProductNo, strProductVersion, strSeqNoRule, strSeqNoType, strSeqNoSize, strDirection, intColumn, intLine, unitIdOrPannids, locations, cnnTemp)) + { + return false; + } + + //(xg)根据 mapdata 字段中为1的数量作为子批数量进行分批(只分良品,不分不良品)-- 龙旗定制 + //(xg)原逻辑: 直接使用报文 Qty 作为子批数量进行分批 + decimal intGoodCount = Qty; + if (!string.IsNullOrEmpty(MapData) && MapData.Length == intColumn * intLine) + { + //(xg)统计 mapdata 中良品(值为1)的数量 + intGoodCount = 0; + foreach (char c in MapData) + { + if (c == '1') + intGoodCount++; + } + //(xg)重新判断母批是否够分,使用良品数量;无良品时不分批 + if (Convert.ToDecimal(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"]) <= intGoodCount || intGoodCount == 0) + { + bolLastLot = true; + decMQTY = Convert.ToDecimal(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"]); + } + else + { + bolLastLot = false; + decMQTY = Convert.ToDecimal(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"]); + } + } + //如果够分批,则执行分批 + if (!bolLastLot) + { + string newSplitLot = string.Empty; //子批 + string newSplitLotXml = string.Empty; //子批 + long LotStamp; + DataTable dtSplitLot; + decimal MCurQty = 0; + string ProductNo = string.Empty; + string ProductVersion = string.Empty; + string oldCarrierNo = string.Empty; + string OPNo = defString; + string ShiftNo = "N/A"; + string userNo = "EAP_AGENT"; + + //开始分批 + //******************************start 开始拆批**************************** + //刷新生产批信息 + LoadLotBasisJoinState_M1001(ref dataSetLotNo, BaseLotNo: strMLotNo); + + //1.先检查拆批的生产批资料是否存在 + if (dataSetLotNo.Tables["BasisJoinState"].Rows.Count == 0) + { + throw new Exception($" 未找{strMLotNo}对应生产批资料!"); + } + + //获取拆批前所需要的资料 + //母批的LotStamp + object lotStampValue = dataSetLotNo.Tables["BasisJoinState"].Rows[0]["LotStamp"]; + LotStamp = lotStampValue == DBNull.Value ? 0 : Convert.ToInt64(lotStampValue); + + dtSplitLot = new DataTable("SplitLot"); + dtSplitLot.Columns.Add("SplitLotNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("SplitLotQty", Type.GetType("System.Double")); + dtSplitLot.Columns.Add("Action", Type.GetType("System.Int32")); + dtSplitLot.Columns.Add("NodeID", Type.GetType("System.String")); + dtSplitLot.Columns.Add("ReturnType", Type.GetType("System.Int32")); + // 2005/08/15 + dtSplitLot.Columns.Add("ProductNo", Type.GetType("System.String")); + dtSplitLot.Columns.Add("ProductVersion", Type.GetType("System.String")); + // 2008/05/22 + dtSplitLot.Columns.Add("CarrierNo", Type.GetType("System.String")); + // 2021/10/14 生產批歷程欄位新增 + dtSplitLot.Columns.Add("OPNo", Type.GetType("System.String")); + + + //取新批号 + //依数量分批 + MCurQty = Convert.ToDecimal(dataSetLotNo.Tables["BasisJoinState"].Rows[0]["CURQTY"].ToString()); + ProductNo = dataSetLotNo.Tables["BasisJoinState"].Rows[0]["ProductNo"].ToString(); + ProductVersion = dataSetLotNo.Tables["BasisJoinState"].Rows[0]["ProductVersion"].ToString(); + OPNo = dataSetLotNo.Tables["BasisJoinState"].Rows[0]["ProductVersion"].ToString(); + + + + + + //放母批 + DataRow newSplitLotData = dtSplitLot.NewRow(); + newSplitLotData["SplitLotNo"] = strMLotNo; + //(xg)原: newSplitLotData["SplitLotQty"] = MCurQty - Qty; + newSplitLotData["SplitLotQty"] = MCurQty - intGoodCount; + newSplitLotData["Action"] = 0; + newSplitLotData["NodeID"] = ""; + newSplitLotData["ReturnType"] = 0; + newSplitLotData["ProductNo"] = ProductNo; + newSplitLotData["ProductVersion"] = ProductVersion; + newSplitLotData["OPNo"] = OPNo; + dtSplitLot.Rows.Add(newSplitLotData); + + //直接取新批号 [直接回写数据库] + using (kcSYS.clsSYSEng objSYSEng = new kcSYS.clsSYSEng()) + { + newSplitLotXml = objSYSEng.GetSplitLotNo_Multiple(true, 1, strMLotNo); + } + + //获取到xml之后解析 + xmlDoc.LoadXml(newSplitLotXml); + + //获取子批 + newSplitLot = xmlDoc.GetElementsByTagName("InitSplitLotNo").Item(0) + .SelectNodes("LotNo").Item(0).InnerXml; + + + strNLotNo = newSplitLot; + + //放子批 + DataRow newSplitLotData2 = dtSplitLot.NewRow(); + newSplitLotData2["SplitLotNo"] = newSplitLot; + //(xg)原: newSplitLotData2["SplitLotQty"] = Qty; + newSplitLotData2["SplitLotQty"] = intGoodCount; + newSplitLotData2["Action"] = 0; + newSplitLotData2["NodeID"] = ""; + newSplitLotData2["ReturnType"] = 0; + newSplitLotData2["ProductNo"] = ProductNo; + newSplitLotData2["ProductVersion"] = ProductVersion; + newSplitLotData2["OPNo"] = OPNo; + dtSplitLot.Rows.Add(newSplitLotData2); + + //做BR分批 + //objLot.BR_Manual_LotSplit(LotStamp, strMLotNo, 1, userNo, dtSplitLot, ShiftNo: ShiftNo); + + //母批不出站 + BR_Manual_LotSplit_M(LotStamp, strMLotNo, 1, userNo, dtSplitLot, ShiftNo: ShiftNo); + + //******************************end 开始拆批**************************** + + ////开始生产批转移,生产批转移需要走隐藏站规则,因为有客制,所以调用MEStc的功能,防止后续改动导致EAP出错 + string strLinkName = "PASS"; + string strMailGroupNo = ""; + string strMsg = ""; + string strRuleNo = defString; + int intERFType = 0; + string strERFMsg = ""; + string ComputerName = System.Net.Dns.GetHostName(); + BRTransferLot_Bin_M(newSplitLot, "EAP", strLinkName, intERFType, strRuleNo, ComputerName: ComputerName, RuleMsg: strERFMsg); + + } + else + { + //母批作为最后一批直接出站 + + //调用标准进站 + var datSendTime = default(DateTime); // 送達時間 + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = string.Empty; // Request User -紀錄操作人員 + Dictionary dicPars = new Dictionary(); //固定引數,Request傳入的一般參數 + Dictionary dicPars_DataTable = new Dictionary(); //固定引數,Request傳入的DataTable參數 + + //添加批号 + dicPars.Add("lotno", strMLotNo); + dicPars.Add("equipmentno", EQPID); + + //出站明细 + DataTable dtLotAttrib = new DataTable(); //特性 + //添加LotNo列 + dtLotAttrib.Columns.Add("LotNo", typeof(string)); + dtLotAttrib.Columns.Add("AttribNo", typeof(string)); + dtLotAttrib.Columns.Add("AttribValue", typeof(string)); + + + + //查询生产批的绑定特性,这里是出站,所以使用TEMP表 + strSQL = $"SELECT ATTRIBNO,ATTRIBVALUE FROM TBLWIPTEMP_ATTRIB WHERE LOTNO='{strMLotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPTEMP_ATTRIB", cnnTemp); + if (dsData.Tables["TBLWIPTEMP_ATTRIB"].Rows.Count > 0) + { + foreach (DataRow dr in dsData.Tables["TBLWIPTEMP_ATTRIB"].Rows) + { + DataRow drLotAttrib = dtLotAttrib.NewRow(); + drLotAttrib["LotNo"] = strMLotNo; + drLotAttrib["AttribNo"] = dr["ATTRIBNO"].ToString(); + if (dr["AttribNo"].ToString() == "GoodQty") + { + drLotAttrib["AttribValue"] = decMQTY; + + } + else if (dr["AttribNo"].ToString() == "ScrapQty") + { + drLotAttrib["AttribValue"] = 0; + } + else if (dr["AttribNo"].ToString() == "DefectQty") + { + drLotAttrib["AttribValue"] = 0; + } + else + { + drLotAttrib["AttribValue"] = dr["ATTRIBVALUE"].ToString(); + } + + dtLotAttrib.Rows.Add(drLotAttrib); + } + } + + + dicPars_DataTable.Add("lotattrib", dtLotAttrib); + + + + AutoexecutionLot_Lot(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CO", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck)); + + + + } + + + + + + //个案表开始处理 + + //要对那个批次做个案表处理 + string inLotNo = strMLotNo; + if (strNLotNo != "") + { + //若有子批,则传子批 + inLotNo = strNLotNo; + } + + //查询新批次的MNewLotSerial + string strMNewLotSerial = ""; + + strSQL = $"SELECT A.BASELOTNO,B.LOTSERIAL FROM TBLWIPLOTBASIS A LEFT JOIN TBLWIPLOTSTATE B ON A.BASELOTNO=B.LOTNO WHERE A.BASELOTNO='{inLotNo}'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: inLotNo + "[%:生产批无 LOTSERIAL!%]"); + return false; + } + else + { + strMNewLotSerial = Conversions.ToString(drTemp["LOTSERIAL"]); + } + drTemp.Close(); + + + + + //如果报文中传了carrierid,则子批进行上载具操作,存TBLWIPCARRIERSTATE/TBLWIPCARRIERSTATElLOG表。若没有传carrierid,则不进行上载具操作。 + if (!string.IsNullOrEmpty(carrierId)) + { + //上载具 + + string strCarrierType = ""; //载具类别 + + int CurCarrierPosition = 1; // 当前位置 + + //载具基础资料检查 + strSQL = "Select CarrierNo,CarrierState,CarrierType From tblWIPCarrierState Where CarrierNo Is Not Null And CarrierNo = '" + carrierId + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (drTemp["CarrierState"].ToString().Trim() != "1" && drTemp["CarrierState"].ToString().Trim() != "0") + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%载具编号%] :" + carrierId + "[% 只有待使用和使用中状态的载具才可以上载具!%] "); + return false; + } + + strCarrierType = drTemp["CarrierType"].ToString().Trim(); + } + else + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%载具编号%] :" + carrierId + "[%不存在!%] "); + return false; + } + drTemp.Close(); + + //载具寿命检查 + bool isCheckResult = CheckCarrierLife_M(carrierId, strCarrierType, UserNo: "EAP"); + if (!isCheckResult) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%载具编号%] :" + carrierId + "[%当前载具已经达到预警寿命!%] "); + return false; + } + + //获取现在最大的位置 + strSQL = "Select Count(CarrierPosition) CountPosition From tblWIPCarrierStateDetail Where CarrierNo = '" + carrierId + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + CurCarrierPosition = Conversions.ToInteger(drTemp["CountPosition"]); + } + drTemp.Close(); + + if (CurCarrierPosition == 0) + { + CurCarrierPosition = 1; + } + + using (kcEQP.clsCarrierBasis objCarrierBasis = new kcEQP.clsCarrierBasis()) + { + //检查容量 + objCarrierBasis.CheckPutsOnUnitID(carrierId, inLotNo, CurCarrierPosition); + + + } + + //检查无问题,则上载具,这里支持回复处理 + AddCarrierStateDetail_M(carrierId, "EAP", inLotNo, CurCarrierPosition, UserNo: "EAP", LotSerial: strMNewLotSerial, colSQL: CollectionSQL); + + } + + //记录  然后将对应数据存到客制表TBLWIPPRDSTATE_LQ&TBLWIPPRDLOG_LQ,具体取值参考1.4中的数据库表的明细。 + + + SaveWIPPrdStateLog_M(LotNo: inLotNo, ProductID: PanleId, EQPID: EQPID, OPNo: strOPNO, State: 1, ProductType: "0", CarrierID: carrierId, LotSerial: strMNewLotSerial, colSQL: CollectionSQL); + + + //for (int i = 0; i < intLine; i++) + //{ + // for (int j = 0; j < intColumn; j++) + // { + // WriteLog(unitIdOrPannids[i, j]); + // } + //} + + //写入客制表 TBLPCSDIELOG_LQ(原地逐字抽出为公共方法,行为不变) + funSaveDieLog(PanleId, inLotNo, EQPID, strOPNO, intColumn, intLine, carrierId, strMNewLotSerial, unitIdOrPannids, locations, CollectionSQL); + + //(xg)原: if (!funMarkBadByMapData(ref aryMessage, PanleId, inLotNo, MapData, strSeqNoSize, strDirection, intColumn, intLine, CollectionSQL)) + //(xg)改: 新增 unitIdOrPannids, strMLotNo 参数 — 不良品归属母批 + 同步更新客制状态表 + //解析 mapdata 打不良(来料异常);走位设定与产生 LOCATIONNO 时同源;不良品归属母批,同步更新客制状态表 + if (!funMarkBadByMapData(ref aryMessage, PanleId, inLotNo, MapData, strSeqNoSize, strDirection, intColumn, intLine, CollectionSQL, unitIdOrPannids, strMLotNo)) + { + return false; + } + + + + + if (bolInsertMONoProperty) + { + //这里查询一遍是为了并非调用时防止INSERT失败 + strSQL = "SELECT PROPERTYVALUE FROM TBLOEMOPROPERTY WHERE MONO='" + MONO + "' AND LOWER(PROPERTYNO) = LOWER('firstlotno')"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + //不存在则插入 + strSQL = $"INSERT INTO TBLOEMOPROPERTY (MONO, PROPERTYNO, PROPERTYVALUE, LOTSERIAL) VALUES ('{MONO}', 'firstlotno', '{strMLotNo}', null)"; + CollectionSQL.Add(strSQL); + + strSQL = $"DELETE FROM TBLOEMOPROPERTY WHERE MONO='{MONO}' AND PROPERTYNO='firstlotno'"; + + objReverse.AddReverseUpdateContent(ref strMNewLotSerial, ref strSQL, CollectionSQL); + } + else + { + //若是存在,则不是需要再更新 + + ////存在则更新 + //strSQL = $"UPDATE TBLOEMOPROPERTY SET PROPERTYVALUE = '{strMLotNo}' WHERE MONO = '{MONO}' AND LOWER(PROPERTYNO) = LOWER('firstlotno')"; + //CollectionSQL.Add(strSQL); + } + drTemp.Close(); + } + + if (CollectionSQL.Count > 0) + { + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + + + funTrackOut_Inquiry = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + + if (objLot != null) + { + objLot = null; + } + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funTrackOut_Inquiry; + + } + + private static void funInitlocation(string[,] location, string strSeqNoSize, string strDirection, int intColumn, int intLine) + { + // intColumn = 行数 (row) + // intLine = 列数 (col) + int totalPoints = intColumn * intLine; + int maxNumberLength = totalPoints.ToString().Length; + int index = 1; + + switch (strSeqNoSize) // 起始角 + { + case "左上": // 起始点 (0, 0) + { + if (strDirection == "横向") // S型横向 + { + for (int row = 0; row < intColumn; row++) + { + if (row % 2 == 0) // 偶数行从左到右 + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数行从右到左 + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "竖向") // S型竖向 + { + for (int col = 0; col < intLine; col++) + { + if (col % 2 == 0) // 偶数列从上到下 + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数列从下到上 + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "全部横向") // 单一方向横向:始终从左到右 + { + for (int row = 0; row < intColumn; row++) + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + else if (strDirection == "全部竖向") // 单一方向竖向:始终从上到下 + { + for (int col = 0; col < intLine; col++) + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + break; + } + case "左下": // 起始点 (0, intColumn-1) + { + if (strDirection == "横向") // S型横向 + { + for (int row = intColumn - 1; row >= 0; row--) + { + if ((intColumn - 1 - row) % 2 == 0) // 偶数行(从底部数)从左到右 + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数行(从底部数)从右到左 + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "竖向") // S型竖向 + { + for (int col = 0; col < intLine; col++) + { + if (col % 2 == 0) // 偶数列从下到上 + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数列从上到下 + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "全部横向") // 单一方向横向:始终从左到右 + { + for (int row = intColumn - 1; row >= 0; row--) + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + else if (strDirection == "全部竖向") // 单一方向纵向:始终从下到上 + { + for (int col = 0; col < intLine; col++) + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + break; + } + case "右上": // 起始点 (intLine-1, 0) + { + if (strDirection == "横向") // S型横向 + { + for (int row = 0; row < intColumn; row++) + { + if (row % 2 == 0) // 偶数行从右到左 + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数行从左到右 + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "竖向") // S型竖向 + { + for (int col = intLine - 1; col >= 0; col--) + { + if ((intLine - 1 - col) % 2 == 0) // 偶数列(从右数)从上到下 + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数列(从右数)从下到上 + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "全部横向") // 单一方向横向:始终从右到左 + { + for (int row = 0; row < intColumn; row++) + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + else if (strDirection == "全部竖向") // 单一方向竖向:始终从上到下 + { + for (int col = intLine - 1; col >= 0; col--) + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + break; + } + case "右下": // 起始点 (intLine-1, intColumn-1) + { + if (strDirection == "横向") // S型横向 + { + for (int row = intColumn - 1; row >= 0; row--) + { + if ((intColumn - 1 - row) % 2 == 0) // 偶数行(从底部数)从右到左 + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数行(从底部数)从左到右 + { + for (int col = 0; col < intLine; col++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "竖向") // S型竖向 + { + for (int col = intLine - 1; col >= 0; col--) + { + if ((intLine - 1 - col) % 2 == 0) // 偶数列(从右数)从下到上 + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + else // 奇数列(从右数)从上到下 + { + for (int row = 0; row < intColumn; row++) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + } + else if (strDirection == "全部横向") // 单一方向横向:始终从右到左 + { + for (int row = intColumn - 1; row >= 0; row--) + { + for (int col = intLine - 1; col >= 0; col--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + else if (strDirection == "全部竖向") // 单一方向竖向:始终从下到上 + { + for (int col = intLine - 1; col >= 0; col--) + { + for (int row = intColumn - 1; row >= 0; row--) + { + location[col, row] = index.ToString().PadLeft(maxNumberLength, '0'); + index++; + } + } + } + break; + } + } + } + + + /// + /// copy标准,支持回复处理 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + // 新增載具內容 + // 傳入值: 各欄位新增值 + // 傳回值: success(成功), fail(失敗) + public static string AddCarrierStateDetail_M(string CarrierNo, string BCIP, string ContentID, int CarrierPosition = 1, int ContentFlag = 0, string AdditionalXml = "", string ComponentNo = "N/A", string UserNo = defString, string LotSerial = defString, Collection colSQL = null) + { + string AddCarrierStateDetailRet = default(string); + // CarrierPosition:預設放置為第1個位置 + // ContentFlag:0:Tray 1:Stocker + // 200612/15 Ben 新增ComponentNo + + var CollectionSQL = new Collection(); + string strSQLAddField = ""; + string strSQLAddValue = ""; + string strSQL = ""; + kcEQP.clsCarrierBasis objCarrierBasis = new kcEQP.clsCarrierBasis(); + + try + { + // //Combine SQL + strSQLAddField = "Insert Into tblWIPCarrierStateDetail (CarrierNo,CarrierPosition,BCIP,ContentID,Flag,LotNo,ComponentNo"; + strSQLAddValue = " Values ('" + CarrierNo + "'," + CarrierPosition + ",'" + BCIP + "','" + ContentID + "'," + ContentFlag + ",'" + ContentID + "','" + ComponentNo + "'"; + + if (string.IsNullOrEmpty(AdditionalXml)) + { + // 當沒有額外的欄位時,直接給定strSQL + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + } + else + { + // 加上additional的field & value 後傳回 + strSQL = SeparateAddXML_Add(ref strSQLAddField, ref strSQLAddValue, AdditionalXml); + } + CollectionSQL.Add(strSQL); + + + strSQL = $"DELETE FROM tblWIPCarrierStateDetail WHERE CarrierNo='{CarrierNo}' AND LotNo ='{ContentID}'"; + //回复处理 + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL); + + + + strSQL = " Update tblWIPLotState Set CarrierNo = '" + CarrierNo + "' Where LotNo = '" + ContentID + "' "; + CollectionSQL.Add(strSQL); + + + + strSQL = " Update tblWIPLotState Set CarrierNo = '' Where LotNo = '" + ContentID + "' "; + //回复处理 + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL); + + + //xuyan 2023/5/31 上载具更改载具状态,载具上有批号 CarrierState=1 + objCarrierBasis.UpdateCarrierState(ref CollectionSQL, CarrierNo, UserNo, 1); + + //收集 + if (colSQL != null) + { + foreach (var item in CollectionSQL) + { + colSQL.Add(item); + } + } + + //執行SQL指令 + //ExecuteSQLNoneQuery_UPD(Convert.ToString(DataBaseType), strConnectionString, CollectionSQL); + + //Return success + AddCarrierStateDetailRet = "success"; + } + catch (Exception e1) + { + // 回傳失敗 + AddCarrierStateDetailRet = "fail"; + + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } // New Exception("kcEQP.AddCarrierStateDetail: " & e1.Message) + finally + { + if (objCarrierBasis != null) + { + objCarrierBasis.Dispose(); + } + } + + return AddCarrierStateDetailRet; + + + } + + + + + /// + /// copy 标准,刷生产批信息 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static string LoadLotBasisJoinState_M1001(ref DataSet dsTemp, string BaseLotNo = defString, string OPNo = defString, string Status = defString, string OrgLotNo = defString, string BatchNo = defString, string BoxNo = defString, string BatchSerial = defString, string LotState = defString, string RONo = defString, int ItemNo = defInteger, string MONo = defString, string ProductNo = defString, string ProductVersion = defString, string CustomerNo = defString, int HotLot = defInteger, + DateTime EndWIPDate = default(DateTime), DateTime FromWIPDate = default(DateTime), string LotNo = defString, string LotSerial = defString, string ProcessNo = defString, string NodeId = defString, string BRNo = defString, string PSNo = defString, string PhaseNo = defString, int HaveComponent = defInteger, int HaveLevel = defInteger, string LinkName = defString, string ERFStatus = defString, string AreaNo = defString, string ProcessVersion = defString, string SORGLotNo = defString, string AdditionalXml = "", string CustomerLotNo = defString, string ComponentNo = defString, string FactoryNo = defString, int CurQTY = defInteger, bool blnShowPartialLot = true, int PartialType = defInteger) + { + string LoadLotBasisJoinState = default(string); + // 此 Function 將資料以XML方式取出 + // 傳入值: 索引值 + + IDbConnection cnnTemp = null; + AppSettings objSetting = new AppSettings(); + var drTemp = default(DbDataReader); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + string strSQL = ""; + try + { + // 2013/03/13, Hank, 開啟Report Mode + cnnTemp = CreateConnection(strConnectionString); + + + + // 2016/12/26 YF, 取出作業站多人加工模式MultiOperatorMode + // 2016/10/19 YF, 取出作業站用料選項取MaterialOption + // 2016-08-11, Joe, Add PartialMode + // PS.要優先使用tblWIPLotState的資料,故tblWIPLotState的欄位要放在Select前面 + // 2017/10/27 OwenLiu, 因應部份報工,同時取出流程主檔 PartialType + + + strSQL = "SELECT A.*, B.*, C.OPName, C.OPShortName, C.PartialMode, C.MaterialOption, C.MultiOperatorMode, D.PartialType,E.PRODUCTNAME"; + strSQL += " FROM tblWIPLotState A join tblWIPLotBasis B ON A.BaseLotNo = B.BaseLotNo"; + strSQL += " left join tblOPBasis C ON A.OPNo = C.OPNo"; + strSQL += " left join tblPRSProcessBasis D ON A.ProcessNo = D.ProcessNo AND A.ProcessVersion = D.ProcessVersion"; + strSQL += " INNER JOIN TBLPRDPRODUCTBASIS E ON B.ProductNo=E.PRODUCTNO and B.ProductVersion=E.ProductVersion"; // 20180808 + strSQL += " WHERE A.LotNo IS NOT NULL "; + + // LotBasis condition + if (BaseLotNo != defString) + strSQL = strSQL + " And B.BaseLotNo = '" + BaseLotNo + "'"; + if (OrgLotNo != defString) + strSQL = strSQL + " And B.OrgLotNo like '" + OrgLotNo + "'"; + if (LotState != defString) + { + int i; + string[] aLotState = Strings.Split(LotState, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And B.LotState In(" + aLotState[0]; + for (i = 1; i <= Information.UBound(aLotState); i++) // 其餘的 + + strSQL = strSQL + "," + aLotState[i]; + strSQL = strSQL + ")"; + } + if (RONo != defString) + strSQL = strSQL + " And B.RONo like '" + RONo + "'"; + if (ItemNo != defInteger) + strSQL = strSQL + " And B.ItemNo = " + ItemNo; + if (MONo != defString) + strSQL = strSQL + " And B.MONo like '" + MONo + "'"; + if (ProductNo != defString) + strSQL = strSQL + " And B.ProductNo like '" + ProductNo + "'"; + if (ProductVersion != defString) + { + int i; + string[] aVersion = Strings.Split(ProductVersion, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And B.ProductVersion In('" + aVersion[0] + "'"; + for (i = 1; i <= Information.UBound(aVersion); i++) // 其餘的 + strSQL = strSQL + ",'" + aVersion[i] + "'"; + strSQL = strSQL + ")"; + } + if (CustomerNo != defString) + strSQL = strSQL + " And B.CustomerNo = '" + CustomerNo + "'"; + if (HotLot != defInteger) + strSQL = strSQL + " And B.HotLot = " + HotLot; + if (FromWIPDate != defDateTime) + strSQL = strSQL + " And B.WIPDate >= '" + Strings.Format((DateTime)FromWIPDate, "yyyy-MM-dd HH:mm:ss") + "'"; + if (EndWIPDate != defDateTime) + { + // 如果傳入值不包含時間則加上23:59:59 + if (EndWIPDate == EndWIPDate.Date) + strSQL = strSQL + " And B.WIPDate <='" + Strings.Format((DateTime)EndWIPDate, "yyyy-MM-dd") + " 23:59:59" + "'"; + else + strSQL = strSQL + " And B.WIPDate <='" + Strings.Format((DateTime)EndWIPDate, "yyyy/MM/dd HH:mm:ss") + "'"; + } + if (CustomerLotNo != defString) + strSQL += " And B.CustomerLotNo = '" + CustomerLotNo + "'"; + + // LotState condition + // cQueue = 0 + // cRunning = 1 + // cWait = 2 + // cHold = 3 + // cINV = 11 + if (Status != defString) + { + int i; + string[] aStatus = Strings.Split(Status, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And A.Status In(" + aStatus[0]; + for (i = 1; i <= Information.UBound(aStatus); i++) // 其餘的 + + strSQL = strSQL + "," + aStatus[i]; + strSQL = strSQL + ")"; + } + + if (LotNo != defString) + { + // strSQL = strSQL & " And A.LotNo = '" & LotNo & "'" + int i; + string[] aLotNo = Strings.Split(LotNo, "|"); // 各批號用|分隔 + strSQL = strSQL + " And A.LotNo In('" + aLotNo[0] + "'"; + for (i = 1; i <= Information.UBound(aLotNo); i++) // 其餘的 + + strSQL = strSQL + ",'" + aLotNo[i] + "'"; + strSQL = strSQL + ")"; + } + + if (LotSerial != defString) + strSQL = strSQL + " And A.LotSerial = '" + LotSerial + "'"; + + if (ProcessNo != defString) + { + strSQL = strSQL + " And A.ProcessNo = '" + ProcessNo + "'"; + if (ProcessVersion != defString) + { + int i; + string[] aVersion = Strings.Split(ProcessVersion, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And A.ProcessVersion In('" + aVersion[0] + "'"; + for (i = 1; i <= Information.UBound(aVersion); i++) // 其餘的 + strSQL = strSQL + ",'" + aVersion[i] + "'"; + strSQL = strSQL + ")"; + } + } + if (OPNo != defString) + strSQL = strSQL + " And A.OPNo = '" + OPNo + "'"; + if (NodeId != defString) + strSQL = strSQL + " And A.NodeId = '" + NodeId + "'"; + if (BRNo != defString) + strSQL = strSQL + " And A.BRNo = '" + BRNo + "'"; + if (PSNo != defString) + strSQL = strSQL + " And A.PSNo = '" + PSNo + "'"; + if (HaveComponent != defInteger) + strSQL = strSQL + " And A.HaveComponent = " + HaveComponent; + if (HaveLevel != defInteger) + strSQL = strSQL + " And A.HaveLevel = " + HaveLevel; + if (LinkName != defString) + strSQL = strSQL + " And A.LinkName = '" + LinkName + "'"; + if (PhaseNo != defString) + { + int i; + string[] aPhase = Strings.Split(PhaseNo, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And A.PhaseNo In(" + aPhase[0]; + for (i = 1; i <= Information.UBound(aPhase); i++) // 其餘的 + strSQL = strSQL + "," + aPhase[i]; + strSQL = strSQL + ")"; + } + if (SORGLotNo != defString) + strSQL += " And A.ORGLotNo = '" + SORGLotNo + "'"; + + // 2016-08-09, Joe, 不顯示Partial站的Lot + if (blnShowPartialLot == false) + strSQL += " And (PartialMode is null OR PartialMode = 0) "; + + // 2017/10/27 OwenLiu, 增加 PartialType 參數處理 + if (!PartialType.Equals(defInteger)) + strSQL += " AND D.PartialType = " + PartialType; + + // ERF Status + // Status + // 0:Create + // 1:Department + // 2:Customer + // 11:Final + // 12:Abort + // 21:Release + + if (ERFStatus != defString) + { + int i; + string[] aERF = Strings.Split(ERFStatus, "|"); // 各狀態值用|分隔 + strSQL = strSQL + " And A.LotNo In (Select LotNo From tblWIPERFBasis Where Status In (" + aERF[0]; + for (i = 1; i <= Information.UBound(aERF); i++) // 其餘的 + strSQL = strSQL + "," + aERF[i]; + strSQL = strSQL + "))"; + } + if (AreaNo != defString) + strSQL = strSQL + " And A.AreaNo = '" + AreaNo + "'"; + + if (BatchNo != defString) + strSQL = strSQL + " And A.BatchNo = '" + BatchNo + "'"; + + if (BoxNo != defString) + strSQL = strSQL + " And A.BoxNo = '" + BoxNo + "'"; + + if (BatchSerial != defString) + strSQL = strSQL + " And A.BatchSerial = '" + BatchSerial + "'"; + + if (ComponentNo != defString) + { + int i; + string[] aryComp = Strings.Split(ComponentNo, "|"); // 各狀態值用|分隔 + strSQL += " And A.LotNo In (Select Distinct LotNo From tblWIPComponentState Where (ComponentNo='" + aryComp[0] + "'"; + for (i = 1; i <= Information.UBound(aryComp); i++) // 其餘的 + strSQL += " Or ComponentNo='" + aryComp[i] + "'"; + strSQL += "))"; + } + + if (FactoryNo != defString) + strSQL = strSQL + " And A.FactoryNo = '" + FactoryNo + "'"; + + if (CurQTY != defInteger) + strSQL += " And A.CurQTY = " + CurQTY; + + if (AdditionalXml != "") + // 加上additional的condition + strSQL = strSQL + SeparateAddXML_Condition(AdditionalXml); + + // //Select data + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "BasisJoinState", cnnTemp); + // //Combine return value + LoadLotBasisJoinState = CombineXMLReturnValue("loadlotbasisjoinstate", "BasisJoinState", "DataSet", FormatXMLSchema(dsTemp.GetXmlSchema()), dsTemp.GetXml(), ""); + } + catch (Exception e1) + { + LoadLotBasisJoinState = "fail"; + throw; + } // (New Exception("kcWIP.LoadLotBasisJoinState: " & e1.Message)) + + finally + { + CloseConnection(cnnTemp); + //if (!daTemp == null) + // daTemp.Dispose(); + if (dsTemp != null) + dsTemp.Dispose(); + } + return LoadLotBasisJoinState; + } + + + /// + /// COPY 标准 + /// + /// + /// + /// + /// + // 將資料以XML方式取出tblWIPCarrierState + // 傳入值: 索引值 + // 傳回值: XML(成功), fail(失敗) + public string LoadCarrierState_M(string CarrierNo = defString, string AdditionalXml = "", int CarrierState = defInteger) + { + string LoadCarrierStateRet = default(string); + + string strSQL = ""; + IDbConnection cnnTemp = null; + + var dsCarrier = default(DataSet); + + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + // //SQL Command + strSQL = "Select * From tblWIPCarrierState Where CarrierNo Is Not Null "; + + if (CarrierNo != defString) + { + strSQL = strSQL + "And CarrierNo = '" + CarrierNo + "'"; + } + + if (CarrierState != defInteger) + { + strSQL = strSQL + "And CarrierState = '" + CarrierState + "'"; + } + + // Additional Condition + if (!string.IsNullOrEmpty(AdditionalXml)) + { + strSQL = strSQL + SeparateAddXML_Condition(AdditionalXml); + } + + // //Select data + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daCarrier = New OleDb.OleDbDataAdapter(cmmTemp) + dsCarrier = new DataSet(); + ExecuteSQLQuery_Adapter(strSQL, dsCarrier, "CarrierState", cnnTemp); + + // //Combine return value + //LoadCarrierStateRet = CombineXMLReturnValue("LoadCarrierState".ToLower(), "CarrierState", "DataSet", FormatXMLSchema(dsCarrier.GetXmlSchema()), dsCarrier.GetXml(), ""); + } + + catch (Exception e1) + { + // 回傳失敗 + LoadCarrierStateRet = "fail"; + + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("kcEQP.LoadCarrierState: " & e1.Message) + + finally + { + CloseConnection(cnnTemp); + if (dsCarrier != null) + { + dsCarrier.Dispose(); + } + + } + + return LoadCarrierStateRet; + + } + + + /// + /// COPY tc 载具寿命检查 + /// + /// + /// + public static bool CheckCarrierLife_M(string CarrierNo, string CarrierType, string UserNo) + { + bool bolCheckCarrierLife_M = true; + + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + IDbConnection cnnTemp = null; + Collection CollectionSQL = new Collection(); + string strSQL; + + try + { + + cnnTemp = CreateConnection(strConnectionString); + + //载具寿命 + DataTable dt01 = new DataTable(); + strSQL = $" select * from TBLCUSCARRIERLIFE where CARRIERNO = '{CarrierNo}' "; + ExecuteSQLQuery_Adapter(strSQL, dt01, cnnTemp); + + //载具类别寿命设定 + DataTable dt = new DataTable(); + strSQL = $" select * from TBLCUSCARRIERLIFESET where CARRIERTYPE = '{CarrierType}' "; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + if (dt.Rows.Count > 0) + { + if (dt01.Rows.Count > 0) + { + string ACCUMULATEQTY = dt01.Rows[0]["ACCUMULATEQTY"].ToString(); //累计数量 + + string ALERTCOUNT = dt.Rows[0]["ALERTCOUNT"].ToString(); //预警次数 + string LIMITCOUNT = dt.Rows[0]["LIMITCOUNT"].ToString(); //单次上限 + + //累计数量达到预警次数 + if (decimal.Parse(ACCUMULATEQTY) >= decimal.Parse(ALERTCOUNT)) + { + bolCheckCarrierLife_M = false; + } + + } + else + { + strSQL = $@" insert into TBLCUSCARRIERLIFE (CARRIERNO,ACCUMULATEQTY,ACCTOTALUSEDQTY,CREATOR,CREATEDATE) + values ('{CarrierNo}',0,0,'{UserNo}',sysdate)"; + CollectionSQL.Add(strSQL); + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + } + + } + } + catch (Exception ex) + { + throw; + } + finally + { + CloseConnection(cnnTemp); + } + + return bolCheckCarrierLife_M; + } + + + + // 写入客制表 TBLWIPPRDSTATE_LQ(现况)与 TBLWIPPRDLOG_LQ(履历) + // 入参说明: + // LotNo - 子批批号(分批后新批号) + // ProductID - PanelID + // EQPID - 设备编号(可为空) + // OPNo - 作业站编号 + // CarrierID - 载具编号(可为空) + // State - 状态(固定传 1) + // ProductType - 产品类别(固定传 "0") + public static void SaveWIPPrdStateLog_M(string LotNo, string ProductID, string EQPID, + string OPNo, string CarrierID, int State, string ProductType, string LotSerial, Collection colSQL = null) + { + var CollectionSQL = new Collection(); + string strSQL; + + // 空值保护,LOG 表 EQPID/CARRIERID 为 NOT NULL + string strEQPID = string.IsNullOrEmpty(EQPID) ? "" : EQPID.Replace("'", "''"); + string strCarrierID = string.IsNullOrEmpty(CarrierID) ? "" : CarrierID.Replace("'", "''"); + string strLotNo = LotNo.Replace("'", "''"); + string strProductID = ProductID.Replace("'", "''"); + string strOPNo = OPNo.Replace("'", "''"); + string strProdType = ProductType.Replace("'", "''"); + + try + { + //查询有没有进站 + + + + // 插入 TBLWIPPRDSTATE_LQ(现况表,EQPID/CARRIERID 允许空) + strSQL = "INSERT INTO TBLWIPPRDSTATE_LQ " + + "(LOTNO, PRODUCTID, EQPID, STATE, OPNO, CARRIERID, PRODUCTTYPE, CREATEDATE) " + + "VALUES " + + "('" + strLotNo + "', '" + strProductID + "', '" + strEQPID + "', " + + State + ", '" + strOPNo + "', '" + strCarrierID + "', '" + strProdType + "', SYSDATE)"; + CollectionSQL.Add(strSQL); + + + strSQL = $"DELETE FROM TBLWIPPRDSTATE_LQ WHERE LOTNO='{strLotNo}'"; + //回复处理 + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL); + + // 插入 TBLWIPPRDLOG_LQ(履历表) + strSQL = "INSERT INTO TBLWIPPRDLOG_LQ " + + "(LOTNO, PRODUCTID, EQPID, OPNO, CARRIERID, PRODUCTTYPE, CREATEDATE) " + + "VALUES " + + "('" + strLotNo + "', '" + strProductID + "', '" + strEQPID + "', " + + "'" + strOPNo + "', '" + strCarrierID + "', '" + strProdType + "', SYSDATE)"; + CollectionSQL.Add(strSQL); + + + strSQL = $"DELETE FROM TBLWIPPRDLOG_LQ WHERE LOTNO='{strLotNo}'"; + //回复处理 + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL); + + if (colSQL != null) + { + foreach (string str in CollectionSQL) + { + colSQL.Add(str); + } + } + else + { + // 提交至数据库(两条 INSERT 在同一事务内执行) + //ExecuteSQLNoneQuery_UPD(Convert.ToString(DataBaseType), strConnectionString, CollectionSQL); + } + + + } + catch (Exception ex) + { + if (ex.InnerException != null) + throw ex.InnerException; + else + throw; + } + } + + /// + /// 进站 + /// + /// + /// + /// + /// + /// + /// + /// + public static bool funTrackIn_Inquiry_LQ(ref List aryMessage, ref List aryException, string EQPID, string ID, string remark) + { + bool funTrackIn_Inquiry = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + var CollectionSQL = new Collection(); + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + string OPNO = ""; + + + + + + + int EQPSTATE = 0; //设备管控闲置状态 + + int nowEQPSTATE = 0; //现在设备管控闲置状态 + + string strLotNo = "";//生产批号 + + try + { + //先检查 设备状态是否是闲置 + + //检查设备是否存在 + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + //throw new iMESException.MESException("0000-202001", +" :设备不存在!"); + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + //获取设备管控闲置状态是多少 + strSQL = "Select EQUIPMENTSTATE From TBLEQPSTATECONTROL Where CONTROLNO Is Not Null AND CONTROLTYPE ='EQP Break Down' AND CONTROLNO='Idle'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + EQPSTATE = Conversions.ToInteger(drTemp["EQUIPMENTSTATE"]); + } + else + { + //throw new iMESException.MESException("0000-202001", "闲置状态未设定!"); + clsERP.combineMessage(ref aryMessage, mmsg: "[%设备闲置状态未设定!%]"); + return false; + } + drTemp.Close(); + + + // ============================ + // 自动判断ID类型(通过序号规则) + // LCSIP开头 → CarrierID(通用载具) + // X1088开头 → CarrierID(专用载具) + // 其他 → ProductID(PanelID或UnitID) + // ============================ + string strIDValue = ID; + string strProductID_Auto = ""; + string strCarrierID_Auto = ""; + string strAutoType = ""; + string Type; + + + if (!string.IsNullOrEmpty(strIDValue)) + { + // 自动判断ID类型 + if (strIDValue.StartsWith("LCSIP") || strIDValue.StartsWith("X1088")) + { + // 载具ID + strAutoType = "2"; // CarrierID + strCarrierID_Auto = strIDValue; + } + else + { + // 产品ID(PanelID或UnitID) + strAutoType = "1"; // ProductID + strProductID_Auto = strIDValue; + } + } + + // 根据自动判断结果或手动指定的Type决定处理逻辑 + string strFinalType; + + strFinalType = strAutoType; + //获取生产批批号 + if (strFinalType == "1") + { + if (string.IsNullOrEmpty(strProductID_Auto)) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%Product_id 没有传值%]"); + return false; + } + DataTable dt = new DataTable(); + strSQL = $"select * from TBLWIPPRDSTATE_LQ where PRODUCTID = '{strProductID_Auto}' and state = 1"; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + if (dt.Rows.Count != 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: $"[%产品ID({strProductID_Auto})对应多个批次,请检查数据来源。%]"); + return false; + } + strLotNo = dt.Rows[0]["LotNo"].ToString(); + } + else if (strFinalType == "2") + { + if (string.IsNullOrEmpty(strCarrierID_Auto)) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%Carrier_id 没有传值%]"); + return false; + } + DataTable dt = new DataTable(); + strSQL = $"select * from TBLWIPPRDSTATE_LQ where carrierid = '{strCarrierID_Auto}' and state = 1"; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + if (dt.Rows.Count > 0) + { + + strLotNo = dt.Rows[0]["LotNo"].ToString(); + } + else + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%找不到对应的生产批%]"); + return false; + } + } + strSQL = $"select * from tblwiplotstate where lotno = '{strLotNo}'"; + + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + OPNO = drTemp["OPNO"].ToString(); + string STATUS = drTemp["STATUS"].ToString(); + string LotSerial = drTemp["LOGGROUPSERIAL"].ToString(); + if (STATUS == "4") + { + var colNextNode = GetNextNode(strLotNo, "Null", defString, AdditionalXml: ""); + using (kcWIP.clsLot objLot = new kcWIP.clsLot()) + { + var drLotState = objLot.GetLotBasisJoinState(LotNo: strLotNo); // 取得最新的LotState + objLot.SetLotStateToNextOP(Conversions.ToLong(drLotState["LotStamp"]), strLotNo, Convert.ToString(colNextNode["NodeID"])); + //objLot.SetLotStateToWait(Conversions.ToLong(drLotState["LotStamp"]), strLotNo, 2, UserNo: "EAP", WaitDescription: "ExeOSReturn finish then GetNextNode failed,can not find next node,linkname:" + strLinkName + "."); + + } + + } + else if (STATUS == "1") + { + funReentryUpdateTime(LotSerial, strLotNo, OPNO, ref CollectionSQL); + goto Reentry; + } + else if (STATUS == "0") + { + funReentryUpdateTime(LotSerial, strLotNo, OPNO, ref CollectionSQL); + } + } + drTemp.Close(); + Check_CIRequest_LOTMaterial(ref aryMessage, EQPID, strLotNo, OPNO); + if (aryMessage.Count > 0) + { + return false; + } + //调用标准进站 + var datSendTime = default(DateTime); // 送達時間 + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = string.Empty; // Request User -紀錄操作人員 + Dictionary dicPars = new Dictionary(); //固定引數,Request傳入的一般參數 + Dictionary dicPars_DataTable = new Dictionary(); //固定引數,Request傳入的DataTable參數 + + //添加批号 + dicPars.Add("lotno", strLotNo); + dicPars.Add("equipmentno", EQPID); + + + AutoexecutionLot_Lot(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CI", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck)); + strSQL = $"update TBLWIPPRDSTATE_LQ set eqpid = '{EQPID}',opno = '{OPNO}' where PRODUCTID = '{strProductID_Auto}' and state = 1"; + CollectionSQL.Add(strSQL); + strSQL = $"update TBLWIPLOTLOG_REPORT set CIREMARK = '{remark}' where LoggroupSerial =(select LoggroupSerial from TBLWIPLOTSTATE where LOTNO='{strLotNo}')"; + CollectionSQL.Add(strSQL); + + Reentry: + ; + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + //strLotNo = Conversions.ToString(dsData.Tables["TBLWIPLOTBASIS"].Rows[0]["BASELOTNO"]); + + + funTrackIn_Inquiry = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funTrackIn_Inquiry; + + } + /// + /// 出站 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool funTrackOut_Inquiry_LQ(ref List aryMessage, ref List aryException, string EQPID, string ID, string remark) + { + bool funTrackOut_Inquiry = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + + + string strMLotNo = "";//母生产批号 + string strNLotNo = "";//子生产批号 + string strProductNo = "";//产品号 + string strProductVersion = "";//产品版本 + string strSeqNoRule = "";//序号规则 + string strSeqNoType = "";//序号类别 + string strSeqNoSize = "";//起始位置 + string strDirection = "";//走向 + string strOPNO = ""; + + string strUnitIdOrPannid = "";//UnitId或者Pannid + + bool bolLastLot = false;//是否是最后一笔 + + DataSet dataSetLotNo = new DataSet(); + + kcWIP.clsLot objLot = new kcWIP.clsLot(); + + Collection CollectionSQL = new Collection(); + + bool bolInsertMONoProperty = false; //插入工单属性 + + decimal decMQTY = 0; //母批数量 + + try + { + //先检查 设备状态是否是闲置 + + //检查设备是否存在 + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + + // ============================ + // 自动判断ID类型(通过序号规则) + // LCSIP开头 → CarrierID(通用载具) + // X1088开头 → CarrierID(专用载具) + // 其他 → ProductID(PanelID或UnitID) + // ============================ + string strIDValue = ID; + string strProductID_Auto = ""; + string strCarrierID_Auto = ""; + string strAutoType = ""; + string Type = ""; + + + if (!string.IsNullOrEmpty(strIDValue)) + { + // 自动判断ID类型 + if (strIDValue.StartsWith("LCSIP") || strIDValue.StartsWith("X1088")) + { + // 载具ID + Type = "2"; // CarrierID + strCarrierID_Auto = strIDValue; + } + else + { + // 产品ID(PanelID或UnitID) + Type = "1"; // ProductID + strProductID_Auto = strIDValue; + } + } + + // 根据自动判断结果或手动指定的Type决定处理逻辑 + + // 17单 需求二/三:依作业站属性自动解绑(TRAY/小载具)+分批出站,在标准判型出站之前 + bool bolAutoUnbindHandled = false; + if (!funAutoUnbindCheckOut_LQ(ref aryMessage, Type, strProductID_Auto, strCarrierID_Auto, EQPID, out bolAutoUnbindHandled)) + { + return false; + } + if (bolAutoUnbindHandled) + { + return true; + } + + + + if (Type == "1") + { + if (strProductID_Auto is null && strProductID_Auto == "") + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%Product_id 没有传值%]"); + return false; + } + DataTable dt = new DataTable(); + strSQL = $"select * from TBLWIPPRDSTATE_LQ where PRODUCTID = '{strProductID_Auto}' and state = 1"; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + if (dt.Rows.Count != 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: $"[%产品ID({strProductID_Auto})对应多个批次,请检查数据来源。%]"); + return false; + } + strMLotNo = dt.Rows[0]["LotNo"].ToString(); + } + else if (Type == "2") + { + //if (strCarrierID_Auto is null && strCarrierID_Auto == "") + //{ + // clsERP.combineMessage(ref aryMessage, mmsg: "[%Carrier_id 没有传值%]"); + // return false; + //} + if (strCarrierID_Auto is null || strCarrierID_Auto == "") //17单 M3:原 && 恒不成立,检核形同虚设,应为 || + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%Carrier_id 没有传值%]"); + return false; + } + + DataTable dt = new DataTable(); + strSQL = $"select * from TBLWIPPRDSTATE_LQ where (carrierid = '{strCarrierID_Auto}' or TrayID = '{strCarrierID_Auto}') and state = 1"; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + //foreach (DataRow row in dt.Rows) + //{ + if (dt.Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%找不到对应的生产批%]"); + return false; + } + strMLotNo = dt.Rows[0]["LotNo"].ToString(); + } + + //获取母批的基本信息 + strSQL = $"SELECT A.PRODUCTNO,A.PRODUCTVERSION,B.STATUS,B.CURQTY,B.OPNO,B.LOTSTAMP FROM TBLWIPLOTBASIS A LEFT JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.BASELOTNO ='{strMLotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS_MLOT", cnnTemp); + + + if (dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:批次状态不是执行中,不允许出站!%]"); + return false; + } + + //检查母批状态是否是执行中 STATUS 是否为 1 + if (Conversions.ToInteger(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["STATUS"]) != 1) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:母生产批状态不是执行中!%]"); + return false; + } + + //检查是否是用当前设备进站 + strSQL = "SELECT EQUIPMENTNO FROM TBLWIPTEMP_EQUIPMENT WHERE LotNo='" + strMLotNo + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (EQPID != drTemp["EQUIPMENTNO"].ToString()) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:当前设备不是进站设备,不允许出站!%]"); + return false; + } + } + drTemp.Close(); + //调用标准出站 + var datSendTime = default(DateTime); // 送達時間 + object blnRuleCheck = true; + bool blnEXETriggerOP = false; + string strComputerName = string.Empty; // Request Client ComputerName + string strCurUserNo = string.Empty; // Request User -紀錄操作人員 + Dictionary dicPars = new Dictionary(); //固定引數,Request傳入的一般參數 + Dictionary dicPars_DataTable = new Dictionary(); //固定引數,Request傳入的DataTable參數 + + //添加批号 + dicPars.Add("lotno", strMLotNo); + dicPars.Add("equipmentno", EQPID); + + //出站明细 + DataTable dtLotAttrib = new DataTable(); //特性 + //添加LotNo列 + dtLotAttrib.Columns.Add("LotNo", typeof(string)); + dtLotAttrib.Columns.Add("AttribNo", typeof(string)); + dtLotAttrib.Columns.Add("AttribValue", typeof(string)); + + decMQTY = decimal.Parse(dsData.Tables["TBLWIPLOTBASIS_MLOT"].Rows[0]["CURQTY"].ToString()); + + //查询生产批的绑定特性,这里是出站,所以使用TEMP表 + strSQL = $"SELECT ATTRIBNO,ATTRIBVALUE FROM TBLWIPTEMP_ATTRIB WHERE LOTNO='{strMLotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPTEMP_ATTRIB", cnnTemp); + if (dsData.Tables["TBLWIPTEMP_ATTRIB"].Rows.Count > 0) + { + foreach (DataRow dr in dsData.Tables["TBLWIPTEMP_ATTRIB"].Rows) + { + DataRow drLotAttrib = dtLotAttrib.NewRow(); + drLotAttrib["LotNo"] = strMLotNo; + drLotAttrib["AttribNo"] = dr["ATTRIBNO"].ToString(); + if (dr["AttribNo"].ToString() == "GoodQty") + { + drLotAttrib["AttribValue"] = decMQTY; + + } + else if (dr["AttribNo"].ToString() == "ScrapQty") + { + drLotAttrib["AttribValue"] = 0; + } + else if (dr["AttribNo"].ToString() == "DefectQty") + { + drLotAttrib["AttribValue"] = 0; + } + else + { + drLotAttrib["AttribValue"] = dr["ATTRIBVALUE"].ToString(); + } + + dtLotAttrib.Rows.Add(drLotAttrib); + } + } + + + dicPars_DataTable.Add("lotattrib", dtLotAttrib); + + // ============================ + // 出站成功后,插入TBLWIPCONT_LOTRECORD记录(remark生产数据) + // ============================ + if (!string.IsNullOrEmpty(strMLotNo) && !string.IsNullOrEmpty(remark)) + { + string strLotSerial = ""; + string strBaseLotNo = ""; + string strOPNos = ""; + string strLogGroupSerial = ""; + string strEventUserNo = ""; + + strSQL = $"SELECT LOTSERIAL, BASELOTNO, OPNO, LOGGROUPSERIAL, EVENTUSERNO FROM TBLWIPLOTSTATE WHERE LOTNO = '{strMLotNo}'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strLotSerial = drTemp["LOTSERIAL"] is DBNull ? "" : drTemp["LOTSERIAL"].ToString(); + strBaseLotNo = drTemp["BASELOTNO"] is DBNull ? "" : drTemp["BASELOTNO"].ToString(); + strOPNos = drTemp["OPNO"] is DBNull ? "" : drTemp["OPNO"].ToString(); + strLogGroupSerial = drTemp["LOGGROUPSERIAL"] is DBNull ? "" : drTemp["LOGGROUPSERIAL"].ToString(); + strEventUserNo = drTemp["EVENTUSERNO"] is DBNull ? "" : drTemp["EVENTUSERNO"].ToString(); + } + drTemp.Close(); + + string strEventTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); + strSQL = $"INSERT INTO TBLWIPCONT_LOTRECORD (BASELOTNO, LOTNO, LOTSERIAL, OPNO, LOTRECORD, USERNO, EVENTTIME, LOGGROUPSERIAL) " + + $"VALUES ('{strBaseLotNo}', '{strMLotNo}', '{strLotSerial}', '{strOPNos}', '{remark}', '{strEventUserNo}', " + + $"TO_DATE('{strEventTime}', 'SYYYY-MM-DD HH24:MI:SS'), '{strLogGroupSerial}')"; + CollectionSQL.Add(strSQL); + } + AutoexecutionLot_Lot(ref blnEXETriggerOP, dicPars, dicPars_DataTable, "CO", datSendTime, strCurUserNo, strComputerName, Convert.ToBoolean(blnRuleCheck)); + #region 出站扣料逻辑 + // 字符串类型 + string LotSerial = ""; + string OPNo = ""; + string InventoryNo = ""; + string MONo = ""; + string CurUnitNo = ""; + string ProductNo = ""; + string ProductVersion = ""; + string BaseLotNo = ""; + string BRNo = ""; + string LogGroupSerial = ""; + long lngLotStamp = 0; + decimal decCurQty = 0; + int intMaterialOption = 0; + int PhaseNo = 0; + DataTable dtMaterial = new DataTable(); + DataTable dtMaterialLot = new DataTable(); + DateTime datEventTime = DateTime.Now; + // 2016/10/26 YF, 取出作業站的用料選項 + // 2018/2/9, Ning, CurUnitNo改取自tblWIPLotState + // 1.取出Temp LotState的資料 + if (strDataBaseType.ToUpper() == "ORACLE") + { + strSQL = "Select A.LotSerial, A.OPNo, A.InventoryNo, A.MONo, B.CurUnitNo, A.ProductNo, A.ProductVersion, A.BaseLotNo, " + " B.BRNo, B.LogGroupSerial, B.LotStamp, B.CurQty, B.PhaseNo, C.MaterialOption " + " From tblWIPTemp_LotState A, tblWIPLotState B, tblOPBasis C " + " Where A.LotNo = '" + strMLotNo + "'" + " And A.LotNo = B.LotNo " + " And B.OPNo = C.OPNo "; + } + else + { + strSQL = "Select A.LotSerial, A.OPNo, A.InventoryNo, A.MONo, B.CurUnitNo, A.ProductNo, A.ProductVersion, A.BaseLotNo, " + " B.BRNo, B.LogGroupSerial, B.LotStamp, B.CurQty, B.PhaseNo, C.MaterialOption " + " From tblWIPTemp_LotState A With (NoLock), tblWIPLotState B With (NoLock), tblOPBasis C With (NoLock) " + " Where A.LotNo = '" + strMLotNo + "'" + " And A.LotNo = B.LotNo " + " And B.OPNo = C.OPNo "; + } + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + LotSerial = drTemp["LotSerial"].ToString(); + OPNo = drTemp["OPNo"].ToString(); + InventoryNo = drTemp["InventoryNo"].ToString(); + MONo = drTemp["MONo"].ToString(); + CurUnitNo = drTemp["CurUnitNo"].ToString(); + ProductNo = drTemp["ProductNo"].ToString(); + ProductVersion = drTemp["ProductVersion"].ToString(); + BaseLotNo = drTemp["BaseLotNo"].ToString(); + BRNo = drTemp["BRNo"].ToString(); + LogGroupSerial = drTemp["LogGroupSerial"].ToString(); + lngLotStamp = Conversions.ToLong(drTemp["LotStamp"]); + decCurQty = Convert.ToDecimal(drTemp["CurQty"]); + intMaterialOption = Conversions.ToInteger(drTemp["MaterialOption"]); + PhaseNo = Conversions.ToInteger(drTemp["PhaseNo"]); // 2020/11/26 Steven Mantis:0082084 [PAD]eRunCard_調整 BR 生產記錄 + } + else + { + throw new iMESException.MESException("0000-202003", "[%LotNo%] : " + strMLotNo); + } + drTemp.Close(); + using (var obj = new clsLot()) + { + + + // 4.Material + // 2016/10/26 YF, 依用料選項來執行扣料的方式 + switch (intMaterialOption) + { + case 0: + { + // 發料點(線邊倉或工單) + obj.SHR_COMaterial(strMLotNo, LogGroupSerial, LotSerial, LotSerial, "EAP", datEventTime, InventoryNo, MONo, OPNo, ref cnnTemp, ref CollectionSQL, dicPars_DataTable["equipment"], dtMaterial, dtMaterialLot); + break; + } + + case 1: + { + // 設備 + var objHandler = new clsMaterialHandler(); + + if (false) + { + // 採先進先出扣料 + objHandler.SHR_COMaterialByEQP_FIFO(strMLotNo, LogGroupSerial, LotSerial, ref CollectionSQL, ref dtMaterial, ref dtMaterialLot, dicPars_DataTable["equipment"], datEventTime); + } + else + { + // 採輸入料批扣料 + objHandler.SHR_COMaterialByEQP(strMLotNo, LogGroupSerial, LotSerial, ref CollectionSQL, ref dtMaterial, ref dtMaterialLot, dicPars_DataTable["equipment"], datEventTime); + } + + + + // Case 2 + // 生產線, 待組裝版再實作 + + // Case 3 + // 工位, 待組裝版再實作 + + objHandler = null; + break; + } + + default: + { + throw new iMESException.MESException("0000-003000", "[%MaterialOption%]:" + intMaterialOption + " [%NOT DEFINE%]!"); + } + } + } + #endregion + + + + if (CollectionSQL.Count > 0) + { + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + + + funTrackOut_Inquiry = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + + if (objLot != null) + { + objLot = null; + } + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funTrackOut_Inquiry; + + } + + public static void funReentryUpdateTime(string LotSerial, string LotNo, string OPNO, ref Collection CollectionSQL) + { + try + { + strSQL = $"update TBLWIPLOTLOG_REPORT set STARTTIME = SYSDATE,CHECKINTIME = SYSDATE where LOGGROUPSERIAL = '{LotSerial}'"; + CollectionSQL.Add(strSQL); + //strSQL = $"update TBLWIPLOTLOG set STARTTIME = SYSDATE where LOGGROUPSERIAL = '{LotSerial}'"; + //CollectionSQL.Add(strSQL); + strSQL = $"insert into tblcusentry(LOTSERIAL,LotNO,STARTTIME,OPNO) Values('{LotSerial}','{LotNo}',SYSDATE,'{OPNO}')"; + CollectionSQL.Add(strSQL); + //回复处理 + strSQL = $"DELETE FROM tblcusentry WHERE LOTSERIAL='{LotSerial}'"; + Collection argcolSQL_Rows = null; + objReverse.AddReverseUpdateContent(ref LotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows); + } + catch (Exception ex) + { + throw; + } + finally + { + + } + } + + #endregion + + #region 进出站对物料的管控 + public static DataSet Check_CIRequest_LOTMaterial(ref List aryMessage, string EquipmentNo, string LotNo, string OPNo) + { + DataSet Check_CIRequest_LOTMaterialRet = default(DataSet); + // Dim result As Boolean = False + var result = new DataSet(); + + var All_result = new DataSet(); + var dsTemp = default(DataSet); + string InXML, OutXML; + string MONO; + string Materialoption = ""; + string LotQty = defString; + string strMessage = ""; + string strError = ""; + try + { + object[] aryPars; + + aryPars = clsCom.funGetMethodParameters("kcEQP", "clsEQPBasis", "ShowEquipmentBasis"); + aryPars[0] = EquipmentNo; + dsTemp = clsCom.funExecuteMethod("kcEQP", "clsEQPBasis", "ShowEquipmentBasis", ref aryPars) as DataSet; + + foreach (DataTable item in dsTemp.Tables) + All_result.Tables.Add(item.Copy()); + + // 檢查設備是否存在 + if (All_result.Tables["EQPEquipmentBasis"] == null || All_result.Tables["EQPEquipmentBasis"].Rows.Count <= 0) + { + throw new iMESException.MESException("0000-200003", "[%EQPNO%]:" + EquipmentNo + " [%IS NOT EXIST%]"); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(All_result.Tables["EQPEquipmentBasis"].Rows[0]["IssueState"], 2, false))) + { + throw new iMESException.MESException("0000-200015", "[%EQPNO%]:" + EquipmentNo + " [%PLEASE CHECK ISSUE STATE%]"); + } + + aryPars = clsCom.funGetMethodParameters("kcWIP", "clsLot", "ShowLotBasisJoinState"); + aryPars[0] = LotNo; + dsTemp = clsCom.funExecuteMethod("kcWIP", "clsLot", "ShowLotBasisJoinState", ref aryPars) as DataSet; + + foreach (DataTable item in dsTemp.Tables) + All_result.Tables.Add(item.Copy()); + + // 檢查生產批是否存在 + if (All_result.Tables["BasisJoinState"] == null || All_result.Tables["BasisJoinState"].Rows.Count <= 0) + { + throw new iMESException.MESException("0000-200003", "[%LOTNO%]:" + LotNo + " [%IS NOT EXIST%]"); + } + if (All_result.Tables["BasisJoinState"].Rows[0]["CURQTY"] == null || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(All_result.Tables["BasisJoinState"].Rows[0]["CURQTY"], 0, false))) + { + throw new iMESException.MESException("0000-200017", "[%LOTNO%]:" + LotNo + " [%LOTCURQTY%] [%CANT BE%] 0"); + } + else if (All_result.Tables["BasisJoinState"].Rows[0]["CURQTY"] == null || Convert.ToBoolean(Operators.ConditionalCompareObjectLess(All_result.Tables["BasisJoinState"].Rows[0]["CURQTY"], 0, false))) + { + throw new iMESException.MESException("0000-200017", "[%LOTNO%]:" + LotNo + " [%LOTCURQTY%] [%MUST BE GREATER THAN%] 0 "); + } + else + { + LotQty = All_result.Tables["BasisJoinState"].Rows[0]["CURQTY"].ToString(); + MONO = All_result.Tables["BasisJoinState"].Rows[0]["MONO"].ToString(); + } + + + aryPars = clsCom.funGetMethodParameters("kcOP", "clsOPBasis", "ShowOPBasis"); + aryPars[0] = OPNo; + dsTemp = clsCom.funExecuteMethod("kcOP", "clsOPBasis", "ShowOPBasis", ref aryPars) as DataSet; + + foreach (DataTable item in dsTemp.Tables) + All_result.Tables.Add(item.Copy()); + + // 檢查作業站編號是否存在 + if (All_result.Tables["OPBasis"] == null || All_result.Tables["OPBasis"].Rows.Count <= 0) + { + throw new iMESException.MESException("0000-200003", "[%OPNO%]:" + OPNo + " [%IS NOT EXIST%]"); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(All_result.Tables["OPBasis"].Rows[0]["IssueState"], 2, false))) + { + throw new iMESException.MESException("0000-200015", "[%OPNO%]:" + OPNo + " [%PLEASE CHECK ISSUE STATE%]"); + } + else + { + Materialoption = All_result.Tables["OPBasis"].Rows[0]["Materialoption"].ToString(); + } + + aryPars = clsCom.funGetMethodParameters("kcOE", "clsOEBasis", "ShowMOMaterialList"); + aryPars[0] = MONO; + aryPars[2] = OPNo; + dsTemp = clsCom.funExecuteMethod("kcOE", "clsOEBasis", "ShowMOMaterialList", ref aryPars) as DataSet; + + foreach (DataTable item in dsTemp.Tables) + All_result.Tables.Add(item.Copy()); + + DataTable dtMOMaterialList; + dtMOMaterialList = new DataTable("materiallist"); + dtMOMaterialList.Columns.Add("materialno", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("materiallotno", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("materiallevel", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("checklotno", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("checkmtlpass", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("useqty", Type.GetType("System.String")); + dtMOMaterialList.Columns.Add("unitno", Type.GetType("System.String")); + + + aryPars = clsCom.funGetMethodParameters("kcWIP", "clsLot", "ShowChkLotCI_Material"); + aryPars[0] = LotNo; + aryPars[1] = OPNo; + aryPars[2] = EquipmentNo; + aryPars[3] = true; + dsTemp = clsCom.funExecuteMethod("kcWIP", "clsLot", "ShowChkLotCI_Material", ref aryPars) as DataSet; + foreach (DataTable item in dsTemp.Tables) + All_result.Tables.Add(item.Copy()); + + DataRow drData; + foreach (DataRow r in All_result.Tables["all_materiallist"].Rows) + { + drData = dtMOMaterialList.NewRow(); + // drData("materialno") = r("materialno").ToString + drData["materialno"] = r["inputmaterialno"].ToString(); + drData["materiallotno"] = r["materiallotno"].ToString(); // 沒有物料批號資料時請填N/A + drData["materiallevel"] = r["materiallevel"].ToString(); // 0:Material(物料)。1:Product(半成品)。 + drData["unitno"] = r["unitno"].ToString(); + drData["checklotno"] = r["checklotno"].ToString(); // 0:False 1:True + drData["checkmtlpass"] = r["checkmtlpass"].ToString(); // -1: 不用查核 0:fail查核失敗, 上料數不足 1:pass查核成功, 上料數足夠 + dtMOMaterialList.Rows.Add(drData); + + // 若有傳出的DataTable中有錯誤訊息已 ;分號 做分隔 + if (!string.IsNullOrEmpty(r["errorcode"].ToString()) | !string.IsNullOrEmpty(r["errormessage"].ToString())) + { + if (string.IsNullOrEmpty(strError)) + { + strError = r["errorcode"].ToString(); + } + else + { + strError = strError + ";" + r["errorcode"].ToString(); + } + + if (string.IsNullOrEmpty(strMessage)) + { + strMessage = "[%materialno%]:" + r["materialno"].ToString() + " " + r["errormessage"].ToString(); + } + else + { + strMessage = strMessage + ";" + "[%materialno%]:" + r["materialno"].ToString() + " " + r["errormessage"].ToString(); + } + + } + + } + + if (!string.IsNullOrEmpty(strMessage)) + { + throw new iMESException.MESException(strError, strMessage); + } + + result.Tables.Add(dtMOMaterialList); + } + + catch (Exception ex) + { + throw; + } + finally + { + Check_CIRequest_LOTMaterialRet = result; + + if (dsTemp != null) + dsTemp.Dispose(); + if (result != null) + result.Dispose(); + if (All_result != null) + All_result.Dispose(); + } + + return Check_CIRequest_LOTMaterialRet; + + } + + + + #endregion + + + #region "MakingCode明码查询" + /// + /// 明码查询接口:根据PanelSN查MAKINGCODE和UNITSN,并校验设备可用性 + /// + public static bool funMakingCode(ref List aryMessage, ref List aryException, string PanelSN, string EQPID, ref string strMAKINGCODE, ref string strUNITSN) + { + bool funMakingCode = default(bool); + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + string strLotNo = ""; + + try + { + // ============================ + // 1. 校验设备是否存在 + // ============================ + strSQL = "SELECT 1 FROM TBLEQPEQUIPMENTBASIS WHERE EQUIPMENTNO='" + EQPID + "' AND ISSUESTATE = 2"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: EQPID + "[%:设备不存在!%]"); + return false; + } + drTemp.Close(); + + // ============================ + // 2. 根据PanelSN(作为ProductID)查询LotNo + // ============================ + strSQL = "SELECT LOTNO FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTID = '" + PanelSN + "' AND STATE = '1'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%PanelSN(" + PanelSN + ")未找到对应批次!%]"); + return false; + } + strLotNo = drTemp["LOTNO"].ToString(); + drTemp.Close(); + + // ============================ + // 3. 校验设备:根据Lot状态决定校验逻辑 + // STATUS=0(待进站):检查设备是否可用(参考frmBR_L_CI_GEN加载可用设备逻辑) + // STATUS=1(已进站):检查所选设备是否是当前批次进站设备 + // ============================ + strSQL = "SELECT STATUS FROM TBLWIPLOTSTATE WHERE LOTNO = '" + strLotNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%批次(" + strLotNo + ")状态未知,不允许查询!%]"); + return false; + } + int lotStatus = Convert.ToInt32(drTemp["STATUS"]); + drTemp.Close(); + + if (lotStatus == 0) + { + // STATUS=0 待进站:参考frmBR_L_CI_GEN带出所有可用设备,检查设备是否在可用设备列表中 + DataTable dtAvailableEquipment_All; + DataTable dtAvailableEquipment_Chamber; + using (var objLot = new clsLot()) + { + var dsAvailable = ShowAvailableEquipment_All(strLotNo); + dtAvailableEquipment_All = dsAvailable.Tables[0]; + + } + + // 检查设备是否在可用设备列表中(AllowExecute=1) + DataRow[] drAvailable = dtAvailableEquipment_All.Select("AllowExecute=1 And EquipmentNo = '" + EQPID + "'"); + if (drAvailable.Length == 0) + { + + clsERP.combineMessage(ref aryMessage, mmsg: "[%设备(" + EQPID + ")不在批次(" + strLotNo + ")的可用设备列表中,不允许查询!%]"); + return false; + + } + } + else if (lotStatus == 1) + { + // STATUS=1 已进站:检查所选设备是否是当前批次进站设备 + strSQL = "SELECT A.LOTNO FROM TBLWIPLOTSTATE A " + + "LEFT JOIN TBLWIPTEMP_EQUIPMENT B ON A.LOTNO = B.LOTNO " + + "WHERE A.LOTNO = '" + strLotNo + "' AND A.STATUS = 1 AND B.EQUIPMENTNO = '" + EQPID + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%批次(" + strLotNo + ")未在设备(" + EQPID + ")上进站,不允许查询!%]"); + return false; + } + drTemp.Close(); + } + else + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%批次(" + strLotNo + ")状态为(" + lotStatus + "),不支持该状态的明码查询!%]"); + return false; + } + + // ============================ + // 4. 查询 TBLPRDPRODUCTBASIS 获取 MAKINGCODE + // ============================ + strSQL = "SELECT A.MAKINGCODE FROM TBLPRDPRODUCTBASIS A " + + "INNER JOIN TBLWIPLOTBASIS B ON A.PRODUCTNO = B.PRODUCTNO AND A.PRODUCTVERSION = B.PRODUCTVERSION " + + "WHERE B.BASELOTNO = '" + strLotNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strMAKINGCODE = drTemp["MAKINGCODE"].ToString(); + } + else + { + strMAKINGCODE = ""; + } + drTemp.Close(); + + // ============================ + // 5. 查询 TBLPCSDIELOG_LQ 获取 Panel 对应的 Unit 信息 + // ============================ + strSQL = "SELECT UNITID,BadFlag FROM TBLPCSDIELOG_LQ WHERE PANLEID = '" + PanelSN + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + var listUnitSN = new List(); + int location = 1; + while (drTemp.Read()) + { + string unitId = drTemp["UNITID"].ToString(); + int badFlag = 0; + if (Convert.ToInt16(drTemp["BadFlag"].ToString()) == 0) + { + badFlag = 1; + + } + else + { + badFlag = 0; + } + if (!string.IsNullOrEmpty(unitId)) + { + listUnitSN.Add("SN" + location.ToString() + ":" + unitId + ":" + badFlag); + location++; + } + } + drTemp.Close(); + strUNITSN = string.Join(";", listUnitSN); + + funMakingCode = true; + exitfun: + ; + } + catch (Exception ex) + { + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + drTemp?.Close(); + CloseConnection(cnnTemp); + } + return funMakingCode; + } + public static DataSet ShowAvailableEquipment_All(string LotNo, bool GetAccessory = false, bool GetMaterial = false, bool GetRecipe = false, string AdditionalXml = "", bool ChkCapacity = true, bool MultiQCList = false) + { + DataSet ShowAvailableEquipment_AllRet = default(DataSet); + + // PS1.Lot已被派工至非指定機台或非Area上的機台(未處理) + // PS2.派工的部份先不加入,因派工機制尚待加強,故先不納入考量. + + IDbConnection cnnTemp = null; + // Dim daTemp As New OleDb.OleDbDataAdapter + var dsTemp = new DataSet(); + DbDataReader drTemp = null; + + DataRow[] drSel; + string strAreaNo, strSerialNo, EquipmentNo, strDesc; + string strEquipmentState = ""; + bool blnAllowExecute; + bool blnAssign = false; // 是否有指定機台 + bool blnDispatch = false; // 是否有派工 + int i, j; + + string strEQPCapability = string.Empty; // 設備能力 + int intOPReference; // 參數要參考0:Product,1:Module + string strOPNo, strReferenceNo, strReferenceVersion; + string strProductNo, strProductVersion; + + strDesc = ""; + strProductNo = ""; + strProductVersion = ""; + AppSettings objSetting = new AppSettings(); + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + // 1.取出Lot相關資料. + strSQL = "Select A.AreaNo,A.OPReference, A.LotSerial,A.OPNo,B.ProductNo,B.ProductVersion,A.ModuleNo,A.ModuleVersion From tblWIPLotState A,TBLWIPLOTBASIS B Where A.LotNo=B.BASELotNo And A.LotNo='" + LotNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strAreaNo = drTemp["AreaNo"].ToString(); + strSerialNo = drTemp["LotSerial"].ToString(); + strOPNo = drTemp["OPNo"].ToString(); + intOPReference = Conversions.ToInteger(drTemp["OPReference"]); + + // 0122190: 【美迪凯】配件管控失效 + // 製程模塊(Module)不支援禁用設備設定、指定配件, + // 若生產批進到模組製程中, 設備與配件需取得產品上的設定。 + strReferenceNo = drTemp["ProductNo"].ToString(); + strReferenceVersion = drTemp["ProductVersion"].ToString(); + strProductNo = drTemp["ProductNo"].ToString(); + strProductVersion = drTemp["ProductVersion"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200003", "[%Get temp data fail%]: [%LotState%]" + Constants.vbCrLf + "[%LotNo%]: " + LotNo); + // Throw New iMESException.MESException("0000-200003", "[Get LotNo:" & LotNo & " Lot State join Temp Lot State,is not exist.]") + } + drTemp.Close(); + + + // 1.1 設系統參數SelectAllAreaEQP (0:否, 1:是),判斷是否要選擇該作業站的所有機台,2010/01/06,by yumei + // 2010/11/24,sammi.加上Module. + string strParameterValue; + + strSQL = "Select ParameterValue From tblSYSParameter Where Upper(ParameterNo)='SELECTALLAREAEQP'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strParameterValue = drTemp["ParameterValue"].ToString(); + } + else + { + strParameterValue = ""; + } + drTemp.Close(); + + + if (strParameterValue == "1") + { + // 取出產品或Module作業站的所有區域 + string strAreaNo_All = ""; + strSQL = "Select AreaNo From tblPRDOPArea" + " Where ProductNo='" + strReferenceNo + "'" + " And ProductVersion='" + strReferenceVersion + "'" + " And OPNo='" + strOPNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTemp.Read()) + { + // 配合後面sql in語法使用,要加單引號 + if (string.IsNullOrEmpty(strAreaNo_All)) + { + strAreaNo_All = "'" + drTemp["AreaNo"] + "'".ToString(); + } + else + { + strAreaNo_All = strAreaNo_All + "," + "'" + drTemp["AreaNo"] + "'".ToString(); + } + } + drTemp.Close(); + + + if (string.IsNullOrEmpty(strAreaNo_All)) + { + strAreaNo = "'" + strAreaNo + "'"; + } + else + { + strAreaNo = strAreaNo_All; + } + } + else + { + strAreaNo = "'" + strAreaNo + "'"; + } + + // 2.取出CheckIn Confirm不可使用的機台狀態 + // {生產}允許使用,不過必須檢查Capacity + strSQL = "Select EquipmentState From tblEMSViolateStatusChange " + " Where ViolativeState In (Select EquipmentState From tblEQPStateControl " + " Where Upper(ControlType) ='WIP TRACKING' And Upper(ControlNo) = 'CHECKINCONFIRM')" + " And EquipmentState <> 1"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strEquipmentState = strEquipmentState + "," + drTemp["EquipmentState"].ToString(); + while (drTemp.Read()) + strEquipmentState = strEquipmentState + "," + drTemp["EquipmentState"].ToString(); + // 去除第一個逗號 + strEquipmentState = Strings.Mid(strEquipmentState, 2, Strings.Len(strEquipmentState) - 1); + } + drTemp.Close(); + + + // 2.5 檢查是否有設定產品作業站的設備能力 (Equipment Capability) Larry 2007/12/21 + // 2010/11/23,sammi.改寫 + strSQL = "Select POA.AttribValue" + " From tblPRDOP PO,tblPRDOPAttrib POA " + " Where PO.SerialNo = POA.SerialNo " + " And PO.ProductNo='" + strReferenceNo + "'" + " And PO.ProductVersion='" + strReferenceVersion + "'" + " And PO.OPNo='" + strOPNo + "'" + " And UPPER (POA.AttribNo) = UPPER ('EQPCapability') "; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strEQPCapability = drTemp["AttribValue"].ToString(); + } + else + { + strEQPCapability = string.Empty; + } + drTemp.Close(); + + + // 3.以AreaNo取出所有機台. + // 有設定Equipment Capability的話 要過濾掉OFF狀態的設備 + if (!string.IsNullOrEmpty(strEQPCapability)) + { + // EQPSwitch 0:OFF 1:ON + // 當有設定PRDOPAttrib.EQPCapability時就只取 EQPSwitch=1(ON)的狀態 + + strSQL = " SELECT * "; + strSQL += " FROM (SELECT AreaEQP.*, EQPCapability.Capability, EQPCapability.EQPSwitch "; + strSQL += " FROM (SELECT EquipmentType, EquipmentNo, EquipmentName, "; + if (strDataBaseType != "oracle") + { + strSQL += " IsNull(EquipmentClass, '') AS EquipmentClass, "; + strSQL += " IsNull(Capacity, -1) AS Capacity, "; + strSQL += " IsNull(LoadPort, 0) AS EQPLoadPort, QCListNo "; + } + else + { + strSQL += " Nvl(EquipmentClass, '') AS EquipmentClass, "; + strSQL += " Nvl(Capacity, -1) AS Capacity, "; + strSQL += " Nvl(LoadPort, 0) AS EQPLoadPort, QCListNo "; + } + strSQL += " FROM tblEQPEquipmentBasis "; + strSQL += " WHERE IssueState = 2 And EquipmentNo IN ( "; + strSQL += " SELECT ObjectNo "; + strSQL += " FROM tblSMDAreaRelation "; + strSQL += " WHERE ContainAreaNo in (" + strAreaNo + ") "; + strSQL += " AND ObjectType = 2) "; + strSQL += " OR EquipmentNo IN ( "; + strSQL += " SELECT EquipmentNo "; + strSQL += " FROM tblEQPGroupDetail "; + strSQL += " WHERE EquipmentGroup IN ( "; + strSQL += " SELECT ObjectNo "; + strSQL += " FROM tblSMDAreaRelation "; + strSQL += " WHERE ContainAreaNo in (" + strAreaNo + ") "; + strSQL += " AND ObjectType = 4))) AreaEQP "; + strSQL += " LEFT OUTER JOIN "; + strSQL += " (SELECT * "; + strSQL += " FROM tblEMSEQPCapabilityStatus "; + strSQL += " WHERE UPPER(Capability) = '" + strEQPCapability.ToUpper() + "') EQPCapability "; + strSQL += " ON AreaEQP.EquipmentNo = EQPCapability.EquipmentNo "; + strSQL += " ) A "; + strSQL += " WHERE A.EQPSwitch = 1 "; + + + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "AreaEquipment_A", cnnTemp); + } + + else + { + strSQL = "Select EquipmentType,EquipmentNo, EquipmentName, "; + if (strDataBaseType != "oracle") + { + strSQL += " IsNull(EquipmentClass,'') as EquipmentClass , IsNull(Capacity,-1) as Capacity , IsNull(LoadPort,0) as EQPLoadPort, QCListNo "; + } + else + { + strSQL += " Nvl(EquipmentClass,'') as EquipmentClass , Nvl(Capacity,-1) as Capacity , Nvl(LoadPort,0) as EQPLoadPort, QCListNo "; + } + strSQL += " From tblEQPEquipmentBasis" + " Where IssueState = 2 And (EquipmentNo In (Select ObjectNo From tblSMDAreaRelation " + " Where ContainAreaNo in (" + strAreaNo + ") And ObjectType = 2)" + " Or EquipmentNo In (Select EquipmentNo From tblEQPGroupDetail " + " Where EquipmentGroup In (Select ObjectNo From tblSMDAreaRelation " + " Where ContainAreaNo in (" + strAreaNo + ") And ObjectType = 4)))"; + + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "AreaEquipment_A", cnnTemp); + + } + + //子设备禁用 + strSQL = "select equipmentno from tblPRDEQPConstraint WHERE PRODUCTNO='" + strReferenceNo + "' AND OPNO='" + strOPNo + "'"; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "PRDEQPConstraint_SubEquipment", cnnTemp); + + // 使用主設備查詢子設備 + // 2021/06/08 TsungYu ===================================================================================== + string strEQP = string.Empty; + string strChamber = string.Empty; + string strParameterChamber = string.Empty; + + strSQL = "Select ParameterValue From tblSYSParameter Where Upper(ParameterNo) = 'CHAMBERMANAGE'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strParameterChamber = drTemp["ParameterValue"].ToString(); + } + else + { + strParameterChamber = ""; + } + drTemp.Close(); + + + // 2021/8/26,Ning, 98778: 客户:浏阳泰科; 系统MESSeries 6.0.5.15; 问题:生产执行进站报错。 + if (strParameterChamber == "1" && dsTemp.Tables["AreaEquipment_A"].Rows.Count > 0) + { + foreach (DataRow dr in dsTemp.Tables["AreaEquipment_A"].Rows) + strEQP += string.Format("'{0}',", dr["EquipmentNo"].ToString()); + // If strEQP = String.Empty Then + // Throw New iMESException.MESException("0000-200015", "[%AreaNo%]: " & strAreaNo & " [%Can not find equipmentno data%]") + // End If + strEQP = strEQP.TrimEnd(','); + + strSQL = "select EquipmentType,EquipmentNo,EquipmentName,BelongEquipmentNo, "; + if (strDataBaseType != "oracle") + { + strSQL += " IsNull(EquipmentClass, '') AS EquipmentClass, "; + strSQL += " IsNull(Capacity, -1) AS Capacity, "; + strSQL += " IsNull(LoadPort, 0) AS EQPLoadPort, QCListNo "; + } + else + { + strSQL += " Nvl(EquipmentClass, '') AS EquipmentClass, "; + strSQL += " Nvl(Capacity, -1) AS Capacity, "; + strSQL += " Nvl(LoadPort, 0) AS EQPLoadPort, QCListNo "; + } + strSQL += " from tblEQPEquipmentBasis where BelongEquipmentNo in (" + strEQP + ") And IssueState = 2 order by EquipmentNo"; + strSQL += " "; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "Chamber", cnnTemp); + + string strChamberEquipmentNo = string.Empty; + + + foreach (DataRow dr in dsTemp.Tables["Chamber"].Rows) + { + // clsAE不存在新增欄位 + if (dsTemp.Tables["Chamber"].Columns.Contains("AllowExecute") == false) + { + var colChamberAE = new DataColumn("AllowExecute", Type.GetType("System.Int16")); + colChamberAE.DefaultValue = 0; + dsTemp.Tables["Chamber"].Columns.Add(colChamberAE); + } + // clsDescription不存在新增欄位 + if (dsTemp.Tables["Chamber"].Columns.Contains("Description") == false) + { + // Description,不可執行的說明,Default="". + var colChamberDE = new DataColumn("Description", Type.GetType("System.String")); + colChamberDE.DefaultValue = ""; + dsTemp.Tables["Chamber"].Columns.Add(colChamberDE); + } + + EquipmentNo = dr["EquipmentNo"].ToString(); + blnAllowExecute = true; + // 檢查子機台 + // 檢查是否為可用狀態 + if (!string.IsNullOrEmpty(strEquipmentState)) + { + strSQL = "Select EquipmentNo From tblEMSEquipmentState " + " Where EquipmentNo = '" + EquipmentNo + "' And EquipmentState In (" + strEquipmentState + ")"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) // 不可使用 + { + blnAllowExecute = false; + strDesc += "EquipmentState is not available."; + } + drTemp.Close(); + + } + // 检查禁用设备 + if (dsTemp.Tables["PRDEQPConstraint_SubEquipment"].Rows.Count > 0) + { + DataRow[] drTemp_SubEQP; + drTemp_SubEQP = dsTemp.Tables["PRDEQPConstraint_SubEquipment"].Select("EquipmentNo='" + dr["EquipmentNo"] + "'"); + if (drTemp_SubEQP.Length > 0) + { + blnAllowExecute = false; + strDesc = "[%Equipment Is Constraint%]"; + } + } + if (ChkCapacity) + { + // 可使用的情況下,檢查Capacity(-1不限制Capacity).已在機台上的量+目前此批的量. + if (blnAllowExecute && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["Capacity"], -1, false))) + { + strSQL = "Select Nvl(Sum(CurQty),0) As SumCurQty From tblWIPLotState " + " Where LotNo In (Select LotNo From tblWIPTemp_Equipment " + " Where EquipmentNo='" + EquipmentNo + "')" + " Or LotNo = '" + LotNo + "'"; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectGreater(drTemp["SumCurQty"], dr["Capacity"], false))) + { + blnAllowExecute = false; + strDesc += "[%Capacity is full%]"; + } + } + drTemp.Close(); + + } + } + + // 2007/10/24 Lena + // 可使用的情況下,檢查 LoadPort(上貨區數量)(<=0 不限制LoadPort) + if (blnAllowExecute && Convert.ToBoolean(Operators.ConditionalCompareObjectGreater(dr["EQPLoadPort"], 0, false))) + { + strSQL = "Select Count(*) as LotQty From tblWIPTemp_Equipment " + " Where EquipmentNo = '" + EquipmentNo + "'"; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(drTemp["LotQty"], dr["EQPLoadPort"], false))) + { + blnAllowExecute = false; // 不可使用, 已超過 LoadPort 設定的數量 + strDesc += "[%LoadPort is full.%]"; + } + } + drTemp.Close(); + + } + // 變更狀態. + dr.BeginEdit(); + if (blnAllowExecute) + { + dr["AllowExecute"] = 1; // 可用 + // 組合予後面使用,可使用的,才加入. + strChamberEquipmentNo += ",'" + EquipmentNo + "'"; + } + else + { + dr["Description"] = strDesc; + + } // 不可用說明 + dr.EndEdit(); + } + } + + + + // ========================================================================================================== + + + // 4.Add Column + // RecipeGroup + var colRG = new DataColumn("RecipeGroup", Type.GetType("System.String")); + colRG.DefaultValue = "N/A"; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colRG); + // RecipeVersion,Default=0. + var colRV = new DataColumn("RecipeVersion", Type.GetType("System.String")); + colRV.DefaultValue = 0; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colRV); + // EquipmentSource,1:參數指定機台,2:Area上的機台,Default=2. + var colES = new DataColumn("EquipmentSource", Type.GetType("System.Int32")); + colES.DefaultValue = 2; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colES); + // DispatchOrder,-1:沒有被派工,其他:派工順序,Default=-1. + var colDO = new DataColumn("DispatchOrder", Type.GetType("System.Int32")); + colDO.DefaultValue = -1; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colDO); + // AllowExecute,0:No,1:Yes,Default=0. + var colAE = new DataColumn("AllowExecute", Type.GetType("System.Int16")); + colAE.DefaultValue = 0; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colAE); + // Description,不可執行的說明,Default="". + var colDE = new DataColumn("Description", Type.GetType("System.String")); + colDE.DefaultValue = ""; + dsTemp.Tables["AreaEquipment_A"].Columns.Add(colDE); + + // Kevin 2014/01/05,模治具處理 + // 取出產品設定的模治具 + strSQL = " Select * From tblPRDAccessory" + " Where ProductNo ='" + strReferenceNo + "'" + " And ProductVersion = '" + strReferenceVersion + "'" + " And OPNo ='" + strOPNo + "'" + " Order By AccessoryType,AccessoryNo"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "PRDAccessory", cnnTemp); + + + // 5.指定機台,可能有多台,指定機台一定在Area的集合內. + string strAssEQP = ""; + if (strDataBaseType != "oracle") + { + strSQL = "Select A.EquipmentNo,IsNull(A.RecipeGroup,'N/A') As RecipeGroup,IsNull(B.RecipeVersion,0) As RecipeVersion " + " From tblPRDOPEQPRecipe A left outer join (Select RecipeGroup,RecipeVersion From tblEQPRecipeBasis Where CurVersion=1) B " + " On A.RecipeGroup=B.RecipeGroup " + " Where A.SerialNo='" + strSerialNo + "'"; + } + else + { + strSQL = "Select A.EquipmentNo,Nvl(A.RecipeGroup,'N/A') As RecipeGroup,Nvl(B.RecipeVersion,0) As RecipeVersion " + " From tblPRDOPEQPRecipe A,(Select RecipeGroup,RecipeVersion From tblEQPRecipeBasis Where CurVersion=1) B " + " Where A.RecipeGroup=B.RecipeGroup(+) " + " And A.SerialNo='" + strSerialNo + "'"; + } + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTemp.Read()) + { + blnAssign = true; + EquipmentNo = drTemp["EquipmentNo"].ToString(); + drSel = dsTemp.Tables["AreaEquipment_A"].Select("EquipmentNo='" + EquipmentNo + "'"); + if (drSel.Length > 0) + { + drSel[0].BeginEdit(); + drSel[0]["RecipeGroup"] = drTemp["RecipeGroup"]; + drSel[0]["RecipeVersion"] = drTemp["RecipeVersion"]; + drSel[0]["EquipmentSource"] = 1; // 來自參數指定機台 + drSel[0].EndEdit(); + strAssEQP += "," + EquipmentNo; + } + } + drTemp.Close(); + + + // 有指定機台的情況下,紀錄其他非指定機台不可使用的原因. + if (blnAssign) + { + strDesc = "Have assigned equipment(" + Strings.Mid(strAssEQP, 2) + "),but current equipment is not assigned."; + drSel = dsTemp.Tables["AreaEquipment_A"].Select("EquipmentSource=2"); + var loopTo = drSel.Length - 1; + for (j = 0; j <= loopTo; j++) + { + drSel[j].BeginEdit(); + drSel[j]["Description"] = strDesc; + drSel[j].EndEdit(); + } + } + + // 6.檢查各機台的可用性. + string strEquipmentNo = ""; + string strRecipe = ""; + string strSel = ""; + + if (blnAssign) + strSel += " And EquipmentSource=1"; // 取出指定機台 + if (blnDispatch) + strSel += " And DispatchOrder<>-1"; // 取出派工機台 + + if (string.IsNullOrEmpty(strSel)) + { + drSel = dsTemp.Tables["AreaEquipment_A"].Select(); + } + else + { + strSel = Strings.Replace(strSel, "And", "", 1, 1, CompareMethod.Text); + drSel = dsTemp.Tables["AreaEquipment_A"].Select(strSel); + } + + var loopTo1 = drSel.Length - 1; + for (i = 0; i <= loopTo1; i++) + { + blnAllowExecute = true; + strDesc = ""; + EquipmentNo = drSel[i]["EquipmentNo"].ToString(); + + // 檢查是否為可用狀態 + if (!string.IsNullOrEmpty(strEquipmentState)) + { + strSQL = "Select EquipmentNo From tblEMSEquipmentState " + " Where EquipmentNo = '" + EquipmentNo + "' And EquipmentState In (" + strEquipmentState + ")"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) // 不可使用 + { + blnAllowExecute = false; + strDesc += "EquipmentState is not available."; + } + drTemp.Close(); + + } + + if (ChkCapacity) + { + // 可使用的情況下,檢查Capacity(-1不限制Capacity).已在機台上的量+目前此批的量. + if (blnAllowExecute && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drSel[i]["Capacity"], -1, false))) + { + strSQL = "Select Nvl(Sum(CurQty),0) As SumCurQty From tblWIPLotState " + + " Where LotNo In (Select LotNo From tblWIPTemp_Equipment " + + " Where EquipmentNo='" + EquipmentNo + "')" + " Or LotNo = '" + LotNo + "'"; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectGreater(drTemp["SumCurQty"], drSel[i]["Capacity"], false))) + { + blnAllowExecute = false; + strDesc += "[%Capacity is full%]"; + } + } + drTemp.Close(); + + } + } + + // 2007/10/24 Lena + // 可使用的情況下,檢查 LoadPort(上貨區數量)(<=0 不限制LoadPort) + if (blnAllowExecute && Convert.ToBoolean(Operators.ConditionalCompareObjectGreater(drSel[i]["EQPLoadPort"], 0, false))) + { + strSQL = "Select Count(*) as LotQty From tblWIPTemp_Equipment " + " Where EquipmentNo = '" + EquipmentNo + "'"; + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(drTemp["LotQty"], drSel[i]["EQPLoadPort"], false))) + { + blnAllowExecute = false; // 不可使用, 已超過 LoadPort 設定的數量 + strDesc += "[%LoadPort is full.%]"; + } + } + drTemp.Close(); + + } + + // Kevin 2014/01/05,模治具處理 + // 檢查設備可用性,依產品-作業站-模治具設定決定可用的設備,只要設備沒有掛上設定之模治具就不能使用,CI不開放選取 + // 先判斷是否有設定資料,有的話才要檢查 + if (blnAllowExecute && dsTemp.Tables["PRDAccessory"].Rows.Count > 0) + { + + if (dsTemp.Tables["AccStateTemp"] != null) + { + dsTemp.Tables.Remove("AccStateTemp"); + } + + // 取出AccState + strSQL = "Select A.*,B.AccessoryState,B.AccumulateQty,B.AccSpareQty,C.ScrapLife,C.LifeManage,C.LifeScript,C.LifeTolerance,C.RepairCycle,D.StateName " + " From tblEMSEQPAccState A left join tblEMSAccessoryState B on A.AccessoryNo=B.AccessoryNo " + " And A.AccessoryVersion=B.AccessoryVersion left join tblEQPAccessoryLife C " + " on A.AccessoryType=C.Accessory " + " left join tblEQPAccStateBasis D On B.AccessoryState = D.AccessoryState " + " Where A.EquipmentNo = '" + EquipmentNo + "'" + " Order By A.AccessoryType,A.AccessoryNo"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "AccStateTemp", cnnTemp); + + + bool blnPRDAcc = false; // 是否有產品設定的模治具 + string strAccessoryType = ""; + var aryShowAccType = new ArrayList(); + var aryShowAccNo = new ArrayList(); + + if (dsTemp.Tables["AccStateTemp"].Rows.Count > 0) + { + // 檢查設備是否都有掛產品指定之模治具,相同類別允許掛多個,但至少要有一個 + foreach (DataRow drPRD in dsTemp.Tables["PRDAccessory"].Rows) + { + + // 檢查是否是同個模治具類別 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(strAccessoryType, drPRD["AccessoryType"], false))) + { + if (blnPRDAcc) + { + // 如果已有產品設定的模治具則跳至下一筆 + goto lblAccCheck; + } + } + else + { + // 第一個物料類別不判斷blnPRDAcc + if (!string.IsNullOrEmpty(strAccessoryType)) + { + // 不同模治具類別時,如果上個模治具類別沒有符合的資料,則此設備不可用 + if (blnPRDAcc == false) + { + // 只要有一種類別模治具不符合就是False + blnAllowExecute = false; + } + } + + // 記錄此次模治具類別 + strAccessoryType = drPRD["AccessoryType"].ToString(); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drPRD["AccessoryNo"], "*", false))) + { + // 如果模治具編號為*代表只有指定模治具類別 + foreach (DataRow drAcc in dsTemp.Tables["AccStateTemp"].Rows) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drAcc["AccessoryType"], drPRD["AccessoryType"], false))) + { + // 有符合的代表有掛指定的模治具類別 + blnPRDAcc = true; + // 移除此次加入的類別 + aryShowAccType.Remove(drPRD["AccessoryType"]); + // 有符合一筆即可 + goto lblAccCheck; + } + else + { + blnPRDAcc = false; + if (!aryShowAccType.Contains(drPRD["AccessoryType"])) + { + aryShowAccType.Add(drPRD["AccessoryType"]); + } + } + } + } + else + { + // 如果模治具編號不為*代表有指定模治具 + foreach (DataRow drAcc in dsTemp.Tables["AccStateTemp"].Rows) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drAcc["AccessoryType"], drPRD["AccessoryType"], false)) && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drAcc["AccessoryNo"], drPRD["AccessoryNo"], false))) + { + // 有符合的代表有掛指定的模治具類別 + blnPRDAcc = true; + // 移除此次加入的編號 + aryShowAccNo.Remove(drPRD["AccessoryNo"]); + // 有符合一筆即可 + break; + } + else + { + blnPRDAcc = false; + if (!aryShowAccNo.Contains(drPRD["AccessoryNo"])) + { + aryShowAccNo.Add(drPRD["AccessoryNo"]); + } + } + } + } + lblAccCheck: + ; + + } + + // 多判斷一次最後一個類別 + if (blnPRDAcc == false) + { + // 只要有一種類別模治具不符合就是False + blnAllowExecute = false; + } + + if (blnAllowExecute == false) + { + // 設備沒有掛載產品設定的模治具 + // 不可用說明 + strDesc += "Equipment don't use Product Setup's Accessorys"; + if (aryShowAccType.Count > 0) + { + strDesc += ", AccessoryType:"; + for (int k = 0, loopTo2 = aryShowAccType.Count - 1; k <= loopTo2; k++) + strDesc = strDesc + aryShowAccType[k] + ",".ToString(); + strDesc = strDesc.TrimEnd(','); + } + if (aryShowAccNo.Count > 0) + { + strDesc += ", AccessoryNo:"; + for (int k = 0, loopTo3 = aryShowAccNo.Count - 1; k <= loopTo3; k++) + strDesc = strDesc + aryShowAccNo[k] + ",".ToString(); + strDesc = strDesc.TrimEnd(','); + } + } + } + else + { + // 設備沒掛模治具就一定沒有掛設定的必需模治具 + // 不可用說明 + blnAllowExecute = false; + strDesc += "There is Product Accessory Setup, Equipment don't use any Accessorys"; + } + } + + // 變更狀態. + drSel[i].BeginEdit(); + if (blnAllowExecute) + { + drSel[i]["AllowExecute"] = 1; // 可用 + // 組合予後面使用,可使用的,才加入. + strEquipmentNo += ",'" + EquipmentNo + "'"; + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drSel[i]["RecipeGroup"], "N/A", false))) + { + strRecipe = strRecipe + ",('" + drSel[i]["RecipeGroup"] + "','" + drSel[i]["RecipeVersion"] + "')".ToString(); + } + } + else + { + drSel[i]["Description"] = strDesc; + + } // 不可用說明 + drSel[i].EndEdit(); + } + + // =================================== + // 子設備 TsungYu 2021/06/08 + if (strParameterChamber == "1" && dsTemp.Tables["AreaEquipment_A"].Rows.Count > 0) + { + var parentColFIAcc = new DataColumn[1]; + var childColChamber = new DataColumn[1]; + parentColFIAcc[0] = dsTemp.Tables["AreaEquipment_A"].Columns["EquipmentNo"]; + childColChamber[0] = dsTemp.Tables["Chamber"].Columns["BelongEquipmentNo"]; + + DataRelation tmpReAcc; + tmpReAcc = new DataRelation("Chamber", parentColFIAcc, childColChamber, false); + dsTemp.Relations.Add(tmpReAcc); + } + // =================================== + + if (!string.IsNullOrEmpty(strEquipmentNo)) + { + // 去除第一個逗號 + strEquipmentNo = Strings.Mid(strEquipmentNo, 2, Strings.Len(strEquipmentNo) - 1); + string[] artEquipmentNo; + artEquipmentNo = strEquipmentNo.Split(','); + + // '=================================== + // '子設備 TsungYu 2021/06/08 + // If strParameterChamber = "1" Then + // Dim parentColFIAcc(0) As DataColumn + // Dim childColChamber(0) As DataColumn + // parentColFIAcc(0) = dsTemp.Tables("AreaEquipment_A").Columns("EquipmentNo") + // childColChamber(0) = dsTemp.Tables("Chamber").Columns("BelongEquipmentNo") + + // Dim tmpReAcc As DataRelation + // tmpReAcc = New DataRelation("Chamber", parentColFIAcc, childColChamber, False) + // dsTemp.Relations.Add(tmpReAcc) + // End If + // '=================================== + + // 取出模治具,GetAccessory是用來決定介面要不要看到EQP掛的模治具的變數 + if (GetAccessory) + { + // Kevin 15/01/26,調整In的寫法 + for (int m = 0, loopTo4 = artEquipmentNo.Length - 1; m <= loopTo4; m++) + { + // 取出AccState + strSQL = "Select A.*,B.AccessoryState,B.AccumulateQty,B.AccSpareQty,C.ScrapLife,C.LifeManage,C.LifeScript,C.LifeTolerance,C.RepairCycle,D.StateName " + " From tblEMSEQPAccState A left join tblEMSAccessoryState B on A.AccessoryNo=B.AccessoryNo " + " And A.AccessoryVersion=B.AccessoryVersion left join tblEQPAccessoryLife C " + " on A.AccessoryType=C.Accessory " + " left join tblEQPAccStateBasis D On B.AccessoryState = D.AccessoryState " + " Where A.EquipmentNo = " + artEquipmentNo[m] + " Order By A.AccessoryType,A.AccessoryNo"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "AccState", cnnTemp); + + } + + // 建立Relation + var parentColFIAcc = new DataColumn[1]; + var childColFIAcc = new DataColumn[1]; + parentColFIAcc[0] = dsTemp.Tables["AreaEquipment_A"].Columns["EquipmentNo"]; + childColFIAcc[0] = dsTemp.Tables["AccState"].Columns["EquipmentNo"]; + // 建立主從關係(RelationName會影響WinForm資料的顯示) + DataRelation tmpReAcc; + tmpReAcc = new DataRelation("Accessory", parentColFIAcc, childColFIAcc, false); + dsTemp.Relations.Add(tmpReAcc); + } + + // 取出物料 + if (GetMaterial) + { + // Kevin 15/01/26,調整In的寫法 + for (int m = 0, loopTo5 = artEquipmentNo.Length - 1; m <= loopTo5; m++) + { + // 取出MaterialState + strSQL = "Select EquipmentNo,MaterialNo,MaterialLotNo,Qty,UnitNo,InputDate From tblEMSEQPMaterialState " + " Where EquipmentNo = " + artEquipmentNo[m]; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "MaterialState", cnnTemp); + + } + + if (dsTemp.Tables["MaterialState"].Rows.Count == 0) + { + dsTemp.Tables.Remove("MaterialState"); + } + else + { + // 建立Relation + var parentColFI = new DataColumn[1]; + var childColFI = new DataColumn[1]; + + parentColFI[0] = dsTemp.Tables["AreaEquipment_A"].Columns["EquipmentNo"]; + childColFI[0] = dsTemp.Tables["MaterialState"].Columns["EquipmentNo"]; + + // 建立主從關係(RelationName會影響WinForm資料的顯示) + DataRelation tmpRe1; + tmpRe1 = new DataRelation("Material", parentColFI, childColFI, false); + dsTemp.Relations.Add(tmpRe1); + } + } + + // 取出Recipe + if (GetRecipe && !string.IsNullOrEmpty(strRecipe)) + { + strRecipe = Strings.Mid(strRecipe, 2); // 去除第一個逗號 + // 取出RecipeDetail(因RecipeVersion要做為Key,故將Number轉為字串) + if (strDataBaseType != "oracle") + { + // strRecipe = Replace(strRecipe, "','", "+") + strRecipe = Strings.Replace(strRecipe, "','", ""); + strSQL = "Select RecipeGroup,STR(RecipeVersion, 1) As RecipeVersion,RecipeNo,RecipeValue From tblEQPRecipeDetail " + " Where (RecipeGroup+Str(RecipeVersion,1)) In (" + strRecipe + ")"; + } + else + { + strSQL = "Select RecipeGroup,Substr(RecipeVersion,1) As RecipeVersion,RecipeNo,RecipeValue From tblEQPRecipeDetail " + " Where (RecipeGroup,RecipeVersion) In (" + strRecipe + ")"; + } + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "RecipeDetail", cnnTemp); + + + if (dsTemp.Tables["RecipeDetail"].Rows.Count == 0) + { + dsTemp.Tables.Remove("RecipeDetail"); + } + else + { + // 建立Relation + var parentColFI = new DataColumn[2]; + var childColFI = new DataColumn[2]; + + parentColFI[0] = dsTemp.Tables["AreaEquipment_A"].Columns["RecipeGroup"]; + childColFI[0] = dsTemp.Tables["RecipeDetail"].Columns["RecipeGroup"]; + parentColFI[1] = dsTemp.Tables["AreaEquipment_A"].Columns["RecipeVersion"]; + childColFI[1] = dsTemp.Tables["RecipeDetail"].Columns["RecipeVersion"]; + + // 建立主從關係(RelationName會影響WinForm資料的顯示) + DataRelation tmpRe1; + tmpRe1 = new DataRelation("Recipe", parentColFI, childColFI, false); + dsTemp.Relations.Add(tmpRe1); + } + } + } + + // 2012/12/26 YF, 檢查產品所設定的設備能力 + var tmp = dsTemp.Tables; + var argdtEquipment = tmp["AreaEquipment_A"]; + using (var objLot = new clsLot()) + { + objLot.funCheckEquipmentCapability(ref cnnTemp, ref argdtEquipment, strReferenceNo, strReferenceVersion, strOPNo); + } + + + // 2012/12/26 YF, 檢查產品所設定的禁用設備 + var tmp1 = dsTemp.Tables; + var argdtEquipment1 = tmp1["AreaEquipment_A"]; + using (var objLot = new clsLot()) + { + objLot.funCheckEquipmentConstraint(ref cnnTemp, ref argdtEquipment1, strReferenceNo, strReferenceVersion, strOPNo); + } + // 現行製程模組不支持設備禁用設定,因此判斷設備禁用的設定應再統一查詢產品資料中的 禁用設備的設定 + if (intOPReference == 1) + { + var tmp2 = dsTemp.Tables; + var argdtEquipment2 = tmp2["AreaEquipment_A"]; + using (var objLot = new clsLot()) + { + objLot.funCheckEquipmentConstraint(ref cnnTemp, ref argdtEquipment2, strProductNo, strProductVersion, strOPNo); + } + } + + if (MultiQCList == true) + { + // 2021/3/18,Ning,QCListNo:列出所有設定為CheckIn的點檢表編號, 若有多筆, 則以逗號串起 + var tmp3 = dsTemp.Tables; + var argdtEquipment3 = tmp3["AreaEquipment_A"]; + using (var objLot = new clsLot()) + { + objLot.funFillEquipmentQCListNo(ref cnnTemp, ref argdtEquipment3); + } + } + + // Return + ShowAvailableEquipment_AllRet = dsTemp; + } + + catch (Exception e1) + { + ShowAvailableEquipment_AllRet = null; + throw; + } + + finally + { + CloseConnection(cnnTemp); + + if (dsTemp != null) + dsTemp.Dispose(); + + } + return ShowAvailableEquipment_AllRet; + + } + + #endregion + + + #region "LotMessage批次信息查询接口" + /// + /// 批次信息查询接口:根据PanelSN查LotNo,再查询批次相关的客户、产品、工艺、当前工序信息 + /// + public static bool funLotMessage(ref List aryMessage, ref List aryException, string PanelSN, string EQPID, + ref string strLOTNO, ref string strPROCESSNO, ref string strOPNO, ref string strPRODUCTNO, ref string strCUSTOMERNO) + { + bool funLotMessage = default(bool); + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + string strLotNo = ""; + + try + { + // ============================ + // 1. 根据PanelSN(作为ProductID)查询LotNo + // ============================ + strSQL = "SELECT LOTNO FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTID = '" + PanelSN + "' AND STATE = '1'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%PanelSN(" + PanelSN + ")未找到对应批次!%]"); + return false; + } + strLotNo = drTemp["LOTNO"].ToString(); + strLOTNO = strLotNo; + drTemp.Close(); + + // ============================ + // 2. 查询批次信息:产品、客户、流程编号、当前工序 + // TBLWIPLOTBASIS: PRODUCTNO, CUSTOMERNO + // TBLWIPLOTSTATE: PROCESSNO (流程编号), OPNO (当前工序) + // ============================ + strSQL = "SELECT A.PRODUCTNO, A.CUSTOMERNO, B.PROCESSNO, B.OPNO " + + "FROM TBLWIPLOTBASIS A " + + "LEFT JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO " + + "WHERE A.BASELOTNO = '" + strLotNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strPRODUCTNO = drTemp["PRODUCTNO"].ToString(); + strCUSTOMERNO = drTemp["CUSTOMERNO"].ToString(); + strPROCESSNO = drTemp["PROCESSNO"].ToString(); + strOPNO = drTemp["OPNO"].ToString(); + } + else + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%批次(" + strLotNo + ")未找到批次基础信息!%]"); + return false; + } + drTemp.Close(); + + funLotMessage = true; + exitfun: + ; + } + catch (Exception ex) + { + string errorMsg = clsERP.GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + drTemp?.Close(); + CloseConnection(cnnTemp); + } + return funLotMessage; + } + #endregion + + + #region "MACBLUE MAC&蓝牙地址生成接口" + /// + /// MAC&蓝牙地址生成:根据UnitId查批次→产品→序号规则,按规则生成MAC和蓝牙地址 + /// + public static string funMACBLUE(string request) + { + string strResult = ""; + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + string strUnitId = ""; + string strLotNo = ""; + string strProductNo = ""; + string strMACRuleNo = ""; + string strBlueToothRuleNo = ""; + string strGeneratedMACID = ""; + string strGeneratedBlueToothID = ""; + + MACBLUEResponse response = new MACBLUEResponse(); + + try + { + var Parameters = JsonConvert.DeserializeObject>(request); + strUnitId = Parameters.ContainsKey("unitid") ? Parameters["unitid"] : ""; + if (string.IsNullOrEmpty(strUnitId)) + throw new Exception("[%unitid不能为空!%]"); + + // 1. 根据unitid查LotNo + string strSQL = "SELECT LOTNO FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTID = '" + strUnitId + "' AND STATE = '1' AND PRODUCTTYPE = '1'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + throw new Exception("[%未找到UnitId(" + strUnitId + ")对应的批次!%]"); + strLotNo = drTemp["LOTNO"].ToString(); + drTemp.Close(); + + // 2. 根据LotNo查ProductNo + strSQL = "SELECT PRODUCTNO FROM TBLWIPLOTBASIS WHERE BASELOTNO = '" + strLotNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + throw new Exception("[%未找到批次(" + strLotNo + ")对应的产品!%]"); + strProductNo = drTemp["PRODUCTNO"].ToString(); + drTemp.Close(); + + // 3. 查产品对应的MAC和蓝牙序号规则编号 + strSQL = "SELECT MACID, BLUETOOTH FROM TBLPRDPRODUCTBASIS WHERE PRODUCTNO = '" + strProductNo + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + throw new Exception("[%未找到产品(" + strProductNo + ")的MAC/蓝牙规则!%]"); + strMACRuleNo = drTemp["MACID"].ToString(); + strBlueToothRuleNo = drTemp["BLUETOOTH"].ToString(); + drTemp.Close(); + + // 4. 生成MAC序号 + if (!string.IsNullOrEmpty(strMACRuleNo)) + strGeneratedMACID = funGenerateSerialWithRange(cnnTemp, strMACRuleNo, strUnitId, "MAC"); + else + strGeneratedMACID = ""; + + // 5. 生成蓝牙序号 + if (!string.IsNullOrEmpty(strBlueToothRuleNo)) + strGeneratedBlueToothID = funGenerateSerialWithRange(cnnTemp, strBlueToothRuleNo, strUnitId, "BLUETOOTH"); + else + strGeneratedBlueToothID = ""; + + // 6. 存表:更新 TBLWIPPRDSTATE_LQ & TBLWIPPRDLOG_LQ + if (!string.IsNullOrEmpty(strGeneratedMACID) || !string.IsNullOrEmpty(strGeneratedBlueToothID)) + { + strSQL = "UPDATE TBLWIPPRDSTATE_LQ SET MACID = '" + strGeneratedMACID + "', BLUETOOTHID = '" + strGeneratedBlueToothID + "' WHERE PRODUCTID = '" + strUnitId + "' AND STATE = '1'"; + ExecuteSQLNoneQuery(strDataBaseType, strConnectionString, ref strSQL); + + strSQL = "INSERT INTO TBLWIPPRDLOG_LQ (LOTNO, PRODUCTID, EQPID, OPNO, CARRIERID, PRODUCTTYPE, CREATEDATE, MACID, BLUETOOTHID) " + + "SELECT LOTNO, PRODUCTID, EQPID, OPNO, CARRIERID, PRODUCTTYPE, CREATEDATE, MACID, BLUETOOTHID " + + "FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTID = '" + strUnitId + "' AND STATE = '1'"; + ExecuteSQLNoneQuery(strDataBaseType, strConnectionString, ref strSQL); + } + + response.code = "0000"; + response.message = "MACBLUE successfully"; + response.time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + response.data = new MACBLUEResponseData { macid = strGeneratedMACID, bluetooth = strGeneratedBlueToothID }; + } + catch (iMESException.MESException ex) + { + response.code = "1111"; + response.message = "MACBLUE :" + ex.Message; + } + catch (Exception ex) + { + response.code = "1111"; + response.message = "MACBLUE :" + ex.Message; + } + finally + { + drTemp?.Close(); + CloseConnection(cnnTemp); + } + strResult = JsonConvert.SerializeObject(response); + return strResult; + } + + /// + /// 根据序号规则编号生成带起始/结束值约束的完整序号(含前缀+流水号) + /// + private static string funGenerateSerialWithRange(IDbConnection cnnTemp, string SerialTypeNo, string UnitId, string SerialType) + { + string strSQL = ""; + DbDataReader drTemp = null; + DataSet dsTemp = new DataSet(); + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + // 检查 UnitId 是否已有对应的值 + string checkField = SerialType == "MAC" ? "MACID" : "BLUETOOTHID"; + string strExistSQL = "SELECT " + checkField + " FROM TBLWIPPRDSTATE_LQ WHERE PRODUCTID = '" + UnitId + "' AND STATE = '1'"; + drTemp = ExecuteSQLQuery_Reader(strExistSQL, cnnTemp); + if (drTemp.Read()) + { + string existVal = drTemp[0] is DBNull ? "" : drTemp[0].ToString(); + drTemp.Close(); + if (!string.IsNullOrEmpty(existVal)) + return existVal; + } + drTemp.Close(); + + // 读取序号规则 Basis(检查启用) + strSQL = "SELECT * FROM TBLSYSSERIALRULEBASIS WHERE SERIALTYPENO = '" + SerialTypeNo + "' AND ENABLE = 1"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "SerialRuleBasis", cnnTemp); + if (dsTemp.Tables["SerialRuleBasis"].Rows.Count == 0) + throw new Exception("[%序号规则(" + SerialTypeNo + ")不存在或未启用!%]"); + + // 读取序号规则所有明细则(含前缀 UD 和流水号 SN) + strSQL = "SELECT * FROM TBLSYSSERIALRULEDETAIL WHERE SERIALTYPENO = '" + SerialTypeNo + "' ORDER BY ITEMNO"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "RuleDetail", cnnTemp); + if (dsTemp.Tables["RuleDetail"].Rows.Count == 0) + throw new Exception("[%序号规则(" + SerialTypeNo + ")未配置明细!%]"); + + int intSerLen = 0; + int intDecimalType = 1; + int intPadLeft = 1; + int intSNIndex = -1; + string strStartNum = ""; + string strEndNum = ""; + + // 添加 Value 列,并处理每个明细项 + dsTemp.Tables["RuleDetail"].Columns.Add("Value"); + for (int i = 0; i < dsTemp.Tables["RuleDetail"].Rows.Count; i++) + { + string sourceType = dsTemp.Tables["RuleDetail"].Rows[i]["SOURCETYPE"].ToString(); + switch (sourceType) + { + case "SN": + intSerLen = Convert.ToInt32(dsTemp.Tables["RuleDetail"].Rows[i]["SERIALLENGTH"]); + intDecimalType = Convert.ToInt32(dsTemp.Tables["RuleDetail"].Rows[i]["DECIMALTYPE"]); + intPadLeft = 1; + if (dsTemp.Tables["RuleDetail"].Columns.Contains("PADLEFT")) + intPadLeft = Convert.ToInt32(dsTemp.Tables["RuleDetail"].Rows[i]["PADLEFT"]); + intSNIndex = i; + + // 读取 STARTNUM / ENDNUM + if (dsTemp.Tables["RuleDetail"].Columns.Contains("STARTNUM") && dsTemp.Tables["RuleDetail"].Rows[i]["STARTNUM"] != DBNull.Value) + strStartNum = dsTemp.Tables["RuleDetail"].Rows[i]["STARTNUM"].ToString(); + if (dsTemp.Tables["RuleDetail"].Columns.Contains("ENDNUM") && dsTemp.Tables["RuleDetail"].Rows[i]["ENDNUM"] != DBNull.Value) + strEndNum = dsTemp.Tables["RuleDetail"].Rows[i]["ENDNUM"].ToString(); + break; + + case "UD": + dsTemp.Tables["RuleDetail"].Rows[i]["Value"] = dsTemp.Tables["RuleDetail"].Rows[i]["USERDEFINE"].ToString(); + break; + + default: + dsTemp.Tables["RuleDetail"].Rows[i]["Value"] = dsTemp.Tables["RuleDetail"].Rows[i]["USERDEFINE"].ToString(); + break; + } + } + + if (intSNIndex < 0) + throw new Exception("[%序号规则(" + SerialTypeNo + ")未配置流水号!%]"); + + // 转换 STARTNUM/ENDNUM 为十进制 + long lngStartNum = 0; + long lngEndNum = long.MaxValue; + if (!string.IsNullOrEmpty(strStartNum)) + lngStartNum = funBaseToDecimal(strStartNum, intDecimalType); + if (!string.IsNullOrEmpty(strEndNum)) + lngEndNum = funBaseToDecimal(strEndNum, intDecimalType); + + // 读取当前最大序号 + strSQL = "SELECT MAXSERIALNO FROM TBLSYSSERIALCREATEMAX WHERE SERIALTYPE = '" + SerialType + "' AND SERIALSTRING = '" + SerialTypeNo + "' AND SERIALLENGTH = " + intSerLen + " AND DECIMALTYPE = " + intDecimalType; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + long lngMaxSerialNo; + bool blnInsert; + if (drTemp.Read()) + { + blnInsert = false; + lngMaxSerialNo = Convert.ToInt64(drTemp["MAXSERIALNO"]); + } + else + { + blnInsert = true; + lngMaxSerialNo = 0; + } + drTemp.Close(); + + // 起始值约束 + if (!string.IsNullOrEmpty(strStartNum) && lngMaxSerialNo < lngStartNum) + lngMaxSerialNo = lngStartNum - 1; + + long lngNewSerialNo = lngMaxSerialNo + 1; + + // 结束值检查 + if (!string.IsNullOrEmpty(strEndNum) && lngNewSerialNo > lngEndNum) + throw new Exception("[%" + SerialType + "序号已达到最大值(" + strEndNum + "),无法继续生成!%]"); + + // 生成流水号字符串 + string strNewSerial = funDecimalToBase(lngNewSerialNo, intDecimalType); + if (intPadLeft == 1) + strNewSerial = strNewSerial.PadLeft(intSerLen, '0'); + + // 长度检查 + if (strNewSerial.Length > intSerLen) + throw new Exception("[%" + SerialType + "序号超出长度限制(" + intSerLen + "): " + strNewSerial + "%]"); + + // 组装完整序号(前缀 + 流水号) + string strFullSerial = ""; + for (int j = 0; j < dsTemp.Tables["RuleDetail"].Rows.Count; j++) + { + if (j == intSNIndex) + strFullSerial += strNewSerial; + else + strFullSerial += dsTemp.Tables["RuleDetail"].Rows[j]["Value"].ToString(); + } + + // 重复检查:在 TBLWIPPRDSTATE_LQ 中查找完整序号 + int retryCount = 0; + int maxRetry = 100; + while (retryCount < maxRetry) + { + strSQL = "SELECT 1 FROM TBLWIPPRDSTATE_LQ WHERE " + checkField + " = '" + strFullSerial + "' AND PRODUCTID <> '" + UnitId + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + drTemp.Close(); + break; + } + drTemp.Close(); + retryCount++; + lngNewSerialNo++; + if (!string.IsNullOrEmpty(strEndNum) && lngNewSerialNo > lngEndNum) + throw new Exception("[%" + SerialType + "序号已达到最大值(" + strEndNum + "),无法继续生成!%]"); + strNewSerial = funDecimalToBase(lngNewSerialNo, intDecimalType); + if (intPadLeft == 1) + strNewSerial = strNewSerial.PadLeft(intSerLen, '0'); + if (strNewSerial.Length > intSerLen) + throw new Exception("[%" + SerialType + "序号超出长度限制(" + intSerLen + "): " + strNewSerial + "%]"); + // 重新组装完整序号 + strFullSerial = ""; + for (int j = 0; j < dsTemp.Tables["RuleDetail"].Rows.Count; j++) + { + if (j == intSNIndex) + strFullSerial += strNewSerial; + else + strFullSerial += dsTemp.Tables["RuleDetail"].Rows[j]["Value"].ToString(); + } + } + if (retryCount >= maxRetry) + throw new Exception("[%生成" + SerialType + "序号失败:重试次数过多!%]"); + + // 更新 TBLSYSSERIALCREATEMAX + if (blnInsert) + { + strSQL = "INSERT INTO TBLSYSSERIALCREATEMAX (SERIALTYPE, SERIALSTRING, SERIALLENGTH, DECIMALTYPE, MAXSERIALNO) " + + "VALUES ('" + SerialType + "', '" + SerialTypeNo + "', " + intSerLen + ", " + intDecimalType + ", " + lngNewSerialNo + ")"; + } + else + { + strSQL = "UPDATE TBLSYSSERIALCREATEMAX SET MAXSERIALNO = " + lngNewSerialNo + + " WHERE SERIALTYPE = '" + SerialType + "' AND SERIALSTRING = '" + SerialTypeNo + "'" + + " AND SERIALLENGTH = " + intSerLen + " AND DECIMALTYPE = " + intDecimalType + + " AND MAXSERIALNO = " + lngMaxSerialNo; + } + ExecuteSQLNoneQuery(strDataBaseType, strConnectionString, ref strSQL); + + return strFullSerial; + } + + /// + /// 将指定进制字符串转10进制 + /// + private static long funBaseToDecimal(string strValue, int decimalType) + { + strValue = strValue.Trim().ToUpper(); + long result = 0; + int baseVal = decimalType == 1 ? 10 : decimalType == 2 ? 16 : decimalType == 4 ? 34 : 36; + + foreach (char c in strValue) + { + int digit; + if (c >= '0' && c <= '9') + digit = c - '0'; + else + { + digit = c - 'A' + 10; + if (decimalType == 4) + { + if (c >= 'J') digit--; + if (c >= 'P') digit--; + } + } + result = result * baseVal + digit; + } + return result; + } + + /// + /// 将10进制转指定进制字符串 + /// + private static string funDecimalToBase(long value, int decimalType) + { + if (value == 0) return "0"; + string chars; + int baseVal; + if (decimalType == 1) { baseVal = 10; chars = "0123456789"; } + else if (decimalType == 2) { baseVal = 16; chars = "0123456789ABCDEF"; } + else if (decimalType == 4) { baseVal = 34; chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; } + else { baseVal = 36; chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } + + string result = ""; + while (value > 0) + { + result = chars[(int)(value % baseVal)] + result; + value /= baseVal; + } + return result; + } + #endregion + + + #region "自动进出站,搬迁标准进出站" + + // 0102096: [6.0.5] EAP自動報工架構_SDD210906_05-01/ Execute_CI_LOT + public static object AutoexecutionLot_Lot(ref bool blnEXETriggerOP, Dictionary dicPars, Dictionary dicPars_DataTable, string FunctionID, DateTime ArriveTime, string UserNo, string ComputerName, bool blnRuleCheck = true) + { + object AutoexecutionLot_LotRet = default(object); + var dtLotState = new DataTable(); // Load Afer TriggerOP + var objLot = new kcWIP.clsLot(); + var objSYS = new clsSYSUserLog(); + var objWIP = new kcWIP.clsWIP(); + var objUSR = new iMESUserManager.clsUSRSecurity(); + //var objclsWIP = new clsWIP(); + var objEMS = new kcEMS.clsEMSEquipment(); + var objReverse = new udReverse.clsReverse(); + DataRow drAdd; + IDbConnection cnnTemp = null; + var drTemp = default(DbDataReader); + //OleDbCommand cmmTemp; + AppSettings objSetting = new AppSettings(); + + string strException; + string strResult; + int PhaseNo; + string AreaNo = defString; + string OPNo = defString; + string PSNo = defString; + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); // Create connection + + string strServiceName = "ExecuteLot"; + + + var dtLotNo = new DataTable(); + dtLotNo.Columns.Add("LotNo", System.Type.GetType("System.String")); + var drLotAdd = dtLotNo.NewRow(); + drLotAdd["LotNo"] = dicPars["lotno"]; + dtLotNo.Rows.Add(drLotAdd); + string LotNo = dtLotNo.Rows[0]["LotNo"].ToString(); + + string InXML = ""; + string OutXML = ""; + + string strRetrunMsg = ""; + + var dtChkRuleLot2 = new DataTable("ChkRuleLot"); // minya 20200315 + string strEquipmentNo = defString; + string strERFMsg = ""; + try + { + + // 1.依InXml資料與Lot目前狀態比對是否符合 + DataRow drLotState = null; + var strKernelModule = default(string); + var strKernelFunctionName = default(string); + + // 檢查USER過帐权限 + DataRow drUser; + if (!string.IsNullOrEmpty(UserNo)) + { + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + UserNo = "EAP_AGENT"; + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + throw new iMESException.MESException("0000-200015", "[%Please provide curuser or set EAP_Agent correct, then execute Lot%] !"); + } + } + } + else + { + UserNo = "EAP_AGENT"; + drUser = objUSR.GetUserSecurity(UserNo, 2); + if (string.IsNullOrEmpty(drUser["UserNo"].ToString())) + { + throw new iMESException.MESException("0000-200015", "[%Please provide curuser or set EAP_Agent correct, then execute Lot%] !"); + } + } + + if (!dicPars.ContainsKey("equipmentno")) + { + throw new iMESException.MESException("0000-200002", "[%EquipmentNo%] [%NOT FOUND%]"); + } + else + { + strEquipmentNo = dicPars["equipmentno"]; + } + + // 2.取得生產批現況資訊 + string refBRNO = defString; + string refBRExecutionFile = defString; + + string strLots = "("; + foreach (DataRow drTempLotNo in dtLotNo.Rows) + strLots += "'" + drTempLotNo["LotNo"].ToString() + "',"; + strLots = strLots.TrimEnd(','); + strLots += ")"; + + if (funLoadLotStatusJoinOPBusinessRule(strLots, ref dtLotNo) < 0) + { + throw new iMESException.MESException("0000-200091", "[%funLoadLotStatusJoinOPBusinessRule fail%]!"); + } + if (!(dtLotNo == null) && dtLotNo.Rows.Count > 0) // 取出區域與作業站 + { + OPNo = dtLotNo.Rows[0]["OPNo"].ToString(); + AreaNo = dtLotNo.Rows[0]["AreaNo"].ToString(); + PSNo = dtLotNo.Rows[0]["PSNo"].ToString(); + } + + // 檢查User是否有此OP的權限------------------------------------------------------------------------------------------------ + // Gary Lu 20121114:這個作業站不在群組內才要進行權限檢查 + if (objUSR.ChkUserOPPriv(UserNo, OPNo) == false) + { + throw new iMESException.MESException("0000-202015", "[%UserNo%]:" + UserNo + "[%NOTHINGSTATE%][%OPPRIVILEGE%], [%OPNo%]:" + OPNo); + } + + // 檢查User是否有產品區段設定權限------------------------------------------------------------------------------------------------ + if (objUSR.ChkUserPSPriv(UserNo, PSNo) == false) + { + throw new iMESException.MESException("0000-200062", "[%EmployeeNo%]:" + UserNo + "[%has no PS Privilege%], [%PSNo%]:" + PSNo); + } + + objUSR = null; + + // 6.取得班別 + string ShiftNo = "N/A"; + using (var obj = new clsUSRDepartment()) + { + ShiftNo = obj.GetShift(UserNo); + } + + + // 0 : Sucess + // -1 : Program Error + // -2 : LotInfo Error + // -3 : Each Lot Has Different BR + // -4 : RefLotNo Didn't Setting KERNELMODULE(tblOPBusinessRuleBasis) + // -5 : RefLotNo Didn't Setting KERNELFUNCTIONNAME(tblOPBusinessRuleBasis) + // -6 : LotStatus Error + switch (ChkLotStateAndBRNo(strLots, FunctionID, OPNo)) + { + case -1: + { + throw new iMESException.MESException("0000-200091", "[%ChkLotStateAndBRNo fail%]!"); + } + case -2: + { + throw new iMESException.MESException("0000-200091", "[%LotNo And OPNo fail!%]"); + } + case -3: + { + throw new iMESException.MESException("0000-200091", "[%Each Lot Has Different BR%]"); + } + case -4: + { + throw new iMESException.MESException("0000-200091", "[%RefLotNo%] " + LotNo + "; [%Not Setting KERNELMODULE(tblOPBusinessRuleBasis)%]"); + } + case -5: + { + throw new iMESException.MESException("0000-200091", "[%RefLotNo%] " + LotNo + "; [%Not Setting KERNELFUNCTIONNAME(tblOPBusinessRuleBasis)%]"); + } + case -6: + { + throw new iMESException.MESException("0000-200091", "[%LotStatus Error%]"); + } + } + + foreach (DataRow drTempLotNo in dtLotNo.Rows) + { + if (dtLotNo.Rows.IndexOf(drTempLotNo) == 0) + { + refBRNO = drTempLotNo["BRNO"].ToString(); + refBRExecutionFile = drTempLotNo["EXECUTIONFILE"].ToString(); + } + else if (drTempLotNo["BRNO"].ToString() != refBRNO) + { + // LotBR 與首批不一致 + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + drTempLotNo["LotNo"].ToString() + " [%BR%] [%Is Not THE SAME%]"); + } + + funCheckStateByLot(ref strKernelModule, ref strKernelFunctionName, drTempLotNo["LotNo"].ToString(), drTempLotNo, FunctionID, OPNo); + } + + if (FunctionID == "CO") + { + if (refBRExecutionFile.ToUpper() != "BR_L_CO_GEN_M.DLL" && refBRExecutionFile.ToUpper() != "BR_L_CO_GEN.DLL") + { + //0156845: [6.0.7]调整EAP接口查核支援BR逻辑,增加查核brno + if (!ExeBrnoIfSupport(refBRExecutionFile.ToUpper(), refBRNO)) + { + throw new iMESException.MESException("0000-200091", "[%Only Support L_CO_GEN Now%] [%NOWUSE%]:" + refBRNO + ""); + } + + } + } + else if (refBRExecutionFile.ToUpper() != "BR_L_CI_GEN.DLL") + { + //0156845: [6.0.7]调整EAP接口查核支援BR逻辑,增加查核brno + if (!ExeBrnoIfSupport(refBRExecutionFile.ToUpper(), refBRNO)) + { + throw new iMESException.MESException("0000-200091", "[%Only Support L_CI_GEN Now%] [%NOWUSE%]:" + refBRNO + ""); + } + } + + // 3.Execution Trigger OP + if (!dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + using (var dcTemp = new DataColumn()) + { + dcTemp.ColumnName = "blnEXETriggerOP"; + dcTemp.DataType = Type.GetType("System.Boolean"); + dcTemp.DefaultValue = false; + dtLotNo.Columns.Add(dcTemp); + } + } + + foreach (DataRow drTempLot in dtLotNo.Rows) + { + // If drTempLot("Status") = 0 Then + string DescriptionTmp = defString; + long NewLotStampTmp = defInteger; + switch (objLot.TriggerOP(ref DescriptionTmp, ref NewLotStampTmp, Convert.ToString(drTempLot["LotNo"]), UserNo: UserNo)) + { + + case "hold_exceedtime": + { + tcEAI.clsWIP.BRERFCreateExecute(pUserId: UserNo, pLotNo: Convert.ToString(drTempLot["LotNo"]), pERFType: 1, pHoldTime: 0, pRuleNo: "EXCEEDTIME"); + throw new iMESException.MESException("0000-200091", "LotNO:" + + drTempLot["LotNo"] + "[%VIOLATE TIME CONTROL,CREATE ERF%]!"); + } + case "futurehold": + { + tcEAI.clsWIP.BRERFCreateExecute(pUserId: UserNo, pLotNo: Convert.ToString(drTempLot["LotNo"]), pERFType: 3, pHoldTime: 0); + throw new iMESException.MESException("0000-200091", "LotNO:" + + drTempLot["LotNo"] + "[%FUTUREHOLD SET,CREATE ERF%]!"); + } + case "futurewait": + { + throw new iMESException.MESException("0000-200091", "LotNO:" + drTempLot["LotNo"] + "[%FUTUREWAIT%]!"); + } + case "futureos": + { + throw new iMESException.MESException("0000-200091", "LotNO:" + drTempLot["LotNo"] + "[%FUTURE OS%]!"); + } + + default: + { + // 2020/03/11 Shih Kai, 68676 :自动进出站BR检核-TriggerOP後增加補做TriggerPhase + // Trigger Phase + drLotState = objLot.GetLotBasisJoinState(LotNo: drTempLot["LotNo"].ToString()); // 取得最新的LotState + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 0, false))) // by Product + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ProductNo"].ToString(), drLotState["ProductVersion"].ToString(), drLotState["OPNo"].ToString(), drLotState["BRNo"].ToString()); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 1, false))) // by Module + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ModuleNo"].ToString(), drLotState["ModuleVersion"].ToString(), drLotState["OPNo"].ToString(), drLotState["BRNo"].ToString()); + } + else + { + throw new iMESException.MESException("0000-200015", "LotNo:" + + drTempLot["LotNo"] + ",[%OPREFERENCE ERROR%]!"); + } + + // 剛做完TriggerOP,不用再執行Attrib的變更 + objLot.TriggerPhase_LotState(Convert.ToString(drTempLot["LotNo"]), PhaseNo, UserNo); + + drTempLot["blnEXETriggerOP"] = true; + break; + } + } + } + + + var drLotRow = objLot.GetLotBasisJoinState(LotNo: LotNo); // 取得最新的LotState + + string strLotStamp = drLotRow["LotStamp"].ToString(); + string strLotSerial = drLotRow["LotSerial"].ToString(); + string strLogGroupSerial = drLotRow["LogGroupSerial"].ToString(); + int intPhaseNo = Conversions.ToInteger(drLotRow["PhaseNo"]); + + blnEXETriggerOP = true; + + // 4.ReLoad Lotstate Afer Trigger OP In dtLotState + funLoadLotStatusJoinOPBusinessRule(strLots, ref dtLotState); + + + // 20200309 Edison Mantis : 68289: [SEMI WAFER]通用性CI/CO BR檢核 + // 區域設備檢核 Key in Lot Attrib檢核 Component Attrib檢核, Check Control Rule + // =============================================== 68289 Start =============================================== + + // 5.Xml轉Table + + DataTable dtLotList = new DataTable(), dtLotAttrib = new DataTable(), dtLotError = new DataTable(), dtLotComponent = new DataTable(), dtLotCompAttrib = new DataTable(), dtEquipment = new DataTable(), dtTempAttrib = new DataTable(), dtComponentError = new DataTable(); + DataTable dtAccessory = null; + + // 將批號加入資料表以便檢查設備 + dtLotList.Columns.Add("LotNo"); + DataRow drLotNo; + drLotNo = dtLotList.NewRow(); + drLotNo["LotNo"] = LotNo; + dtLotList.Rows.Add(drLotNo); + + if (dicPars_DataTable.Keys.Contains("lotattrib")) + { + dtLotAttrib = dicPars_DataTable["lotattrib"]; + } + if (dicPars_DataTable.Keys.Contains("loterror")) + { + dtLotError = dicPars_DataTable["loterror"]; + } + if (dicPars_DataTable.Keys.Contains("lotcompoment")) + { + dtLotComponent = dicPars_DataTable["lotcompoment"]; + } + if (dicPars_DataTable.Keys.Contains("lotcomponentattrib")) + { + dtLotCompAttrib = dicPars_DataTable["lotcomponentattrib"]; + } + if (dicPars_DataTable.Keys.Contains("equipment")) + { + dtEquipment = dicPars_DataTable["equipment"]; + } + else + { + dtEquipment.Columns.Add("EquipmentNo"); + DataRow drEQP; + drEQP = dtEquipment.NewRow(); + drEQP["EquipmentNo"] = strEquipmentNo; + dtEquipment.Rows.Add(drEQP); + } + if (dicPars_DataTable.Keys.Contains("tempattrib")) + { + dtTempAttrib = dicPars_DataTable["tempattrib"]; + } + if (dicPars_DataTable.Keys.Contains("componenterror")) + { + dtComponentError = dicPars_DataTable["componenterror"]; + } + if (dicPars_DataTable.Keys.Contains("accessorylist")) + { + dtAccessory = dicPars_DataTable["accessorylist"]; + } + + if (dtAccessory == null) + { + dtAccessory = objEMS.LoadEQPACCStateJoinAccState_EAP(EquipmentNo: strEquipmentNo); + } + + string strCANodeName, strComponentNodeName; + string strLinkName = "PASS"; + string strMailGroupNo = ""; + string strMsg = ""; + string strRuleNo = defString; + int intERFType = 0; + DataTable dtLotRuleData = default(DataTable); + //DataTable dtLotRuleData = default(DataTable), dtCompRuleData = default(DataTable); + + var dtLotAttrib_Temp = new DataTable(); + //dtLotAttrib_Temp.Columns.Add("LotNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("AttribNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("AttribType", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribSequence", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribSource", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribPhase", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("AttribValue", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("SaveToLotPropertyNo", Type.GetType("System.String")); + // 2021/12/1 缺少QCItemNo,於標準BRcheckin會出錯 + dtLotAttrib_Temp.Columns.Add("TestValue", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("Result", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("Result_INT", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("FactorSerial", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("SerialNo", Type.GetType("System.Int32")); + dtLotAttrib_Temp.Columns.Add("MEMO", Type.GetType("System.String")); + dtLotAttrib_Temp.Columns.Add("ComponentNo", Type.GetType("System.String")); + // SPC + dtLotAttrib_Temp.Columns["TestValue"].Expression = "AttribValue"; + + var dtLotCompAttrib_Temp = new DataTable(); + dtLotCompAttrib_Temp.Columns.Add("LotNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("ComponentNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribNo", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribValue", Type.GetType("System.String")); + dtLotCompAttrib_Temp.Columns.Add("AttribType", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribSequence", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribSource", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("AttribPhase", Type.GetType("System.Int32")); + dtLotCompAttrib_Temp.Columns.Add("SaveToLotPropertyNo", Type.GetType("System.String")); + + if (blnRuleCheck) + { + + // 預設 + strCANodeName = "componentattrib"; + strComponentNodeName = "component"; + // Call XmlToTable(InXML, dtEquipment, dtLotList, dtLotAttrib, dtLotError, dtLotComponent, dtLotCompAttrib, strLots, LotNo, strCANodeName, strComponentNodeName, refBRNO) 'refBRNO minya 20200312 + + // dtLotAttrib若不包含欄位:LotNo,會出錯誤 + if (!(dtLotAttrib == null)) + { + if (!dtLotAttrib.Columns.Contains("LotNo")) + { + dtLotAttrib.Columns.Add("LotNo"); + if (!(dtLotNo == null) && dtLotNo.Rows.Count > 0) + { + foreach (DataRow dr in dtLotAttrib.Rows) + dr["LotNo"] = dtLotNo.Rows[0]["LotNo"].ToString(); + } + } + } + // 6. 基本檢查 + funBasisCheck(CIorCO: FunctionID, dtLotNo: dtLotNo, dtEquipment: dtEquipment, dtLotList: dtLotList, dtLotAttrib: dtLotAttrib, dtLotError: dtLotError, dtLotComponent: dtLotComponent, dtLotCompAttrib: dtLotCompAttrib, dtTempAttrib: ref dtTempAttrib, strLots: strLots); + + // 7.格式化Rule Check 資料 並進行ChkControlRule---------------------------------------------------------------------------------------------- + string strBatchComponent = ""; + string strAttrib = ""; + string strCAttrib = ""; + string strError = ""; + string strTemp = ""; + + // 7.1 需要判 Rule 的生產批 + var dtChkRuleLot = new DataTable("ChkRuleLot"); + string strRuleLot = ""; + dtChkRuleLot.Columns.Add("LotNo", Type.GetType("System.String")); + + foreach (DataRow rL in dtLotNo.Rows) + { + strRuleLot += CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rL["LotNo"].ToString()))); + dtChkRuleLot.Rows.Add(rL["LotNo"].ToString()); + } + + // 7.2 格式化資料Component + foreach (DataRow rC in dtLotComponent.Rows) + { + strBatchComponent += CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rC["LotNo"].ToString())) + + CombineXMLValue("componentno", CInput(rC["ComponentNo"].ToString()))); + } + + // 7.3 格式化-Key In Attrib + // KeyIn Attrib + //20240102,13871,0155146: [6.0.7]EAP接口Execute_CO_LOT,出站输入特性参数时,EAP和产品作业站输入一致,但是会提示报错 + DataTable attribtemp = null; + using (var obj = new kcWIP.clsLot()) + { + attribtemp = obj.ShowTemp_Attrib(LotNo).Tables[0]; + } + + + if (!(attribtemp == null)) + { + attribtemp.DefaultView.RowFilter = "(AttribPhase = " + intPhaseNo + " or AttribPhase = 99) And AttribSource <> 0"; // CurPhase & All的所有Attrib,除了KeyIn + for (int i = 0; i <= attribtemp.DefaultView.Count - 1; i++) + { + strTemp = CombineXMLValue("lotno", LotNo) + + CombineXMLValue("attribno", CInput(attribtemp.DefaultView[i]["AttribNo"].ToString())) + + CombineXMLValue("attribtype", attribtemp.DefaultView[i]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", attribtemp.DefaultView[i]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", attribtemp.DefaultView[i]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", attribtemp.DefaultView[i]["AttribPhase"].ToString()) + + CombineXMLValue("savetolotpropertyno", CInput(attribtemp.DefaultView[i]["SaveToLotPropertyNo"].ToString())); + if (attribtemp.DefaultView[i]["AttribValue"] is DBNull) + strTemp += CombineXMLValue("attribvalue", ""); + else + strTemp += CombineXMLValue("attribvalue", CInput(attribtemp.DefaultView[i]["AttribValue"].ToString())); + strAttrib += CombineXMLValueTag(strTemp); + } + //還原顯示 + attribtemp.DefaultView.RowFilter = "AttribSource <> 0 And AttribSource <> 1 And (AttribPhase = " + intPhaseNo + " or AttribPhase = 99)"; // Source = Not KeyIn, Not Calculate ,CurPhase and All + + //Temp:Attrib_KeyIn + for (int i = 0; i <= dtLotAttrib.Rows.Count - 1; i++) + { + if (dtLotAttrib.Rows[i]["AttribValue"] is DBNull) + dtLotAttrib.Rows[i]["AttribValue"] = ""; + + DataRow[] drChk = attribtemp.Select("AttribNo='" + dtLotAttrib.Rows[i]["AttribNo"] + "'"); + if (drChk.Length == 0) + { + throw new iMESException.MESException("0000-203010", "[%AttribNo%]:" + dtLotAttrib.Rows[i]["AttribNo"].ToString()); + } + else + { + strTemp = CombineXMLValue("lotno", LotNo) + + CombineXMLValue("attribno", CInput(dtLotAttrib.Rows[i]["AttribNo"].ToString())) + + CombineXMLValue("attribtype", drChk[0]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", drChk[0]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", drChk[0]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", drChk[0]["AttribPhase"].ToString()) + + CombineXMLValue("attribvalue", CInput(dtLotAttrib.Rows[i]["AttribValue"].ToString())) + + CombineXMLValue("savetolotpropertyno", CInput(drChk[0]["SaveToLotPropertyNo"].ToString())); + if (drChk[0]["QCItemNo"] is DBNull) + strTemp += CombineXMLValue("qcitemno", ""); + else + strTemp += CombineXMLValue("qcitemno", CInput(drChk[0]["QCItemNo"].ToString())); + strAttrib += CombineXMLValueTag(strTemp); + } + } + } + + // 7.4.格式化 Component Attrib + foreach (DataRow rCA in dtLotCompAttrib.Rows) + { + DataSet dsTemp; + using (var obj = new kcWIP.clsLot()) + { + dsTemp = obj.ShowTemp_ComponentAttrib(LotNo); + } + + for (int x = 0, loopTo1 = dsTemp.Tables[0].Rows.Count - 1; x <= loopTo1; x++) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(rCA["AttribNo"], dsTemp.Tables[0].Rows[x]["AttribNo"], false))) + { + strCAttrib = strCAttrib + CombineXMLValueTag( + CombineXMLValue("lotno", LotNo) + + CombineXMLValue("componentno", CInput(dsTemp.Tables[0].Rows[x]["ComponentNo"].ToString())) + + CombineXMLValue("attribno", CInput(rCA["AttribNo"].ToString())) + + CombineXMLValue("attribtype", dsTemp.Tables[0].Rows[x]["AttribType"].ToString()) + + CombineXMLValue("attribsequence", dsTemp.Tables[0].Rows[x]["AttribSequence"].ToString()) + + CombineXMLValue("attribsource", dsTemp.Tables[0].Rows[x]["AttribSource"].ToString()) + + CombineXMLValue("attribphase", dsTemp.Tables[0].Rows[x]["AttribPhase"].ToString()) + + CombineXMLValue("attribvalue", CInput(rCA["AttribValue"].ToString())) + + CombineXMLValue("savetolotpropertyno", CInput(dsTemp.Tables[0].Rows[x]["SaveToLotPropertyNo"].ToString()))); + + DataRow drTemp_Rows; + drTemp_Rows = dtLotCompAttrib_Temp.NewRow(); + drTemp_Rows["LotNo"] = LotNo; + drTemp_Rows["ComponentNo"] = dsTemp.Tables[0].Rows[x]["ComponentNo"]; + drTemp_Rows["AttribNo"] = rCA["AttribNo"]; + drTemp_Rows["AttribType"] = dsTemp.Tables[0].Rows[x]["AttribType"]; + drTemp_Rows["AttribSequence"] = dsTemp.Tables[0].Rows[x]["AttribSequence"]; + drTemp_Rows["AttribSource"] = dsTemp.Tables[0].Rows[x]["AttribSource"]; + drTemp_Rows["AttribPhase"] = dsTemp.Tables[0].Rows[x]["AttribPhase"]; + drTemp_Rows["AttribValue"] = rCA["AttribValue"].ToString(); + drTemp_Rows["SaveToLotPropertyNo"] = dsTemp.Tables[0].Rows[x]["SaveToLotPropertyNo"]; + dtLotCompAttrib_Temp.Rows.Add(drTemp_Rows); + } + } + } + + // 7.5 格式化不良原因 + foreach (DataRow rE in dtLotError.Rows) + { + strError = strError + CombineXMLValueTag( + CombineXMLValue("lotno", CInput(rE["LotNo"].ToString())) + + CombineXMLValue("componentno", CInput(rE["ComponentNo"].ToString())) + + CombineXMLValue("errorno", CInput(rE["ErrorNo"].ToString())) + + CombineXMLValue("errorqty", rE["ErrorQty"].ToString()) + + CombineXMLValue("errorlevel", rE["ErrorLevel"].ToString())); + } + + // 7.6 Control Rule Check------------------------------------------------------------------------------------------------------------- + DataSet dsTestValue = null; + + //if (ChkControlRule_BatchComponent(dtChkRuleLot, true, UserNo, strRuleLot, strBatchComponent, ref strAttrib, ref strCAttrib, ref strLinkName, ref strMsg, ref strRuleNo, ref intERFType, ref dtLotRuleData, ref dtCompRuleData, ref strMailGroupNo, ref dsTestValue, strError) < 0) + if (tcEAI.clsEAP.ChkControlRule(ref dsTestValue, ref dtChkRuleLot, LotNo, UserNo, Conversions.ToLong(strLotStamp), ref strAttrib, ref strLinkName, ref strMsg, ref strRuleNo, ref intERFType, ref strMailGroupNo, strError) < 0) + + { + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + LotNo + ",Check Control Rule [%FUNCTION%][%Fail%]."); + } + + // Check SPC Contorl + if (funChkSPCControl_Var(UserNo, LotNo, ref strAttrib, dsTestValue, ref strLinkName, ref intERFType, ref strERFMsg, dtEquipment) < 0) + { + throw new iMESException.MESException("0000-200091", "[%LotNo%]:" + LotNo + ",Check SPC Contorl [%FUNCTION%][%Fail%]."); + } + strERFMsg = tcEAI.clsEAP.TranslateMsg(strERFMsg); + + //strAttrib to dtLotAttrib_Temp + dtLotAttrib_Temp = ConvertXmlToDataTable(dtLotAttrib_Temp, strAttrib); + + // 取得RuleNo + DataRow[] drSelHoldRule; + if (!(dtLotRuleData == null) && dtLotRuleData.Rows.Count > 0) + { + if (strLinkName == "HOLD") + { + drSelHoldRule = dtLotRuleData.Select("Linkname= 'HOLD'"); + if (drSelHoldRule.Length > 0) + { + strRuleNo = drSelHoldRule[0]["RuleNo"].ToString(); + } + } + } + + // 2020/03/12 Lena, 將 InXml 中的 LiknName、Lot Attrib、Component Attrib 置換為 Control Rule Check 後的結果 + string strLinkNameTagName = "linkname".ToLower(); + string strLAttribTagName = "attrib".ToLower(); + string strCAttribTagName = strCANodeName.ToLower(); + + int intStartIndex, intEndIndex; + string strHand, strLast, strChang; + string strInXml = InXML; + DataRow[] drSel; + + // LinkName + if (!string.IsNullOrEmpty(strLinkName)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strLinkNameTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLinkNameTagName.Length + 3); + string argname = "LinkName"; + string argtype = "String"; + string argdesc = ""; + strChang = CombineXMLParameter(strLinkNameTagName, argname, argtype, strLinkName, argdesc); + strInXml = strHand + strChang + strLast; + } + } + + // Lot Attrib + if (!string.IsNullOrEmpty(strAttrib)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strLAttribTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLAttribTagName.Length + 3); // strLAttribTagName.Length + 3 = 的長度 + string argtype1 = "String"; + string argdesc1 = ""; + strChang = CombineXMLParameterMultiValue(strLAttribTagName, strLAttribTagName, argtype1, strAttrib, argdesc1); + strInXml = strHand + strChang + strLast; + } + } + + // Component Attrib + if (!string.IsNullOrEmpty(strCAttrib)) + { + intStartIndex = Strings.InStr(strInXml, "<" + strCAttribTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strCAttribTagName.Length + 3); // strCAttribTagName.Length + 3 = 的長度 + string argtype2 = "String"; + string argdesc2 = ""; + strChang = CombineXMLParameterMultiValue(strCAttribTagName, strCAttribTagName, argtype2, strCAttrib, argdesc2); + strInXml = strHand + strChang + strLast; + } + } + + InXML = strInXml; + + dtChkRuleLot2 = dtChkRuleLot.Copy(); + + + } + + // 將LotStamp替換為TriggerOP後的LotStamp + if (blnEXETriggerOP) + { + string strLotStampTagName = "lotstamp".ToLower(); + + int intStartIndex, intEndIndex; + string strHand, strLast, strChang; + string strInXml = InXML; + DataRow[] drSel; + + // 取得LotStamp + intStartIndex = Strings.InStr(strInXml, "<" + strLotStampTagName + ">"); + intEndIndex = Strings.InStr(strInXml, ""); + if (intStartIndex > 0 && intEndIndex > 0) + { + strHand = strInXml.Substring(0, intStartIndex - 1); + strLast = Strings.Mid(strInXml, intEndIndex + strLotStampTagName.Length + 3); + string argname1 = "LotStamp"; + string argtype3 = "Long"; + string argvalue = Conversions.ToInteger(dtLotState.Rows[0]["LotStamp"]).ToString(); + string argdesc3 = ""; + strChang = CombineXMLParameter(strLotStampTagName, argname1, argtype3, argvalue, argdesc3); + strInXml = strHand + strChang + strLast; + InXML = strInXml; + } + } + + string strcheckinresult = ""; // BR_CheckIn回傳success or fail + using (var obj = new kcWIP.clsLot()) + { + if (FunctionID == "CO") + { + // 5.取出GoodQty,GoodUnitNo--------------------------------------------------------------------------------------------------- + DataRow[] drSel; + double GoodQty = 0d; + + drSel = dtLotAttrib_Temp.Select("AttribNo='GoodQty'"); + if (drSel.Length == 0) + { + throw new iMESException.MESException("0000-200001", "[%CheckOut%] [%GoodQty%] [%not found%]"); + } + else + { + GoodQty = Convert.ToDouble(drSel[0]["AttribValue"]); + } + // 進站之前已扣料過。 + strcheckinresult = obj.BR_CheckOut(Conversions.ToLong(strLotStamp), LotNo, strLinkName, dtLotAttrib_Temp, dtEquipment, null, null, (decimal)GoodQty, UserNo); + + strRetrunMsg = strcheckinresult; + // 9.Return Value + if (!string.IsNullOrEmpty(strRetrunMsg)) + { + strResult = "fail"; + throw new iMESException.MESException("0000-200011", "[%LotNo%] : " + LotNo + "[%Execute%] [%Fail%]."); + } + else + { + strException = ""; + strResult = "success"; + } + } + + else + { + strcheckinresult = obj.BR_CheckIn(Conversions.ToLong(strLotStamp), LotNo, strLinkName, dtLotAttrib_Temp, dtEquipment, UserNo, ShiftNo, dtAccessory: dtAccessory); + strRetrunMsg = strcheckinresult; + + // 9.Return Value + if (strRetrunMsg == "success") + { + strException = ""; + strResult = "success"; + } + else + { + strResult = "fail"; + throw new iMESException.MESException("0000-200011", "[%LotNo%] : " + LotNo + "[%Execute%] [%Fail%]."); + } + } + } + + + + objSYS.AddEventLog(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, "ExecuteLot", ComputerName: ComputerName); + + if (FunctionID == "CO") + { + //开始生产批转移,生产批转移需要走隐藏站规则,因为有客制,所以调用MEStc的功能,防止后续改动导致EAP出错 + BRTransferLot_Bin_M(LotNo, UserNo, strLinkName, intERFType, strRuleNo, ComputerName: ComputerName, RuleMsg: strERFMsg); + } + else + { + // Call BRTransferLot(LotNo, UserNo, strLinkName, 1) + tcEAI.clsEAP.BRTransferLot_Bin(LotNo, UserNo, strLinkName, intERFType, strRuleNo, ComputerName: ComputerName, RuleMsg: strERFMsg); + + } + + + lblExitProcedure: + ; + } + + + catch (iMESException.MESException ex) + { + + if (FunctionID == "CI") + { + if (dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + // CheckIn失敗將狀態變更回Queue + foreach (DataRow drTempLotInfo in dtLotNo.Rows) + { + if (Convert.ToBoolean(drTempLotInfo["blnEXETriggerOP"])) + { + DataRow[] drSel = dtLotState.Select("LotNO='" + drTempLotInfo["LotNo"] + "'".ToString()); + // Call objReverse.ExecuteReverse(drSel(0)("LotNo"), "AutoExe", Now, , , , , drSel(0)("LotStamp")) + // Call objLot.ExeReverseTriggerOP(drSel(0)("LotNo"), drSel(0)("LotSerial"), drSel(0)("LogGroupSerial"), drSel(0)("LotStamp")) + ExeReverseTriggerOP_NotUseUndo(UserNo, Convert.ToString(drSel[0]["LotNo"]), Convert.ToString(drSel[0]["LotSerial"]), Conversions.ToInteger(drSel[0]["LotStamp"]), ComputerName); + } + } + } + } + + strResult = "fail"; + strRetrunMsg = ex.Message; + + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, ex.Message + " : " + ex.StackTrace, ComputerName: ComputerName, ErrorCode: Convert.ToString(ex.ErrorCode)); + + throw ex; + } + + catch (Exception ex) + { + + if (FunctionID == "CI") + { + // CheckIn失敗將狀態變更回Queue + if (dtLotNo.Columns.Contains("blnEXETriggerOP")) + { + foreach (DataRow drTempLotInfo in dtLotNo.Rows) + { + if (Convert.ToBoolean(drTempLotInfo["blnEXETriggerOP"])) + { + DataRow[] drSel = dtLotState.Select("LotNO='" + drTempLotInfo["LotNo"] + "'".ToString()); + // Call objReverse.ExecuteReverse(drSel(0)("LotNo"), "AutoExe", Now, , , , , drSel(0)("LotStamp")) + // Call objLot.ExeReverseTriggerOP(drSel(0)("LotNo"), drSel(0)("LotSerial"), drSel(0)("LogGroupSerial"), drSel(0)("LotStamp")) + ExeReverseTriggerOP_NotUseUndo(UserNo, Convert.ToString(drSel[0]["LotNo"]), Convert.ToString(drSel[0]["LotSerial"]), Conversions.ToInteger(drSel[0]["LotStamp"]), ComputerName); + } + } + } + } + + strResult = "fail"; + strRetrunMsg = ex.Message; + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, ex.Message + " : " + ex.StackTrace, ComputerName: ComputerName); + + throw ex; + } + + finally + { + if (!(drTemp == null)) + drTemp.Close(); + if (!(objLot == null)) + { + objLot.Dispose(); + objLot = null; + } + if (!(objSYS == null)) + { + objSYS.Dispose(); + objSYS = null; + } + AutoexecutionLot_LotRet = strRetrunMsg; + CloseConnection(cnnTemp); + } + + return AutoexecutionLot_LotRet; + } + + + public static short funLoadLotStatusJoinOPBusinessRule(string strLotNo, ref DataTable dtLots) + { + short funLoadLotStatusJoinOPBusinessRuleRet = default(short); + + funLoadLotStatusJoinOPBusinessRuleRet = -1; + + try + { + + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + string argstrDataBaseType = "Null"; + + ExecuteSQLQuery_Adapter( + " Select State.*, Basis.MONo, Basis.ProductNo, Basis.ProductVersion, BusinessRule.EXECUTIONFILE,BusinessRule.KERNELMODULE ,BusinessRule.KERNELFUNCTIONNAME,PRDPhase.PHASENO CurPhaseNo, G.SerialNo From tblWIPLotState State " + + " Left Join tblOPBusinessRuleBasis BusinessRule On BusinessRule.BRNO = State.BRNO " + + " Left Join (Select PHASENO,FromNode From tblPRDOPBusinessruleRelation Group by PHASENO,FROMNODE)PRDPhase On State.BRNO =PRDPhase.FROMNODE " + + " Left Join tblWIPTemp_LotState G ON State.LotNo=G.LotNo " + + " Left Join tblWIPLotBasis Basis ON State.LotNo=Basis.BASELOTNO " + + " Where State.LotNo In " + strLotNo, + ds.Tables.Add("LotState"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtLots = ds.Tables[0]; + + funLoadLotStatusJoinOPBusinessRuleRet = 0; + + } + } + catch (Exception e1) + { + funLoadLotStatusJoinOPBusinessRuleRet = -1; + throw; + } + + return funLoadLotStatusJoinOPBusinessRuleRet; + + + } + + + public static short ChkLotStateAndBRNo(string strLotNo, string FunctionID, string OPNo) + { + short ChkLotStateAndBRNoRet = default(short); + + ChkLotStateAndBRNoRet = -1; + var dtTemp = new DataTable(); + + try + { + + using (var ds = new DataSet()) + { + AppSettings objSetting = new AppSettings(); + //根据生产批号查询产品编号以及产品版本 + ExecuteSQLQuery_Adapter( + " select ProductNo,ProductVersion from tblWIPLotbasis where BaseLotNo in " + strLotNo, + dtTemp, objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + string condition = " where OPNo='" + OPNo + "' "; + if (dtTemp.Rows.Count > 0) + { + if (dtTemp.Rows[0]["ProductNo"].ToString() != "") + { + condition += " and ProductNo='" + dtTemp.Rows[0]["ProductNo"].ToString() + "'"; + } + if (dtTemp.Rows[0]["ProductVersion"].ToString() != "") + { + condition += " and ProductVersion='" + dtTemp.Rows[0]["ProductVersion"].ToString() + "'"; + } + } + //string argstrDataBaseType = "Null"; + //using (var cn = new OleDbConnection(objSetting.GetConnectionString(strDataBaseType: ref argstrDataBaseType))) + //{ + // using (var da = new OleDbDataAdapter(" Select State.*, BusinessRule.EXECUTIONFILE,BusinessRule.KERNELMODULE ,BusinessRule.KERNELFUNCTIONNAME,PRDPhase.PHASENO CurPhaseNo From tblWIPLotState State " + " Left Join tblOPBusinessRuleBasis BusinessRule On BusinessRule.BRNO = State.BRNO " + " Left Join (Select PHASENO,FromNode From tblPRDOPBusinessruleRelation Group by PHASENO,FROMNODE)PRDPhase On State.BRNO =PRDPhase.FROMNODE " + " Where State.LotNo In " + strLotNo + " And OPNo ='" + OPNo + "' ", cn)) + // { + // da.Fill(ds.Tables.Add("LotState")); + // } + //} + ExecuteSQLQuery_Adapter( + " Select State.*, BusinessRule.EXECUTIONFILE,BusinessRule.KERNELMODULE ,BusinessRule.KERNELFUNCTIONNAME,PRDPhase.PHASENO CurPhaseNo From tblWIPLotState State " + + " Left Join tblOPBusinessRuleBasis BusinessRule On BusinessRule.BRNO = State.BRNO " + + " Left Join (Select PHASENO,FromNode From tblPRDOPBusinessruleRelation " + condition + " Group by PHASENO,FROMNODE)PRDPhase On State.BRNO =PRDPhase.FROMNODE " + + " Where State.LotNo In " + strLotNo + " And OPNo ='" + OPNo + "' ", + ds.Tables.Add("LotState"), objSetting.GetConnectionString(), objSetting.GetDataBaseType()); + dtTemp = ds.Tables[0]; + + if (dtTemp.Rows.Count == 0) + { + ChkLotStateAndBRNoRet = -2; + return ChkLotStateAndBRNoRet; + } + + if (dtTemp.DefaultView.ToTable(true, "BRNo").Rows.Count > 1) + { + ChkLotStateAndBRNoRet = -3; + return ChkLotStateAndBRNoRet; + } + + foreach (DataRow drTemp in dtTemp.Rows) + { + + if (drTemp["BRNO"].ToString().Contains("SPC")) + { + ChkLotStateAndBRNoRet = -6; + return ChkLotStateAndBRNoRet; + } + + switch (FunctionID) + { + case "CI": + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["CurPhaseNO"], 0, false)) && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["CurPhaseNO"], 1, false))) + { + ChkLotStateAndBRNoRet = -6; + return ChkLotStateAndBRNoRet; + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["Status"], 0, false)) && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["Status"], 1, false))) + { + ChkLotStateAndBRNoRet = -6; + return ChkLotStateAndBRNoRet; + } + + break; + } + + case "CO": + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["CurPhaseNO"], 2, false))) + { + ChkLotStateAndBRNoRet = -6; + return ChkLotStateAndBRNoRet; + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drTemp["Status"], 1, false))) + { + ChkLotStateAndBRNoRet = -6; + return ChkLotStateAndBRNoRet; + } + + break; + } + + } + } + + ChkLotStateAndBRNoRet = 0; + + } + } + catch (Exception e1) + { + ChkLotStateAndBRNoRet = -1; + throw; + } + + return ChkLotStateAndBRNoRet; + + + } + + + + + + //0156845: [6.0.7] 调整EAP接口查核支援BR逻辑 + public static bool ExeBrnoIfSupport(string brdll, string brno) + { + bool blnExecResult = false; + DbDataReader drTemp; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + IDbConnection cnnTemp = null; + try + { + cnnTemp = CreateConnection(strConnectionString); + string strSQL = "select * from TBLSYSEAPBRNOBASIS where UPPER(BRDLL)='" + brdll + "' and UPPER(BRNO)='" + brno + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + blnExecResult = true; + } + drTemp.Close(); + } + catch (Exception ex) + { + blnExecResult = false; + throw; + } + finally + { + CloseConnection(cnnTemp); + } + return blnExecResult; + } + + + + + + + + #endregion + + #region "panleid&unit序号生成" + public static DataTable InitPanleIdOrUnitId(bool ReserveSerialNo = false, long SerialCount = defInteger, string SerialTypeNo = defString, string LotNo = defString, string PanleId = defString, string ProductNo = defString, string SerialType = defString, string AdditionalXml = "", string location = "") + { + DataTable InitPanleIdOrUnitId = default(DataTable); + + AppSettings objSetting = new AppSettings(); + IDbConnection cnnTemp = null; + string strSQL = defString; + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + DataSet dsTemp = new DataSet(); + dsTemp.Tables.Add("InitPanleIdOrUnitId"); + dsTemp.Tables["InitPanleIdOrUnitId"].Columns.Add("SeqNo"); + + string strSerialString = ""; // 序號編碼字串 + + DbDataReader drTemp = null; + + var datEventTime = DateTime.Now; + + var intSer_Len = default(int); // 流水號長度. + var intSer_DT = default(int); // 流水號進位方式-1:10進位,2:16進位,3:36進位. + var intSNIndex = -1; // 流水號所在Index位置 + int intPadLeft = 1; // 流水號是否向左補零 0:不補零,1:自動補零 + + if (SerialCount == defInteger) + SerialCount = 1L; // 沒有傳入產生序號數量則預設值產生一筆序號 + var colParameters = new Collection(); + + var objArgs = new object(); + var arySerial = new ArrayList(); // 流水號陣列 + + DataRow drNew; + + + string strProductNo = ProductNo; + + + + try + { + // 取出編碼規則 + strSQL = "Select * From tblSYSSerialRuleBasis Where SERIALTYPENO = '" + SerialTypeNo + "'AND ENABLE = 1 "; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "SerialRuleBasis", cnnTemp); + + if (dsTemp.Tables["SerialRuleBasis"].Rows.Count == 0) + { + throw new Exception(SerialTypeNo + "[%:序号类别编号不存在或者没有启用!%]"); + } + + + // 取出分批編碼明細 + strSQL = "Select * From tblSYSSerialRuleDetail Where SERIALTYPENO='" + SerialTypeNo + "' Order By ItemNo "; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "SerialRuleDetail", cnnTemp); + + if (dsTemp.Tables["SerialRuleDetail"].Rows.Count == 0) + { + throw new Exception(SerialTypeNo + "[%:序号类别编号不存在或者没有启用!%]"); + } + + // 新增欄位紀錄該編碼項目此次編碼內容 + dsTemp.Tables["SerialRuleDetail"].Columns.Add("Value"); + + for (int i = 0, loopTo = dsTemp.Tables["SerialRuleDetail"].Rows.Count - 1; i <= loopTo; i++) + { + + // 依照不同編碼項目取得值 + switch (dsTemp.Tables["SerialRuleDetail"].Rows[i]["SourceType"].ToString()) + { + + case "SN": + { + + // 進位方式(1:10進位,2:16進位,3:36進位) + intSer_DT = Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["DecimalType"]); + intSer_Len = Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]); + if (dsTemp.Tables["SerialRuleDetail"].Columns.Contains("PadLeft")) + { + intPadLeft = Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["PadLeft"]); + } + intSNIndex = i; + break; + } + + case "UD": + { + + // 序號編碼項目 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += dsTemp.Tables["SerialRuleDetail"].Rows[i]["UserDefine"].ToString(); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = dsTemp.Tables["SerialRuleDetail"].Rows[i]["UserDefine"].ToString(); + break; + } + + case "D1": + case "D2": + case "M1": + case "M2": + case "M3": + case "Y1": + case "Y2": + case "Y4": + case "W2": + { + + // 序號編碼項目 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + string tableTmp = dsTemp.Tables["SerialRuleDetail"].Rows[i]["SourceType"].ToString(); + strSerialString += funExeSerialCreate_Date(ref datEventTime, ref tableTmp); + } + + string tableTmp2 = dsTemp.Tables["SerialRuleDetail"].Rows[i]["SourceType"].ToString(); + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = funExeSerialCreate_Date(ref datEventTime, ref tableTmp2); + break; + } + + case "MO": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strMONo = ""; + strSQL = "Select MONo From tblWIPLotBasis Where BaseLotNo "; + strSQL += " = (Select BaseLotNo From tblWIPLotState Where LotNo = '" + LotNo + "')"; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strMONo = drTemp["MONo"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%MONo%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strMONo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%MONo%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMONo.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMONo.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMONo; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMONo; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strMONo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%MONo%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMONo.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strMONo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMONo.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strMONo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + + case "FC": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strFabCode = ""; + strSQL = "Select FabCode From tblSMDFactoryBasis Where FactoryNo = (Select FactoryNo From tblWIPLotState Where LotNo = '" + LotNo + "')"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strFabCode = drTemp["FabCode"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%FactoryNo%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strFabCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%FabCode%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFabCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFabCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFabCode; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFabCode; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strFabCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%FabCode%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFabCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strFabCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFabCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strFabCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + + case "MTC": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strMOTypeCode = ""; + + strSQL = " Select MT.MOTypeCode From tblWIPLotState LS "; + strSQL += "Left Join tblWIPLotBasis LB On LS.BaseLotNo = LB.BaseLotNo "; + strSQL += "Left Join tblOEMOBasis MO On LB.MONo = MO.MONo "; + strSQL += "Left Join tblSYSMOTypeBasis MT On MO.MOTypeNo = MT.MOTypeNo "; + strSQL += "Where LS.LotNo = '" + LotNo + "' "; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strMOTypeCode = drTemp["MOTypeCode"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%MOTypeNo%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strMOTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%MOTypeCode%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMOTypeCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMOTypeCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMOTypeCode; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMOTypeCode; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strMOTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%MOTypeCode%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strMOTypeCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strMOTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strMOTypeCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strMOTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + + case "PTC": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strProductTypeCode = ""; + + strSQL = " Select PT.ProductTypeCode From tblWIPLotState LS "; + strSQL += "Left Join tblWIPLotBasis LB On LS.BaseLotNo = LB.BaseLotNo "; + strSQL += "Left Join tblPRDProductBasis PB On LB.ProductNo = PB.ProductNo AND LB.ProductVersion = PB.ProductVersion "; + strSQL += "Left Join tblPRDType PT On PB.ProductType = PT.ProductType "; + strSQL += "Where LS.LotNo = '" + LotNo + "' "; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strProductTypeCode = drTemp["ProductTypeCode"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%ProductType%],[%ProductNo%],[%ProductVersion%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductType%],[%ProductNo%],[%ProductVersion%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductTypeCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductTypeCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductTypeCode; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductTypeCode; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductType%],[%ProductNo%],[%ProductVersion%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductTypeCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductTypeCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductTypeCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + + case "PN": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + //string strProductNo = ""; + + strSQL = " Select PB.ProductNo From tblWIPLotState LS "; + strSQL += "Left Join tblWIPLotBasis LB On LS.BaseLotNo = LB.BaseLotNo "; + strSQL += "Left Join tblPRDProductBasis PB On LB.ProductNo = PB.ProductNo AND LB.ProductVersion = PB.ProductVersion "; + strSQL += "Where LS.LotNo = '" + LotNo + "' "; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strProductNo = drTemp["ProductNo"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%ProductNo%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductNo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductNo%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductNo.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductNo.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductNo; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductNo; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductNo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductNo%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductNo.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductNo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductNo.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductNo.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + + case "PC": + { + + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strProductCode = ""; + + strSQL = " Select PB.ProductCode From tblWIPLotState LS "; + strSQL += "Left Join tblWIPLotBasis LB On LS.BaseLotNo = LB.BaseLotNo "; + strSQL += "Left Join tblPRDProductBasis PB On LB.ProductNo = PB.ProductNo AND LB.ProductVersion = PB.ProductVersion "; + strSQL += "Where LS.LotNo = '" + LotNo + "' "; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strProductCode = drTemp["ProductCode"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%ProductNo%],[%ProductVersion%]"); + } + drTemp.Close(); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductCode%],[%ProductNo%],[%ProductVersion%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductCode.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductCode; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductCode; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strProductCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%ProductCode%],[%ProductNo%],[%ProductVersion%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strProductCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strProductCode.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strProductCode.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + case "FUN": + { + + string strFunString = ""; + // 2018/04/10 OwenLiu, Mantis:0045761, 增加客製 SerialNoFunction 支援機制 + string strScripFuncName = dsTemp.Tables["SerialRuleDetail"].Rows[i]["FunctionName"].ToString(); + MethodInfo mi = null; + + if (strScripFuncName.ToUpper().StartsWith("FUNC_")) + { + using (var objSerialNoFunction = new udSYS_Customer.clsSerialNoFunction()) + { + mi = objSerialNoFunction.GetType().GetMethod(strScripFuncName, BindingFlags.Public | BindingFlags.Instance); + if (!(mi == null)) + { + try + { + strFunString = Convert.ToString(mi.Invoke(objSerialNoFunction, (object[])objArgs)); + } + catch (TargetInvocationException tie) + { + throw tie.InnerException; + } + catch (Exception ex) + { + throw; + } + } + else + { + throw new iMESException.MESException("0000-200091", "[%Function%] [%not found%]: " + dsTemp.Tables["SerialRuleDetail"].Rows[i]["FunctionName"].ToString()); + } + } + } + else + { + using (var objSerialNoFunction = new udSYS.clsSerialNoFunction()) + { + mi = objSerialNoFunction.GetType().GetMethod(strScripFuncName, BindingFlags.Public | BindingFlags.Instance); + if (!(mi == null)) + { + try + { + strFunString = Convert.ToString(mi.Invoke(objSerialNoFunction, (object[])objArgs)); + } + catch (TargetInvocationException tie) + { + throw tie.InnerException; + } + catch (Exception ex) + { + throw; + } + } + else + { + throw new iMESException.MESException("0000-200091", "[%Function%] [%not found%]: " + dsTemp.Tables["SerialRuleDetail"].Rows[i]["FunctionName"].ToString()); + } + } + } + + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strFunString.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", strFunString); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFunString.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFunString.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFunString; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFunString; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(strFunString.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", strFunString); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += strFunString.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strFunString.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strFunString.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(strFunString.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + case "PCB供应商代码": + { + if (PanleId == defString) + { + throw new Exception("PanleId: " + PanleId + " 不能为空!"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 0, false))) // 有指定起訖字串位置 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(PanleId.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "PanleId 长度不足!"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += PanleId.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = PanleId.Substring(Conversions.ToInteger(Operators.SubtractObject(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"], 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 1, false))) // 取得全部字串 + { + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += PanleId; + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = PanleId; + } + + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["GetData"], 2, false))) // 右側取碼 + { + + // 判斷長度是否足夠 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLess(Operators.AddObject(Operators.SubtractObject(PanleId.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), 1), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"], false))) + { + throw new iMESException.MESException("0000-220021", "[%PanleId%]"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + { + strSerialString += PanleId.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(PanleId.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + } + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = PanleId.Substring(Conversions.ToInteger(Operators.AddObject(Operators.SubtractObject(Operators.SubtractObject(PanleId.Length, dsTemp.Tables["SerialRuleDetail"].Rows[i]["SearchStart"]), dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"]), 1)), Conversions.ToInteger(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialLength"])); + + } + + break; + } + case "基板信息": + { + if (PanleId == defString) + { + throw new Exception("PanleId: " + PanleId + " 不能为空!"); + } + + strSerialString += PanleId; + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = PanleId; + break; + } + case "Year_LQ": + { + + + strSQL = "SELECT CUSTOMCODE FROM TBLCUSNUMCUSTOM WHERE PRODUCTNO='" + strProductNo + "' AND CUSTOMTYPE='年' AND CUSTOMSOURCE='" + datEventTime.Year.ToString("D4") + "'"; + + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strSerialString += drTemp["CUSTOMCODE"].ToString(); + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = drTemp["CUSTOMCODE"].ToString(); + } + else + { + throw new Exception("Year_LQ 规则未生成!请检查panleid&unit序号规则_年月周定义设定!"); + } + drTemp.Close(); + break; + } + case "Mouth_LQ": + { + + + + strSQL = @"SELECT CUSTOMCODE FROM TBLCUSNUMCUSTOM WHERE PRODUCTNO = '" + strProductNo + "' AND CUSTOMTYPE = '月' AND( CUSTOMSOURCE = '" + datEventTime.Month.ToString("D2") + "' OR CUSTOMSOURCE = '" + datEventTime.Month.ToString() + "')"; + + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strSerialString += drTemp["CUSTOMCODE"].ToString(); + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = drTemp["CUSTOMCODE"].ToString(); + } + else + { + throw new Exception("Mouth_LQ 规则未生成!请检查panleid&unit序号规则_年月周定义设定!"); + } + drTemp.Close(); + + break; + } + case "Week_LQ": + { + + + + int dayOfYear = datEventTime.DayOfYear; + int week = (dayOfYear + 6) / 7; + string WeekNo = week.ToString(); + + strSQL = @"SELECT CUSTOMCODE FROM TBLCUSNUMCUSTOM WHERE PRODUCTNO = '" + strProductNo + "' AND CUSTOMTYPE = '周' AND CUSTOMSOURCE ='" + WeekNo + "'"; + + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strSerialString += drTemp["CUSTOMCODE"].ToString(); + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = drTemp["CUSTOMCODE"].ToString(); + } + else + { + throw new Exception("Week_LQ 规则未生成!请检查panleid&unit序号规则_年月周定义设定!"); + } + drTemp.Close(); + break; + } + case "Day_LQ": + { + + + + strSQL = @"SELECT CUSTOMCODE FROM TBLCUSNUMCUSTOM WHERE PRODUCTNO = '" + strProductNo + "' AND CUSTOMTYPE = '日' AND( CUSTOMSOURCE = '" + datEventTime.Day.ToString("D2") + "' OR CUSTOMSOURCE = '" + datEventTime.Day.ToString() + "')"; + + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strSerialString += drTemp["CUSTOMCODE"].ToString(); + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = drTemp["CUSTOMCODE"].ToString(); + } + else + { + throw new Exception("Day_LQ 规则未生成!请检查panleid&unit序号规则_年月周日定义设定!"); + } + drTemp.Close(); + + break; + } + case "位置编号": + { + + //strSerialString += location; + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = location; + break; + } + case "工单属性": + { + if (LotNo == defString) + throw new iMESException.MESException("0000-200002", "[%LotNo%]"); + + string strMONo = ""; + strSQL = "Select MONo From tblWIPLotBasis Where BaseLotNo "; + strSQL += " = (Select BaseLotNo From tblWIPLotState Where LotNo = '" + LotNo + "')"; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strMONo = drTemp["MONo"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", "[%MONo%]"); + } + drTemp.Close(); + + // 序號編碼項目 + //if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["SerialRuleDetail"].Rows[i]["SerialCodeFlag"], 1, false))) + //{ + // strSerialString += dsTemp.Tables["SerialRuleDetail"].Rows[i]["UserDefine"].ToString(); + //} + string strPropertyNO = ""; + string value = dsTemp.Tables["SerialRuleDetail"].Rows[i]["UserDefine"].ToString(); + strSQL = $"Select PROPERTYVALUE From TBLOEMOPROPERTY Where MONO = '{strMONo}' and PROPERTYNO = '{value}' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strPropertyNO = drTemp["PROPERTYVALUE"].ToString(); + } + else + { + throw new iMESException.MESException("0000-220020", $"{value}属性编号不存在"); + } + drTemp.Close(); + + + dsTemp.Tables["SerialRuleDetail"].Rows[i]["Value"] = strPropertyNO; + break; + } + } + + } + + + if (arySerial.Count == 0) + { + // 呼叫序號產生,取得目前最大值,並且產生多筆序號,更新系統紀錄 + // arySerial = funExeSerialCreate_Serial(cnnTemp, "LOTNO", SerialCount, strSerialString, intSer_Len, intSer_DT, ReserveSerialNo) + string argSerialType1 = SerialType; + arySerial = funExeSerialCreate_Serial(ref cnnTemp, ref argSerialType1, ref SerialCount, ref strSerialString, ref intSer_Len, ref intSer_DT, ref ReserveSerialNo, intPadLeft); + } + + // 將編碼與流水號合併 + for (int i = 0, loopTo6 = arySerial.Count - 1; i <= loopTo6; i++) + { + + strSerialString = ""; + for (int j = 0, loopTo7 = dsTemp.Tables["SerialRuleDetail"].Rows.Count - 1; j <= loopTo7; j++) + { + + if (j == intSNIndex) + { + strSerialString += arySerial[0].ToString(); + } + else + { + strSerialString += dsTemp.Tables["SerialRuleDetail"].Rows[j]["Value"].ToString(); + } + + } + + drNew = dsTemp.Tables["InitPanleIdOrUnitId"].NewRow(); + drNew["SeqNo"] = strSerialString; + dsTemp.Tables["InitPanleIdOrUnitId"].Rows.Add(drNew); + + } + + + // 移除多餘Table + dsTemp.Tables.Remove("SerialRuleBasis"); + dsTemp.Tables.Remove("SerialRuleDetail"); + + if (!(dsTemp.Tables["LotStateJoinBasis"] == null)) + dsTemp.Tables.Remove("LotStateJoinBasis"); + + // //Combine return value + InitPanleIdOrUnitId = dsTemp.Tables[0]; + } + catch (Exception e1) + { + InitPanleIdOrUnitId = null; + throw; + } + finally + { + drTemp?.Close(); + dsTemp?.Dispose(); + CloseConnection(cnnTemp); + } + return InitPanleIdOrUnitId; + } + + + + public static string funExeSerialCreate_Date(ref DateTime EventTime, ref string SourceType) + { + string funExeSerialCreate_DateRet = default(string); + + var strResult = default(string); + + try + { + switch (SourceType) + { + + case "D1": + { + switch (EventTime.ToString("dd")) + { + case "01": + case "02": + case "03": + case "04": + case "05": + case "06": + case "07": + case "08": + case "09": + { + strResult = EventTime.ToString("dd").Substring(1, 1); + break; + } + case "10": + { + strResult = "A"; + break; + } + case "11": + { + strResult = "B"; + break; + } + case "12": + { + strResult = "C"; + break; + } + case "13": + { + strResult = "D"; + break; + } + case "14": + { + strResult = "E"; + break; + } + case "15": + { + strResult = "F"; + break; + } + case "16": + { + strResult = "G"; + break; + } + case "17": + { + strResult = "H"; + break; + } + case "18": + { + strResult = "I"; + break; + } + case "19": + { + strResult = "J"; + break; + } + case "20": + { + strResult = "K"; + break; + } + case "21": + { + strResult = "L"; + break; + } + case "22": + { + strResult = "M"; + break; + } + case "23": + { + strResult = "N"; + break; + } + case "24": + { + strResult = "O"; + break; + } + case "25": + { + strResult = "P"; + break; + } + case "26": + { + strResult = "Q"; + break; + } + case "27": + { + strResult = "R"; + break; + } + case "28": + { + strResult = "S"; + break; + } + case "29": + { + strResult = "T"; + break; + } + case "30": + { + strResult = "U"; + break; + } + case "31": + { + strResult = "V"; + break; + } + } + + break; + } + + case "D2": + { + strResult = Strings.Format(DateAndTime.DatePart(DateInterval.Day, EventTime), "00"); + break; + } + + case "M1": + { + switch (EventTime.ToString("MM")) + { + case "01": + case "02": + case "03": + case "04": + case "05": + case "06": + case "07": + case "08": + case "09": + { + strResult = EventTime.ToString("MM").Substring(1, 1); + break; + } + case "10": + { + strResult = "A"; + break; + } + case "11": + { + strResult = "B"; + break; + } + case "12": + { + strResult = "C"; + break; + } + } + + break; + } + + case "M2": + { + strResult = Strings.Format(DateAndTime.DatePart(DateInterval.Month, EventTime), "00"); + break; + } + + case "M3": + { + int intMonth; + intMonth = DateAndTime.DatePart(DateInterval.Month, EventTime); + switch (intMonth) + { + case 1: + { + strResult = "JAN"; + break; + } + case 2: + { + strResult = "FEB"; + break; + } + case 3: + { + strResult = "MAR"; + break; + } + case 4: + { + strResult = "APR"; + break; + } + case 5: + { + strResult = "MAY"; + break; + } + case 6: + { + strResult = "JUN"; + break; + } + case 7: + { + strResult = "JUL"; + break; + } + case 8: + { + strResult = "AUG"; + break; + } + case 9: + { + strResult = "SEP"; + break; + } + case 10: + { + strResult = "OCT"; + break; + } + case 11: + { + strResult = "NOV"; + break; + } + case 12: + { + strResult = "DEC"; + break; + } + } + + break; + } + + case "Y1": + { + strResult = Strings.Mid(DateAndTime.DatePart(DateInterval.Year, EventTime).ToString(), 4, 1); + break; + } + + case "Y2": + { + strResult = Strings.Mid(DateAndTime.DatePart(DateInterval.Year, EventTime).ToString(), 3, 2); + break; + } + + case "Y4": + { + strResult = DateAndTime.DatePart(DateInterval.Year, EventTime).ToString(); + break; + } + + case "W2": + { + strResult = Strings.Format(DateAndTime.DatePart(DateInterval.WeekOfYear, EventTime, FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1), "00"); + break; + } + + default: + { + throw new iMESException.MESException("0000-200015", "[%SourceType%] is not valid!"); + } + } + + // Return + funExeSerialCreate_DateRet = strResult; + } + + catch (Exception e1) + { + funExeSerialCreate_DateRet = "fail"; + throw; + } + finally + { + + } + + return funExeSerialCreate_DateRet; + + } + + + private static ArrayList funExeSerialCreate_Serial(ref IDbConnection cnnTemp, ref string SerialType, ref long SerialCount, ref string SerialString, ref int SerialLength, ref int DecimalType, ref bool ReserveSerialNo, int PadLeft = defInteger) + { + ArrayList funExeSerialCreate_SerialRet = default(ArrayList); + + DbDataReader drTemp = null; + var colSQL = new Collection(); + var colSQL_Rows = new Collection(); + var arySerial = new ArrayList(); + string strSQL = ""; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + try + { + + if (SerialCount <= 0L) + { + throw new iMESException.MESException("0000-200017", "[%MOQty%]"); + } + + // 取出最大碼. + bool blnInsert; + long lngMaxSerialNo; // 起始碼. + long lngSerialNo_Last; // 最大一個序號. + var strSerialNo_Last_nn = default(string); // 轉換成10,16,36表示式. + + strSQL = "Select MaxSerialNo From tblSYSSerialCreateMax " + " Where SerialType='" + SerialType + "'" + " And SerialString='" + SerialString + "'" + " And SerialLength=" + SerialLength + " And DecimalType=" + DecimalType; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + blnInsert = false; + lngMaxSerialNo = Conversions.ToLong(drTemp["MaxSerialNo"]); + } + else + { + blnInsert = true; + lngMaxSerialNo = 0L; + } + drTemp.Close(); + + // 最大的序號 + lngSerialNo_Last = lngMaxSerialNo + SerialCount; + + if (DecimalType == 1) + { + strSerialNo_Last_nn = lngSerialNo_Last.ToString(); + } + else if (DecimalType == 2) + { + strSerialNo_Last_nn = Tran10_16(lngSerialNo_Last); + } + else if (DecimalType == 3) + { + strSerialNo_Last_nn = Tran10_36(lngSerialNo_Last); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + strSerialNo_Last_nn = Tran10_34(lngSerialNo_Last); + // ===================================== 86774 End ===================================== + + } + + // 最大碼是否超出序號長度. + if (strSerialNo_Last_nn != null && strSerialNo_Last_nn.Length > SerialLength) + { + throw new iMESException.MESException("9P12-200028", "[%SerialString%]: " + SerialString + Constants.vbNewLine + "[%SerialLength%]: " + SerialLength + Constants.vbNewLine + "[%SerialNo%]: " + strSerialNo_Last_nn); + } + + if (ReserveSerialNo == true) + { + // 回填最大碼(利用MaxSerialNo來確保資料的一致性及使用的序號為唯一) + if (blnInsert) + { + strSQL = "Insert into tblSYSSerialCreateMax " + " (SerialType,SerialString,SerialLength,DecimalType,MaxSerialNo) " + " Values('" + SerialType + "','" + SerialString + "'," + SerialLength + "," + DecimalType + "," + lngSerialNo_Last + ")"; + colSQL.Add(strSQL); + colSQL_Rows.Add(1); + } + else + { + strSQL = "Update tblSYSSerialCreateMax Set MaxSerialNo=" + lngSerialNo_Last + " Where SerialType='" + SerialType + "'" + " And SerialString='" + SerialString + "'" + " And SerialLength=" + SerialLength + " And DecimalType=" + DecimalType + " And MaxSerialNo=" + lngMaxSerialNo; + colSQL.Add(strSQL); + colSQL_Rows.Add(1); + } + + ExecuteSQLNoneQuery_ChkRowCount(strDataBaseType, strConnectionString, colSQL, colSQL_Rows); + } + + for (int i = 1, loopTo = (int)SerialCount; i <= loopTo; i++) + { + if (PadLeft == 0) + { + if (DecimalType == 1) + { + arySerial.Add((lngMaxSerialNo + i).ToString()); + } + else if (DecimalType == 2) + { + arySerial.Add(Tran10_16(lngMaxSerialNo + i).ToString()); + } + else if (DecimalType == 3) + { + arySerial.Add(Tran10_36(lngMaxSerialNo + i).ToString()); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + arySerial.Add(Tran10_34(lngMaxSerialNo + i).ToString()); + // ===================================== 86774 End ===================================== + } + } + else if (DecimalType == 1) + { + arySerial.Add((lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + else if (DecimalType == 2) + { + arySerial.Add(Tran10_16(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + else if (DecimalType == 3) + { + arySerial.Add(Tran10_36(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + arySerial.Add(Tran10_34(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + // ===================================== 86774 End ===================================== + } + } + + // 回傳最大碼 + funExeSerialCreate_SerialRet = arySerial; + } + + catch (Exception e1) + { + funExeSerialCreate_SerialRet = null; + throw; + } + finally + { + + } + + return funExeSerialCreate_SerialRet; + + } + + + #endregion + + #region "分批客制" + //客制母批不需要变状态 + + // 功能:依dtSplitLot內的資料,執行分批. + // 傳入值:LotNo,dtSplitLot + // 傳回值:success(成功), fail(失敗) + // 修改:2008/08/26,sammi.可由使用者指定SysQty而不自動計算. + // 修改:2009/08/14,yumei, tblWIPLotLog*新增OPGroupNo欄位 + // 修改:2012/06/18,sammi.新增多人加工處理. + // 修改:2019/04/25 Lena, 交辦單:W084562019040028 + // 調整在製品庫分批,當生產批為在製品庫分批且狀態已為99結批時,不建立還原點,不允許還原.(因生產批結批時,已將其所有還原的資料都已刪除,故不能做還原的作業) + public static string BR_Manual_LotSplit_M(long LotStamp, string MLotNo, int SplitType, string UserNo, DataTable dtSplitLot, string LinkName = defString, string ShiftNo = defString, string AdditionalXml = "", string EventDescription = "", bool blnWIPInv = false, int intUserActiveId = defInteger) + { + string BR_Manual_LotSplitRet = default(string); + + // PS1.手動的分批可能發生在任一時點(站中or站間) + // PS2.手動分批也可是一個BR,若是BR則分批完成,Staus要變更為4 + + IDbConnection cnnTemp = null; + var dsTemp = new DataSet(); + DbDataReader drTemp = null; + var CollectionSQL = new Collection(); + Collection colToINVLotNo = new Collection(); + + DataRow drAdd; + DataRow[] drSel; + string MNewLotSerial, SLotNo, SLotSerial, SerialNo; + int MReverseId = default(int), SReverseId = default(int); + string MLotSerial, AutoMergeToLotNo; + var decSplitQty = default(decimal); + DateTime datEventTime; + bool blnAutoMerge, blnHaveFromLot, blnHaveSysQty; + int intOPStatus; + decimal MLotQtyAfterSplit = defInteger; + int i; + string MLogGroupSerial; + + var aryLotProperty = new ArrayList(); + bool blnECN = false; + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III + var EventTime = DateTime.Now; + objLotLog = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle(intUserActiveId, UserNo, EventTime); + objLotLog.ColSQL = CollectionSQL; + // === + // ===2021/09/13 Troy 生產批歷程,將MCurQty, SysQty移至外層宣告 mantis:94662 + decimal MCurQty, SysQty; + + SLotSerial = ""; + SerialNo = ""; + AutoMergeToLotNo = ""; + + string strSQL = ""; + kcWIP.clsLot objLot = new kcWIP.clsLot(); + + AppSettings objSetting = new AppSettings(); + + + string DataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + // 2020/02/12 Eric Mantis:0067304(分批未繼承ECN) 確認是否為IC_FT_PKG + bool blnIsIC_PKG = false; + strSQL = "Select Count(ACTIVEMODULE) from TBLSYSFUNCTION Where ActiveModule='IC_FT_PKG'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + if (Convert.ToBoolean(Operators.ConditionalCompareObjectGreater(ExecuteSQLQuery_Scalar(strSQL, cnnTemp), 0, false))) + blnIsIC_PKG = true; + + + // 1.檢查子批------------------------------------------------------------------------------------------------------------- + if (dtSplitLot.Select("Action <> 0 And Action <> 1 And Action <> 2").Length > 0) + { + throw new iMESException.MESException("0000-200015", "Action of Split Lot is not Valid Valud(0:Go,1:Jump OP,2:Jump Process)!!"); + } + + // 檢查新分批的子批中是否有FromLotNo + drSel = dtSplitLot.Select("SplitLotNo ='" + MLotNo + "'"); + if (drSel.Length == 0) + { + blnHaveFromLot = false; + } + else + { + // 2020/11/9,Ning,0081028: [6.0.5]分批處理,產品變更/流程變更調整 + // If drSel(0)("Action") <> 0 Then + // Throw New iMESException.MESException("0000-214010", "[SplitLotNo:" & MLotNo & " only support GO action.]") + // End If + MLotQtyAfterSplit = Convert.ToDecimal(drSel[0]["SplitLotQty"]); + blnHaveFromLot = true; + } + + // 2.加總SplitLotQty------------------------------------------------------------------------------------------------------ + var loopTo = dtSplitLot.Rows.Count - 1; + for (i = 0; i <= loopTo; i++) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectLessEqual(dtSplitLot.Rows[i]["SplitLotQty"], 0, false))) + { + throw new iMESException.MESException("0000-200017", "SplitLotNo:" + + dtSplitLot.Rows[i]["SplitLotNo"] + " SplitQty = 0!!"); + } + decSplitQty = Convert.ToDecimal(Operators.AddObject(decSplitQty, dtSplitLot.Rows[i]["SplitLotQty"])); + } + + // 3.取出母批相關資料----------------------------------------------------------------------------------------------------- + datEventTime = DateTime.Now; + + objLot.SHR_Split_GetReference(ref cnnTemp, ref dsTemp, ref SerialNo, MLotNo, datEventTime); + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(decSplitQty, dsTemp.Tables["LotState"].Rows[0]["CurQty"], false))) + { + throw new iMESException.MESException("0000-214003", "Sum of SplitLotQty(" + Strings.Format(decSplitQty, "0.####") + ") is not equal CurQty(" + Strings.Format(dsTemp.Tables["LotState"].Rows[0]["CurQty"], "0.####") + ") of LotNo!!"); + } + + // 2020/02/12 Eric Mantis:0067304(分批未繼承ECN) 若產品的CustomerNo及DeviceNo皆不為N/A, 才啟用ECN相關處理 + strSQL = "Select CustomerNo,DeviceNo From tblPRDProductBasis Where ProductNo ='" + dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString() + "'" + " And ProductVersion = '" + dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString() + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (drTemp["CustomerNo"].ToString() != "N/A" && drTemp["DeviceNo"].ToString() != "N/A" && !string.IsNullOrEmpty(drTemp["CustomerNo"].ToString()) && !string.IsNullOrEmpty(drTemp["DeviceNo"].ToString())) + { + blnECN = true; + } + } + drTemp.Close(); + + + MLotSerial = dsTemp.Tables["LotState"].Rows[0]["LotSerial"].ToString(); + intOPStatus = Conversions.ToInteger(dsTemp.Tables["LotState"].Rows[0]["OPStatus"]); + MLogGroupSerial = dsTemp.Tables["LotState"].Rows[0]["LogGroupSerial"].ToString(); + + // 3.1取出主批之庫房資訊 + if (blnWIPInv) + { + strSQL = "Select * From tblINVWIPInventory_Semi Where LotNo = '" + MLotNo + "'"; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp = New OleDb.OleDbDataAdapter(cmmTemp) + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "WIPInv_RefLot", cnnTemp); + + if (dsTemp.Tables["WIPInv_RefLot"].Rows.Count == 0) + { + throw new iMESException.MESException("0000-202002", "[%LotNo%] : " + MLotNo); + } + + } + + // 4.Create ToLot Table for Split Inherit use--------------------------------------------------------------------------- + var dtSplitCont = new DataTable("SplitLot"); + dtSplitCont.Columns.Add("ToLotNo", Type.GetType("System.String")); + dtSplitCont.Columns.Add("ToBaseLotNo", Type.GetType("System.String")); + dtSplitCont.Columns.Add("ToLotSerial", Type.GetType("System.String")); + dtSplitCont.Columns.Add("ToReverseId", Type.GetType("System.Int32")); + dtSplitCont.Columns.Add("ToLotQty", Type.GetType("System.Decimal")); + dtSplitCont.Columns.Add("MajorLot", Type.GetType("System.Byte")); // 0:No,1:Yes(應該只有一筆是1) + + // 5.判斷SysQty的來源. + if (dtSplitLot.Columns.Contains("SplitSysQty") && dtSplitLot.Select("SplitSysQty is null").Length == 0) + { + blnHaveSysQty = true; // 使用前端傳入的SysQty而不自動計算. + } + else + { + blnHaveSysQty = false; + } // 由系統自動計算. + + // 5.母批--------------------------------------------------------------------------------------------------------------- + // 不可以使用LotState上的LotSerial,必須重新產生,否則Undo時會將前一Reverse已備份的BK刪除 + MNewLotSerial = objLot.InitLotSerial(MLotNo); + + // 2019/04/25 Lena, 在製品庫分批且生產批狀態已為99結批,不建立還原點 + if (!blnWIPInv || Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dsTemp.Tables["LotState"].Rows[0]["LotState"], 99, false))) + { + var tmp = dsTemp.Tables["LotState"].Rows[0]; + string argOPNo = tmp["OPNo"].ToString(); + udReverse.clsReverse.ReverseType revTypeTmp = udReverse.clsReverse.ReverseType.Split_From; + MReverseId = objReverse.NewReverseID(ref MLotNo, ref revTypeTmp, ref MNewLotSerial, ref argOPNo, ref CollectionSQL, Description: "BR Manual Split(From Lot)", Creator: UserNo, CreateDate: datEventTime); + tmp["OPNo"] = argOPNo; + } + + if (SplitType == 1) // BR分批 + { + // 加入Cont_Employee + strSQL = "Insert into tblWIPCont_Employee(LogGroupSerial,LotSerial,LotNo,OPNo,BRNo,UserNo,FunctionName,ShiftNo,EventTime)" + " Values('" + + dsTemp.Tables["LotState"].Rows[0]["LogGroupSerial"] + "','" + MNewLotSerial + "','" + MLotNo + "','" + dsTemp.Tables["LotState"].Rows[0]["OPNo"] + + "','" + dsTemp.Tables["LotState"].Rows[0]["BRNo"] + "','" + UserNo + "','BR_Manual_LotSplit','" + ShiftNo + "'," + "To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + + "','YYYY/MM/DD HH24:MI:SS'))"; + CollectionSQL.Add(strSQL); + } + + if (intOPStatus == 1) + { + // 變更LotLog的EndTime + strSQL = "Select EndTime From tblWIPLotLog Where LotSerial = '" + MLotSerial + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strSQL = "Update tblWIPLotLog Set EndTime = To_Date('" + Strings.Format(Convert.ToDateTime(datEventTime), "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + " Where LotSerial = '" + MLotSerial + "'"; + CollectionSQL.Add(strSQL); + + // 加入ReverseUpdateContent + if (drTemp["EndTime"] is DBNull) + { + strSQL = "Update tblWIPLotLog Set EndTime = null Where LotSerial = '" + MLotSerial + "'"; + } + else + { + strSQL = "Update tblWIPLotLog Set EndTime = To_Date('" + Strings.Format(Convert.ToDateTime(drTemp["EndTime"]), "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + " Where LotSerial = '" + MLotSerial + "'"; + } + Collection argcolSQL_Rows = null; + objReverse.AddReverseUpdateContent(ref MNewLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows); + } + drTemp.Close(); + + } + + // 併回處理 + // 檢查母批是否已指定為要併回 + strSQL = "Select FromLotNo,ToLotNo From tblWIPAutoMerge Where FromLotNo = '" + MLotNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) // 是 + { + blnAutoMerge = true; + AutoMergeToLotNo = drTemp["ToLotNo"].ToString(); + if (!blnHaveFromLot) + { + // 刪除母批併回資料(將子批併回資料加入,再後面處理) + strSQL = "Delete From tblWIPAutoMerge Where FromLotNo = '" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + } + } + else + { + blnAutoMerge = false; + } + drTemp.Close(); + + + if (blnHaveFromLot) // 扣量處理 + { + int intStatus = defInteger; + int intGOStatus = defInteger; + + if (intOPStatus == 1) + { + if (SplitType == 1) // BR分批 + { + if (LinkName == "HOLD") + { + intStatus = 3; + intGOStatus = 4; + } + else if (LinkName == "WAIT") + { + intStatus = 2; + intGOStatus = 4; + } + else + { + intStatus = 4; + intGOStatus = defInteger; + } + } + else + { + } // 站中手動分批,不需要變更. + } + + // 系統數量. + // ===2021/09/13 Troy 生產批歷程,移至外層宣告 mantis:94662 + // Dim MCurQty, SysQty As Decimal + + drSel = dtSplitLot.Select("SplitLotNo ='" + MLotNo + "'"); + MCurQty = Convert.ToDecimal(drSel[0]["SplitLotQty"]); + + if (blnHaveSysQty) + { + SysQty = Convert.ToDecimal(drSel[0]["SplitSysQty"]); + } + else + { + // 計算系統數量. + var objUnit = new udUnitTransferFunction.clsUnitTransferFunction(); + var colParameters = new Collection(); + + colParameters.Add(dsTemp.Tables["LotState"].Rows[0]["ENGNo"].ToString(), "ENGNo"); + colParameters.Add(dsTemp.Tables["LotState"].Rows[0]["ENGVersion"].ToString(), "ENGVersion"); + colParameters.Add(dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(), "ProductNo"); + colParameters.Add(dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(), "ProductVersion"); + SysQty = Convert.ToDecimal(objUnit.EXETransferQty(dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"].ToString(), dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"].ToString(), (double)MCurQty, colParameters)); + objUnit = null; + } + + //0370 20260604 母批不走完成状态 + + // 其他修改的資料(LotSerial,NewReverseId內已更新.) + strSQL = "Update tblWIPLotState Set CurQty = " + MCurQty + "," + " CurUnitNo = '" + + dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"] + "'," + " SysQty = " + SysQty + "," + " SysUnitNo = '" + dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"] + + "'," + " EventTime=To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + " EventUserNo='" + UserNo + + "'," + " EventDescription='" + EventDescription + "'"; + // BR分批或手動分批會有不同的處理. + if (LinkName != defString) + strSQL += ",LinkName='" + LinkName + "'"; + + //0370 20260604 母批不走完成状态 + + //if (intStatus != defInteger) + // strSQL += ",Status=" + intStatus; + + if (intGOStatus != defInteger) + strSQL += ",GOStatus=" + intGOStatus; + strSQL += " Where LotNo ='" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + + // 2009/9/10,yumei,更新母批tblWIPTemp_Attrib,tblWIPCont_Attrib資料,NewLot_Split只有更新子批---- + if (intOPStatus == 1) // 站中 + { + var tmp1 = dsTemp.Tables; + var argdtLotState = tmp1["LotState"]; + var tmp2 = dsTemp.Tables; + var argdtTempLotAttrib = tmp2["TempLotAttrib"]; + var tmp3 = dsTemp.Tables; + var argdtLotProperty = tmp3["LotProperty"]; + var tmp4 = dsTemp.Tables; + var argdtLotECNAttrib = tmp4["LotECNAttrib"]; + objLot.UpdLotAttrib(ref MLotNo, ref MNewLotSerial, ref MLogGroupSerial, (double)MCurQty, argdtLotState, argdtTempLotAttrib, dtLotProperty: argdtLotProperty, dtLotECNAttrib: argdtLotECNAttrib, CollectionSQL: CollectionSQL); + + //2023/8/22,Ning,143969: 木林森项目:木林森项目,进站后,站分批,母批出站时会按照原始的inputqty计算物料耗用 + strSQL = "Update tblWIPTemp_LotState Set CurQty = " + MCurQty + " Where LotNo = '" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + } + // ------------------------- + + drAdd = dtSplitCont.NewRow(); + drAdd["ToLotNo"] = MLotNo; + drAdd["ToBaseLotNo"] = dsTemp.Tables["LotState"].Rows[0]["BaseLotNo"]; + drAdd["ToLotSerial"] = MNewLotSerial; + drAdd["ToReverseId"] = MReverseId; + drAdd["ToLotQty"] = MCurQty; + drAdd["MajorLot"] = 1; + dtSplitCont.Rows.Add(drAdd); + + // 母批變更產品 + // ===生產批歷程,新增boolean,判斷母批是否有改產品 + bool blnChgProduct = false; + // === + var drSelMLot = dtSplitLot.Select("SplitLotNo ='" + MLotNo + "'"); + drSel = dsTemp.Tables["LotState"].Select("LotNo ='" + MLotNo + "'"); + + string ProcessNo, ProcessVersion, strECNNo, AttribValue; + decimal decCurQty = Convert.ToDecimal(dsTemp.Tables["LotState"].Rows[0]["CurQty"]); + string MOrgProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(); + string MOrgProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(); + string OPNo = dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString(); + if ((Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drSelMLot[0]["ProductNo"], MOrgProductNo, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drSelMLot[0]["ProductVersion"], MOrgProductVersion, false))) && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drSelMLot[0]["ProductNo"], defString, false))) + { + + // 取得欲變更的產品單位 + string strUnitNo = ""; + strSQL = "Select * From tblPRDProductBasis Where ProductNo ='" + + drSelMLot[0]["ProductNo"] + "' And ProductVersion='" + drSelMLot[0]["ProductVersion"] + "' "; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strUnitNo = drTemp["UnitNo"].ToString(); + } + drTemp.Close(); + + + // 變更產品 + objLot.ChgProductOperation(MLotNo, UserNo, MOrgProductNo, MOrgProductVersion, Convert.ToString(drSelMLot[0]["ProductNo"]), Convert.ToString(drSelMLot[0]["ProductVersion"]), strUnitNo, + CollectionSQL, RefLotNo: MLotNo); + // ===生產批歷程,新增boolean,判斷母批是否有改產品 + blnChgProduct = true; + // B. 更新Temp Attrib Cont Attrib及Log_Report資料 (若在站中intOPStatus = 1) + // 取得此生產批於此作業站的ECNNo + // 2019/06/04 Edison母批換品號時的OPECN及Temp Attrib Cont Attrib, Log_Report資料 + if (blnIsIC_PKG && blnECN) + { + if (intOPStatus == 1) + { + strSQL = "Select ECNNo_OP From tblWIPLotOPECNRecord Where LotNo = '" + MLotNo + "' And OPNo = '" + OPNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strECNNo = drTemp["ECNNo_OP"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200003", "[%OP%] [%ECNNo%]"); + } + drTemp.Close(); + + + strSQL = "Delete From tblWIPTemp_Attrib Where LotNo = '" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + + strSQL = "Delete From tblWIPCont_Attrib Where LogGroupSerial = '" + MLogGroupSerial + "'"; + CollectionSQL.Add(strSQL); + + strSQL = "Select * From tblPRDOPAttrib Where SerialNo = '" + SerialNo + "' And (ECNNo = '" + strECNNo + "' Or ECNNo = 'N/A')"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // daTemp.SelectCommand = cmmTemp + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "OPAttrib", cnnTemp); + + // drTemp.Close() + + foreach (DataRow drAttrib in dsTemp.Tables["OPAttrib"].Rows) + { + // 變更DefaultValue + if (drAttrib["AttribValue"] is DBNull) + { + AttribValue = ""; + } + else + { + switch (drAttrib["AttribValue"].ToString().ToUpper()) + { + case "NOW": + { + AttribValue = iMES_Format_Date(DateTime.Now, strDataBaseType); + break; + } + + case "LOT CURQTY": + { + AttribValue = decCurQty.ToString(); + break; + } + + default: + { + // 2010/11/25 YF, 預設值若是#GetSpec, 故需傳入ProductNo + AttribValue = Convert.ToString(objLot.ChangeDefaultValue(drAttrib["AttribValue"].ToString(), MLotNo, ProductNo: drSelMLot[0]["ProductNo"].ToString())); + break; + } + } + } + + // Temp + // 2016/01/27 YF, 加入OrgAttribValue, 將AttribNo保留在OrgAttribValue, 在挑選設備時可判斷#GetEQPRecipe + strSQL = "Insert into tblWIPTemp_Attrib(LotNo, AttribType, EquipmentType, AttribNo, AttribSource, AttribPhase, " + " AttribSequence, AttribValue, QCItemNo, OrgAttribValue, SaveToLotPropertyNo)" + " Values('" + MLotNo + "', 0,'" + + drAttrib["EquipmentType"] + "','" + drAttrib["AttribNo"] + "'," + drAttrib["AttribSource"] + "," + drAttrib["AttribPhase"] + + "," + drAttrib["AttribSequence"] + ",'" + AttribValue + "','" + drAttrib["QCItemNo"] + "','" + drAttrib["AttribValue"] + "'"; + if (drAttrib["SaveToLotPropertyNo"] is DBNull) + { + strSQL = strSQL + ",'N/A')"; + } + else + { + strSQL = strSQL + ",'" + drAttrib["SaveToLotPropertyNo"] + "')".ToString(); + } + CollectionSQL.Add(strSQL); + + // Content + strSQL = "Insert into tblWIPCont_Attrib(LotSerial,EquipmentType,AttribNo,AttribValue,LogGroupSerial)" + " Values('" + MNewLotSerial + "','" + + drAttrib["EquipmentType"] + "','" + drAttrib["AttribNo"] + "','" + AttribValue + "','" + OPNo + "')"; + CollectionSQL.Add(strSQL); + + // Lot Property(因之後都以Update的方式更新,故在此先將 TableType=0 的Property,Insert至tblWIPLotProperty) + if (!(drAttrib["SaveToLotPropertyNo"] is DBNull)) + { + // 檢查是否已新增過 + if (aryLotProperty.IndexOf(Strings.UCase(drAttrib["SaveToLotPropertyNo"].ToString())) < 0) + { + strSQL = "Select PropertyNo From tblSYSLotPropertyBasis " + " Where PropertyNo = '" + + drAttrib["SaveToLotPropertyNo"] + "'" + " And TableType = 0 " + " And PropertyNo Not In(Select PropertyNo From tblWIPLotProperty " + + " Where LotNo = '" + MLotNo + "'" + " And PropertyNo ='" + drAttrib["SaveToLotPropertyNo"] + "')"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) // 沒有存在,故須Insert + { + // 因PropertyNo允許大小寫資料,故不可任意轉換,會無法取得資料 + strSQL = "Insert into tblWIPLotProperty (LotNo, PropertyNo, PropertyValue)" + " Values('" + MLotNo + "','" + + drTemp["PropertyNo"] + "','')"; + CollectionSQL.Add(strSQL); + aryLotProperty.Add(Strings.UCase(drAttrib["SaveToLotPropertyNo"].ToString())); + } + drTemp.Close(); + + } + } + } + + // 更新tblWIPLotLog_Report的ECNNo + strSQL = "Update tblWIPLotLog_Report Set ECNNO_OP = '" + strECNNo + "'" + " Where LotNo='" + MLotNo + "' " + " And OPNo='" + OPNo + "'" + " And LoggroupSerial='" + MLogGroupSerial + "'"; + CollectionSQL.Add(strSQL); + } + } + } + + drSel = dtSplitLot.Select("SplitLotNo ='" + MLotNo + "'"); + // 2020/11/9,Ning,0081028: [6.0.5]分批處理,產品變更/流程變更調整, 母批跳流程 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drSel[0]["Action"], 1, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drSel[0]["Action"], 2, false))) + { + objLot.SetLotStateToNextOP(LotStamp, MLotNo, Convert.ToString(drSel[0]["NodeID"]), EventUserNo: UserNo, EventDescription: EventDescription, colSQL: CollectionSQL, RefLotNo: MLotNo, NewProductNo: Convert.ToString(drSel[0]["ProductNo"]), NewProductVersion: Convert.ToString(drSel[0]["ProductVersion"])); + if (blnIsIC_PKG && blnECN && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drSel[0]["Action"], 2, false))) + { + + var dsECN = new DataSet(); + var dtECN = new DataTable(); + dtECN.Columns.Add(new DataColumn("LotNo", Type.GetType("System.String"))); + dtECN.Columns.Add(new DataColumn("OrgLotNo", Type.GetType("System.String"))); + dtECN.Columns.Add(new DataColumn("CustomerLotNo", Type.GetType("System.String"))); + dtECN.Columns.Add(new DataColumn("MONo", Type.GetType("System.String"))); + + drAdd = dtECN.NewRow(); + drAdd["LotNo"] = MLotNo; + drAdd["OrgLotNo"] = dsTemp.Tables["LotState"].Rows[0]["OrgLotNo"].ToString(); + drAdd["CustomerLotNo"] = dsTemp.Tables["LotState"].Rows[0]["CustomerLotNo"].ToString(); + drAdd["MONo"] = dsTemp.Tables["LotState"].Rows[0]["MONo"].ToString(); + dtECN.Rows.Add(drAdd); + + // 依NodeID取得ProcessNo, ProcessVersion, NodeNo + strSQL = "Select ProcessNo, ProcessVersion, NodeNo From tblPRSNodeBasis Where NodeID = '" + + drSel[0]["NodeID"] + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + ProcessNo = drTemp["ProcessNo"].ToString(); + ProcessVersion = drTemp["ProcessVersion"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200003", "NodeBasis of NodeID:" + + drSel[0]["NodeID"] + " is not exist!"); + } + drTemp.Close(); + + + // 取得流程各站的ECNNo_OP + dsECN = objLot.ShowECNOPData(drSel[0]["ProductNo"].ToString(), drSel[0]["ProductVersion"].ToString(), dtECN, ProcessNo, ProcessVersion); + + // 先刪 + strSQL = "Delete From TBLWIPLOTOPECNRECORD where LotNo='" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + + foreach (DataRow drECN in dsECN.Tables[0].Rows) + { + strSQL = "Insert into TBLWIPLotOPECNRecord(LotNo,OPNo,ECNNo_OP,Creator,CreateDate,ECNType,AreaNo) " + "Values('" + MLotNo + "','" + drECN["OPNo"].ToString() + "','" + drECN["ECNNo"].ToString() + "','" + UserNo + "', " + " To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + drECN["ECNType"].ToString() + "','" + drECN["AreaNo"].ToString() + "')"; + CollectionSQL.Add(strSQL); + } + + if (dsECN != null) + dsECN = null; + } + } + // =====94661,生產批歷程 Phase II LotState變更紀錄 + var objChangeData = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData.clsChangeLot(); + objChangeData.SplitType = SplitType; + objChangeData.FromLotNo = MLotNo; + objChangeData.FromLotSerial = MLotSerial; + objChangeData.ToLotNo = MLotNo; + objChangeData.ToLotSerial = MNewLotSerial; + var clsLotData = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData(); + clsLotData.ProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(); + clsLotData.ProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(); + clsLotData.CurQty = MCurQty; + clsLotData.CurUnitNo = dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"].ToString(); + clsLotData.SysQty = SysQty; + clsLotData.SysUnitNo = dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"].ToString(); + if (drSel[0]["OPNo"].ToString() != dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString() || drSel[0]["NodeId"].ToString() != dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString()) + { + clsLotData.OPNo = drSel[0]["OPNo"].ToString(); + clsLotData.NodeId = drSel[0]["NodeID"].ToString(); + } + else + { + clsLotData.OPNo = dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString(); + clsLotData.NodeId = dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString(); + } + objLotLog.funCreateSQL(clsLotData, ChangeLotData: objChangeData, LotNo: MLotNo, LotSerial: MNewLotSerial, LogGroupSerial: MLogGroupSerial, SysActiveId: 4, ReferenceLotNo: MLotNo); + // === + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III 改產品 + if (blnChgProduct == true) + { + var objChangeProduct = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData.clsChangeProduct(); + var clsLotData2 = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData(); + objChangeProduct.FromProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(); + objChangeProduct.FromProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(); + objChangeProduct.ToProductNo = drSelMLot[0]["ProductNo"].ToString(); + objChangeProduct.ToProductVersion = drSelMLot[0]["ProductVersion"].ToString(); + objChangeProduct.ChangePRDType = 4; + clsLotData2.ProductNo = drSelMLot[0]["ProductNo"].ToString(); + clsLotData2.ProductVersion = drSelMLot[0]["ProductVersion"].ToString(); + clsLotData2.CurQty = MCurQty; + clsLotData2.CurUnitNo = dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"].ToString(); + clsLotData2.SysQty = SysQty; + clsLotData2.SysUnitNo = dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"].ToString(); + if (drSelMLot[0]["OPNo"].ToString() != dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString() || drSelMLot[0]["NodeId"].ToString() != dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString()) + { + clsLotData2.OPNo = drSelMLot[0]["OPNo"].ToString(); + clsLotData2.NodeId = drSelMLot[0]["NodeID"].ToString(); + } + else + { + clsLotData2.OPNo = dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString(); + clsLotData2.NodeId = dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString(); + } + objLotLog.funCreateSQL(clsLotData2, ChangeProductData: objChangeProduct, LotNo: MLotNo, LotSerial: MNewLotSerial, LogGroupSerial: dsTemp.Tables["LotState"].Rows[0]["LogGroupSerial"].ToString(), SysActiveId: 6, ReferenceLotNo: MLotNo); + blnChgProduct = false; + } + // === + // 派工處理,子批有繼承母批批號,不須做任何處理 + // 母批已處理完成,將母批移除 + drSel = dtSplitLot.Select("SplitLotNo ='" + MLotNo + "'"); + dtSplitLot.Rows.Remove(drSel[0]); + dtSplitLot.AcceptChanges(); + + if (intOPStatus == 1) // 站中,產生一筆對應的LotLog + { + strSQL = "Insert into tblWIPLotLog (LogGroupSerial,LotNo,LotSerial,OPNo,NodeID,BaseLotNo,StartTime,EndTime,Status,AreaNo,ModuleNo,ModuleVersion,OPGroupNo) " + " Values ('" + + dsTemp.Tables["LotState"].Rows[0]["LogGroupSerial"] + "','" + MLotNo + "','" + MNewLotSerial + "','" + dsTemp.Tables["LotState"].Rows[0]["OPNo"] + + "','" + dsTemp.Tables["LotState"].Rows[0]["NodeId"] + "','" + dsTemp.Tables["LotState"].Rows[0]["BaseLotNo"] + "'," + "To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + + "','YYYY/MM/DD HH24:MI:SS')," + "To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'), 0, '" + + dsTemp.Tables["LotState"].Rows[0]["AreaNo"] + "','" + dsTemp.Tables["LotState"].Rows[0]["ModuleNo"] + "','" + dsTemp.Tables["LotState"].Rows[0]["ModuleVersion"] + + "', '" + dsTemp.Tables["LotState"].Rows[0]["OPGroupNo"] + "')"; + CollectionSQL.Add(strSQL); + } + + if (blnWIPInv) + { + // 更新母批分批數量 + strSQL = "Update tblINVWIPInventory_Semi Set QTY = " + MCurQty; + strSQL += " Where InventoryNo = '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INVENTORYNO"].ToString() + "'"; + strSQL += " And LotNo = '" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + + // 2019/04/25 Lena, 在製品庫分批且生產批狀態已為99結批,不建立還原點 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dsTemp.Tables["LotState"].Rows[0]["LotState"], 99, false))) + { + // Undo + strSQL = "Update tblINVWIPInventory_Semi Set QTY = " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["QTY"].ToString(); + strSQL += " Where InventoryNo = '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INVENTORYNO"].ToString() + "'"; + strSQL += " And LotNo = '" + MLotNo + "'"; + Collection argcolSQL_Rows1 = null; + objReverse.AddReverseUpdateContent(ref MNewLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows1); + } + } + } + + // 併回,在併回處理未刪除. + + // 多人加工不需做任何處理. + else + { + decimal decFinalFailQty = defInteger; + + if (intOPStatus == 1) + { + // 不要ReleaseEQP,子批仍在使用. + decimal FinalGoodQtyTmp = defInteger, FinalFailQtyTmp = defInteger; + objLot.EndOP(ref FinalGoodQtyTmp, ref decFinalFailQty, MLotNo, MNewLotSerial, datEventTime, CollectionSQL, UserNo, EventDescription: EventDescription, CalculateEMP: false); + + // 2011/11/07 YF, 因母批在站中, 且不保留母批, EndOP也未ReleaseEQP, 故另外計算母批人時機時*********************************** + // Call SHR_CalculateResource(MLotNo, MLogGroupSerial, MLotSerial, MNewLotSerial, UserNo, datEventTime, cnnTemp, CollectionSQL, , dsTemp.Tables("LotState").Rows(0)("CurQty")) + + // 2017/12/01,Sammi.人時AutoRun平攤需求,將上工下工資料,整合入舊的多人加工機制. + // 2018/04/24,Sammi.分批時,結算人時允許無上下工資料. + using (var obj = new kcWIP.clsOperatorState()) + { + var locCollectionSQL_Rows = new Collection(); + obj.SHR_CO_EMP(ref cnnTemp, ref CollectionSQL, ref locCollectionSQL_Rows, ref objReverse, UserNo, datEventTime, datEventTime, MLotNo, Convert.ToDecimal(dsTemp.Tables["LotState"].Rows[0]["CurQty"]), NewLotSerial: MNewLotSerial, EMPAllowPass: true); + } + + objLot.SHR_COEquipment_N_Release(ref cnnTemp, ref CollectionSQL, MLotNo, MLogGroupSerial, MNewLotSerial, UserNo, datEventTime, InputQty: Convert.ToDecimal(dsTemp.Tables["LotState"].Rows[0]["CurQty"])); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dsTemp.Tables["LotState"].Rows[0]["OPReference"], 1, false))) + { + // 不正常結束,CompleteFlag=0. + objLot.EndModule(MLotNo, MNewLotSerial, datEventTime, CollectionSQL, EventUserNo: UserNo, EventDescription: EventDescription, CompleteFlag: 0, UnUpdateFailQty: decFinalFailQty); + } + + // 2007/07/13,sammi.tblWIPLotBasis vs tblWIPLotState的對應方式. + // objDBCom.Split1To1,True:1對1(要檢查母批LotBasis是否要結批),False:1對多(不用檢查). + objLot.CloseLot(MLotNo, 100, CollectionSQL, objDBCom.Split1To1, MNewLotSerial, EventTime: datEventTime, EventUserNo: UserNo, EventDescription: EventDescription); + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III closeLot + objLotLog.funCreateSQL(new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData() + { ProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(), ProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(), CurQty = Convert.ToDecimal(dsTemp.Tables["LotState"].Rows[0]["CurQty"]), CurUnitNo = Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"]), SysQty = Convert.ToDecimal(dsTemp.Tables["LotState"].Rows[0]["CurQty"]), SysUnitNo = Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"]), OPNo = Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["OPNo"]), NodeId = Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["NodeId"]), CloseType = 1 }, LotNo: MLotNo, LotSerial: MNewLotSerial, SysActiveId: 17, ReferenceLotNo: MLotNo); + // === + // 派工處理,找出母批派工之設備 + strSQL = "Select EquipmentNo From tblEMSDispatchState Where LotNo = '" + MLotNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) // 是 + { + // 將母批的派工資料拿掉,並重新取出Order + objLot.UpdEQPDispatch(Convert.ToString(drTemp["EquipmentNo"]), MLotNo, MNewLotSerial, CollectionSQL); + } + drTemp.Close(); + + } + + // 6.子批---------------------------------------------------------------------------------------------------------------- + string NewBaseLotNo = ""; + decimal decSLotSysQty = defInteger; + + var loopTo1 = dtSplitLot.Rows.Count - 1; + for (i = 0; i <= loopTo1; i++) + { + SLotNo = dtSplitLot.Rows[i]["SplitLotNo"].ToString().ToUpper(); + SLotSerial = objLot.InitLotSerial(SLotNo); + + // 2019/04/25 Lena, 在製品庫分批且生產批狀態已為99結批,不建立還原點 + if (!blnWIPInv || Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dsTemp.Tables["LotState"].Rows[0]["LotState"], 99, false))) + { + var tmp5 = dsTemp.Tables["LotState"].Rows[0]; + string argOPNo1 = tmp5["OPNo"].ToString(); + udReverse.clsReverse.ReverseType revTypeTmp = udReverse.clsReverse.ReverseType.Split_To; + SReverseId = objReverse.NewReverseID(ref SLotNo, ref revTypeTmp, ref SLotSerial, ref argOPNo1, ref CollectionSQL, Description: "BR Manual Split(To Lot)", Creator: UserNo, CreateDate: datEventTime); + tmp5["OPNo"] = argOPNo1; + } + + + if (blnHaveSysQty) + { + decSLotSysQty = Convert.ToDecimal(dtSplitLot.Rows[i]["SplitSysQty"]); + } + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III + string NewLotGroupSerial = ""; + if (!string.IsNullOrEmpty(NewLotGroupSerial)) + { + NewLotGroupSerial = null; + } + bool blnChgProduct = false; + // === + int iAction = -1; + if (!int.TryParse(dtSplitLot.Rows[i]["Action"].ToString(), out iAction)) + iAction = -1; + switch (iAction) + { + case 0: // Go + { + if (intOPStatus == 1) + { + if (SplitType == 1) // BR分批 + { + if (LinkName == "HOLD") + { + var tmp6 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty = Convert.ToDecimal(tmp6["SplitLotQty"]); + var tmp7 = dtSplitLot.Rows[i]; + int argNewReturnType = Conversions.ToInteger(tmp7["ReturnType"]); + int argNewStatus = 3; + bool argTriggerOP = true; + string argLinkName = "HOLD"; + var tmp8 = dsTemp.Tables; + var argdtLotState1 = tmp8["LotState"]; + var tmp9 = dsTemp.Tables; + var argdtLotProperty1 = tmp9["LotProperty"]; + var tmp10 = dsTemp.Tables; + var argdtLotProcess = tmp10["LotProcess"]; + var tmp11 = dsTemp.Tables; + var argdtOPGroupState = tmp11["OPGroupState"]; + var tmp12 = dsTemp.Tables; + var argdtTempLotAttrib1 = tmp12["TempLotAttrib"]; + var tmp13 = dsTemp.Tables; + var argdtTempMaterial = tmp13["TempMaterial"]; + var tmp14 = dsTemp.Tables; + var argdtTempEquipment = tmp14["TempEquipment"]; + var tmp15 = dsTemp.Tables; + var argdtTempQCItem = tmp15["TempQCItem"]; + var tmp16 = dsTemp.Tables; + var argdtLotECNAttrib1 = tmp16["LotECNAttrib"]; + var tmp17 = dtSplitLot.Rows[i]; + string argNewProductNo = tmp17["ProductNo"].ToString(); + var tmp18 = dtSplitLot.Rows[i]; + string argNewProductVersion = tmp18["ProductVersion"].ToString(); + int argGoStatus = 4; + decimal argNewLotSysQtyLog = -999m; + + bool NewLotBasisTmp = false; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref argGoStatus, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty, CollectionSQL, SerialNo, argNewReturnType, NewStatus: argNewStatus, TriggerOP: argTriggerOP, LinkName: argLinkName, dtLotState: argdtLotState1, dtLotProperty: argdtLotProperty1, dtLotProcess: argdtLotProcess, dtOPGroupState: argdtOPGroupState, dtTempLotAttrib: argdtTempLotAttrib1, dtTempMaterial: argdtTempMaterial, dtTempEquipment: argdtTempEquipment, dtTempQCItem: argdtTempQCItem, dtLotECNAttrib: argdtLotECNAttrib1, NewProductNo: argNewProductNo, NewProductVersion: argNewProductVersion, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp6["SplitLotQty"] = argNewLotCurQty; + tmp7["ReturnType"] = argNewReturnType; + tmp17["ProductNo"] = argNewProductNo; + tmp18["ProductVersion"] = argNewProductVersion; + } + + else if (LinkName == "WAIT") + { + var tmp33 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty2 = Convert.ToDecimal(tmp33["SplitLotQty"]); + var tmp34 = dtSplitLot.Rows[i]; + int argNewReturnType2 = Conversions.ToInteger(tmp34["ReturnType"]); + int argNewStatus2 = 2; + bool argTriggerOP2 = true; + string argLinkName1 = "WAIT"; + var tmp35 = dsTemp.Tables; + var argdtLotState3 = tmp35["LotState"]; + var tmp36 = dsTemp.Tables; + var argdtLotProperty3 = tmp36["LotProperty"]; + var tmp37 = dsTemp.Tables; + var argdtLotProcess2 = tmp37["LotProcess"]; + var tmp38 = dsTemp.Tables; + var argdtOPGroupState2 = tmp38["OPGroupState"]; + var tmp39 = dsTemp.Tables; + var argdtTempLotAttrib3 = tmp39["TempLotAttrib"]; + var tmp40 = dsTemp.Tables; + var argdtTempMaterial2 = tmp40["TempMaterial"]; + var tmp41 = dsTemp.Tables; + var argdtTempEquipment2 = tmp41["TempEquipment"]; + var tmp42 = dsTemp.Tables; + var argdtTempQCItem2 = tmp42["TempQCItem"]; + var tmp43 = dsTemp.Tables; + var argdtLotECNAttrib3 = tmp43["LotECNAttrib"]; + var tmp44 = dtSplitLot.Rows[i]; + string argNewProductNo2 = tmp44["ProductNo"].ToString(); + var tmp45 = dtSplitLot.Rows[i]; + string argNewProductVersion2 = tmp45["ProductVersion"].ToString(); + int argGoStatus1 = 4; + decimal argNewLotSysQtyLog2 = -999m; + + bool NewLotBasisTmp = false; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref argGoStatus1, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog2, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty2, CollectionSQL, SerialNo, argNewReturnType2, NewStatus: argNewStatus2, TriggerOP: argTriggerOP2, LinkName: argLinkName1, dtLotState: argdtLotState3, dtLotProperty: argdtLotProperty3, dtLotProcess: argdtLotProcess2, dtOPGroupState: argdtOPGroupState2, dtTempLotAttrib: argdtTempLotAttrib3, dtTempMaterial: argdtTempMaterial2, dtTempEquipment: argdtTempEquipment2, dtTempQCItem: argdtTempQCItem2, dtLotECNAttrib: argdtLotECNAttrib3, NewProductNo: argNewProductNo2, NewProductVersion: argNewProductVersion2, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp33["SplitLotQty"] = argNewLotCurQty2; + tmp34["ReturnType"] = argNewReturnType2; + tmp44["ProductNo"] = argNewProductNo2; + tmp45["ProductVersion"] = argNewProductVersion2; + } + else + { + // Status(4:代表成功完成BR,紀錄LinkName若TransferLot失敗可以重新再執行TransferLot) + var tmp19 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty1 = Convert.ToDecimal(tmp19["SplitLotQty"]); + var tmp20 = dtSplitLot.Rows[i]; + int argNewReturnType1 = Conversions.ToInteger(tmp20["ReturnType"]); + int argNewStatus1 = 4; + bool argTriggerOP1 = true; + var tmp21 = dsTemp.Tables; + var argdtLotState2 = tmp21["LotState"]; + var tmp22 = dsTemp.Tables; + var argdtLotProperty2 = tmp22["LotProperty"]; + var tmp23 = dsTemp.Tables; + var argdtLotProcess1 = tmp23["LotProcess"]; + var tmp24 = dsTemp.Tables; + var argdtOPGroupState1 = tmp24["OPGroupState"]; + var tmp25 = dsTemp.Tables; + var argdtTempLotAttrib2 = tmp25["TempLotAttrib"]; + var tmp26 = dsTemp.Tables; + var argdtTempMaterial1 = tmp26["TempMaterial"]; + var tmp27 = dsTemp.Tables; + var argdtTempEquipment1 = tmp27["TempEquipment"]; + var tmp28 = dsTemp.Tables; + var argdtTempQCItem1 = tmp28["TempQCItem"]; + var tmp29 = dsTemp.Tables; + var argdtLotECNAttrib2 = tmp29["LotECNAttrib"]; + var tmp30 = dtSplitLot.Rows[i]; + string argNewProductNo1 = tmp30["ProductNo"].ToString(); + var tmp31 = dtSplitLot.Rows[i]; + string argNewProductVersion1 = tmp31["ProductVersion"].ToString(); + var tmp32 = dsTemp.Tables; + var argdtLotLoginState = tmp32["LotLoginState"]; + decimal argNewLotSysQtyLog1 = -999m; + + bool NewLotBasisTmp = false; + int GoStatusTmp = defInteger; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref GoStatusTmp, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog1, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty1, CollectionSQL, SerialNo, argNewReturnType1, NewStatus: argNewStatus1, TriggerOP: argTriggerOP1, LinkName: LinkName, dtLotState: argdtLotState2, dtLotProperty: argdtLotProperty2, dtLotProcess: argdtLotProcess1, dtOPGroupState: argdtOPGroupState1, dtTempLotAttrib: argdtTempLotAttrib2, dtTempMaterial: argdtTempMaterial1, dtTempEquipment: argdtTempEquipment1, dtTempQCItem: argdtTempQCItem1, dtLotECNAttrib: argdtLotECNAttrib2, NewProductNo: argNewProductNo1, NewProductVersion: argNewProductVersion1, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, dtLotLoginState: argdtLotLoginState, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp19["SplitLotQty"] = argNewLotCurQty1; + tmp20["ReturnType"] = argNewReturnType1; + tmp30["ProductNo"] = argNewProductNo1; + tmp31["ProductVersion"] = argNewProductVersion1; + } + } + + else // 站中手動分批 + { + // 因目前狀態可能是complete,故須保留LinkName. + // 2020/02/12 Eric Mantis:0067304(分批未繼承ECN) 補上傳入ECN繼承參數 + var tmp46 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty3 = Convert.ToDecimal(tmp46["SplitLotQty"]); + var tmp47 = dtSplitLot.Rows[i]; + int argNewReturnType3 = Conversions.ToInteger(tmp47["ReturnType"]); + bool argTriggerOP3 = true; + var tmp48 = dsTemp.Tables; + var argdtLotState4 = tmp48["LotState"]; + var tmp49 = dsTemp.Tables; + var argdtLotProperty4 = tmp49["LotProperty"]; + var tmp50 = dsTemp.Tables; + var argdtLotProcess3 = tmp50["LotProcess"]; + var tmp51 = dsTemp.Tables; + var argdtOPGroupState3 = tmp51["OPGroupState"]; + var tmp52 = dsTemp.Tables; + var argdtTempLotAttrib4 = tmp52["TempLotAttrib"]; + var tmp53 = dsTemp.Tables; + var argdtTempMaterial3 = tmp53["TempMaterial"]; + var tmp54 = dsTemp.Tables; + var argdtTempEquipment3 = tmp54["TempEquipment"]; + var tmp55 = dsTemp.Tables; + var argdtTempQCItem3 = tmp55["TempQCItem"]; + var tmp56 = dsTemp.Tables; + var argdtLotECNAttrib4 = tmp56["LotECNAttrib"]; + var tmp57 = dtSplitLot.Rows[i]; + string argNewProductNo3 = tmp57["ProductNo"].ToString(); + var tmp58 = dtSplitLot.Rows[i]; + string argNewProductVersion3 = tmp58["ProductVersion"].ToString(); + var tmp59 = dsTemp.Tables; + var argdtLotLoginState1 = tmp59["LotLoginState"]; + decimal argNewLotSysQtyLog3 = -999m; + + bool NewLotBasisTmp = false; + int GoStatusTmp = defInteger; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref GoStatusTmp, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog3, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty3, CollectionSQL, SerialNo, argNewReturnType3, TriggerOP: argTriggerOP3, LinkName: dsTemp.Tables["LotState"].Rows[0]["LinkName"].ToString(), + dtLotState: argdtLotState4, dtLotProperty: argdtLotProperty4, dtLotProcess: argdtLotProcess3, dtOPGroupState: argdtOPGroupState3, dtTempLotAttrib: argdtTempLotAttrib4, + dtTempMaterial: argdtTempMaterial3, dtTempEquipment: argdtTempEquipment3, dtTempQCItem: argdtTempQCItem3, + dtLotECNAttrib: argdtLotECNAttrib4, NewProductNo: argNewProductNo3, NewProductVersion: argNewProductVersion3, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, dtLotLoginState: argdtLotLoginState1, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp46["SplitLotQty"] = argNewLotCurQty3; + tmp47["ReturnType"] = argNewReturnType3; + tmp57["ProductNo"] = argNewProductNo3; + tmp58["ProductVersion"] = argNewProductVersion3; + } + } + + else // 站間手動分批 + { + // 因可能是臨時外包分批,故LinkName要繼承. + // 2020/02/12 Eric Mantis:0067304(分批未繼承ECN) 補上傳入ECN繼承參數 + var tmp60 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty4 = Convert.ToDecimal(tmp60["SplitLotQty"]); + var tmp61 = dtSplitLot.Rows[i]; + int argNewReturnType4 = Conversions.ToInteger(tmp61["ReturnType"]); + bool argTriggerOP4 = false; + string argLinkName2 = dsTemp.Tables["LotState"].Rows[0]["LinkName"].ToString(); + var tmp62 = dsTemp.Tables; + var argdtLotState5 = tmp62["LotState"]; + var tmp63 = dsTemp.Tables; + var argdtLotProperty5 = tmp63["LotProperty"]; + var tmp64 = dsTemp.Tables; + var argdtLotProcess4 = tmp64["LotProcess"]; + var tmp65 = dsTemp.Tables; + var argdtOPGroupState4 = tmp65["OPGroupState"]; + var tmp66 = dsTemp.Tables; + var argdtLotECNAttrib5 = tmp66["LotECNAttrib"]; + var tmp67 = dtSplitLot.Rows[i]; + string argNewProductNo4 = tmp67["ProductNo"].ToString(); + var tmp68 = dtSplitLot.Rows[i]; + string argNewProductVersion4 = tmp68["ProductVersion"].ToString(); + decimal argNewLotSysQtyLog4 = -999m; + + bool NewLotBasisTmp = false; + int GoStatusTmp = defInteger; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref GoStatusTmp, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog4, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty4, CollectionSQL, NewReturnType: argNewReturnType4, TriggerOP: argTriggerOP4, LinkName: argLinkName2, dtLotState: argdtLotState5, dtLotProperty: argdtLotProperty5, dtLotProcess: argdtLotProcess4, dtOPGroupState: argdtOPGroupState4, dtLotECNAttrib: argdtLotECNAttrib5, NewProductNo: argNewProductNo4, NewProductVersion: argNewProductVersion4, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp60["SplitLotQty"] = argNewLotCurQty4; + tmp61["ReturnType"] = argNewReturnType4; + tmp67["ProductNo"] = argNewProductNo4; + tmp68["ProductVersion"] = argNewProductVersion4; + } + + + // 檢查是否為倉庫分批 + if (blnWIPInv) + { + // 目前規則一批只能出現在一個庫房 + if (dsTemp.Tables["WIPInv_RefLot"] != null && dsTemp.Tables["WIPInv_RefLot"].Rows.Count == 1) + { + + // 將資訊複製給子批 + strSQL = "INSERT INTO tblINVWIPInventory_Semi (INVENTORYNO,PRODUCTNO,LOTNO, "; + strSQL += "UNITNO,QTY,INPUTDATE,BASELOTNO,BOUGHTEN,BOOKINGFLAG,PRODUCTVERSION) "; + strSQL += " VALUES ('" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INVENTORYNO"].ToString() + "', "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["PRODUCTNO"].ToString() + "', "; + strSQL += " '" + SLotNo + "', "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["UNITNO"].ToString() + "', "; + strSQL = strSQL + " " + dtSplitLot.Rows[i]["SplitLotQty"] + ", ".ToString(); + strSQL += " TO_DATE('" + Strings.Format(dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INPUTDATE"], "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'), "; + strSQL += " '" + NewBaseLotNo + "',"; + strSQL += " " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["BOUGHTEN"].ToString() + ", "; + strSQL += " " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["BOOKINGFLAG"].ToString() + ", "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["PRODUCTVERSION"].ToString() + "')"; + + SQLCommandTuning(DataBaseType, ref strSQL); + CollectionSQL.Add(strSQL); + + // 2019/04/25 Lena, 在製品庫分批且生產批狀態已為99結批,不建立還原點 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dsTemp.Tables["LotState"].Rows[0]["LotState"], 99, false))) + { + // Undo + strSQL = "Delete From tblINVWIPInventory_Semi Where InventoryNo = '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INVENTORYNO"].ToString() + "'" + " And LotNo = '" + SLotNo + "'"; + Collection argcolSQL_Rows2 = null; + objReverse.AddReverseUpdateContent(ref SLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows2); + } + + } + + } + break; + } + + + case 1: + case 2: // Jump OP,Jump Process '2020/02/12 Eric Mantis:0067304(分批未繼承ECN) 補上傳入ECN繼承參數 + { + var tmp69 = dtSplitLot.Rows[i]; + decimal argNewLotCurQty5 = Convert.ToDecimal(tmp69["SplitLotQty"]); + var tmp70 = dtSplitLot.Rows[i]; + int argNewReturnType5 = Conversions.ToInteger(tmp70["ReturnType"]); + var tmp71 = dtSplitLot.Rows[i]; + string argNewNodeId = tmp71["NodeID"].ToString(); + int argNewStatus3 = 0; + bool argTriggerOP5 = false; + var tmp72 = dsTemp.Tables; + var argdtLotState6 = tmp72["LotState"]; + var tmp73 = dsTemp.Tables; + var argdtLotProperty6 = tmp73["LotProperty"]; + var tmp74 = dsTemp.Tables; + var argdtLotProcess5 = tmp74["LotProcess"]; + var tmp75 = dsTemp.Tables; + var argdtOPGroupState5 = tmp75["OPGroupState"]; + var tmp76 = dsTemp.Tables; + var argdtLotECNAttrib6 = tmp76["LotECNAttrib"]; + var tmp77 = dtSplitLot.Rows[i]; + string argNewProductNo5 = tmp77["ProductNo"].ToString(); + var tmp78 = dtSplitLot.Rows[i]; + string argNewProductVersion5 = tmp78["ProductVersion"].ToString(); + decimal argNewLotSysQtyLog5 = -999m; + + bool NewLotBasisTmp = false; + int GoStatusTmp = defInteger; + DataTable dtContAccTmp = null; + objLot.NewLot_Split(ref NewLotBasisTmp, ref GoStatusTmp, ref NewLotGroupSerial, ref dtContAccTmp, ref NewBaseLotNo, ref argNewLotSysQtyLog5, + MLotNo, MNewLotSerial, SLotNo, ref SLotSerial, + argNewLotCurQty5, CollectionSQL, NewReturnType: argNewReturnType5, NewNodeId: argNewNodeId, NewStatus: argNewStatus3, TriggerOP: argTriggerOP5, dtLotState: argdtLotState6, dtLotProperty: argdtLotProperty6, dtLotProcess: argdtLotProcess5, dtOPGroupState: argdtOPGroupState5, dtLotECNAttrib: argdtLotECNAttrib6, NewProductNo: argNewProductNo5, NewProductVersion: argNewProductVersion5, + Creator: UserNo, datEventTime: datEventTime, NewLotSysQty: decSLotSysQty, SplitType: SplitType, blnIsIC_PKG: blnIsIC_PKG); + tmp69["SplitLotQty"] = argNewLotCurQty5; + tmp70["ReturnType"] = argNewReturnType5; + tmp71["NodeID"] = argNewNodeId; + tmp77["ProductNo"] = argNewProductNo5; + tmp78["ProductVersion"] = argNewProductVersion5; + break; + } + } + + + drAdd = dtSplitCont.NewRow(); + drAdd["ToLotNo"] = SLotNo; + drAdd["ToBaseLotNo"] = NewBaseLotNo; + drAdd["ToLotSerial"] = SLotSerial; + drAdd["ToReverseId"] = SReverseId; + drAdd["ToLotQty"] = dtSplitLot.Rows[i]["SplitLotQty"]; + if (!blnHaveFromLot && i == 0) + { + drAdd["MajorLot"] = 1; + } + else + { + drAdd["MajorLot"] = 0; + } + dtSplitCont.Rows.Add(drAdd); + + // 併回 + if (blnAutoMerge) + { + strSQL = "Insert into tblWIPAutoMerge(FromLotNo,ToLotNo) Values ('" + SLotNo + "','" + AutoMergeToLotNo + "')"; + CollectionSQL.Add(strSQL); + } + + // 2020/11/9 Ning 0081028: [6.0.5]分批處理,產品變更/流程變更調整 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dtSplitLot.Rows[i]["ProductNo"], dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(), false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dtSplitLot.Rows[i]["ProductVersion"], dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(), false))) + { + // 取得欲變更的產品單位 + string strUnitNo = ""; + strSQL = "Select * From tblPRDProductBasis Where ProductNo ='" + + dtSplitLot.Rows[i]["ProductNo"] + "' And ProductVersion='" + dtSplitLot.Rows[i]["ProductVersion"] + "' "; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + strUnitNo = drTemp["UnitNo"].ToString(); + } + drTemp.Close(); + + + // 變更產品 + objLot.ChgProductOperation_SplitLot(SLotNo, UserNo, Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["ProductNo"]), Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["ProductVersion"]), Convert.ToString(dtSplitLot.Rows[i]["ProductNo"]), Convert.ToString(dtSplitLot.Rows[i]["ProductVersion"]), strUnitNo, CollectionSQL, RefLotNo: MLotNo, colToINVLotNo: colToINVLotNo); + // 若是跳流程, 需以跳流程的流程為最終流程 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtSplitLot.Rows[i]["Action"], 1, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtSplitLot.Rows[i]["Action"], 2, false))) + { + objLot.SetLotStateToNextOP(LotStamp, SLotNo, Convert.ToString(dtSplitLot.Rows[i]["NodeID"]), EventUserNo: UserNo, EventDescription: EventDescription, colSQL: CollectionSQL, RefLotNo: MLotNo, NewProductNo: Convert.ToString(dtSplitLot.Rows[i]["ProductNo"]), NewProductVersion: Convert.ToString(dtSplitLot.Rows[i]["ProductVersion"])); + + if (blnIsIC_PKG && blnECN && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtSplitLot.Rows[i]["Action"], 2, false))) + { + + string ProcessNo, ProcessVersion; + var dsECN = new DataSet(); + var dtECN = new DataTable(); + dtECN.Columns.Add("LotNo", Type.GetType("System.String")); + dtECN.Columns.Add("OrgLotNo", Type.GetType("System.String")); + dtECN.Columns.Add("CustomerLotNo", Type.GetType("System.String")); + dtECN.Columns.Add("MONo", Type.GetType("System.String")); + + drAdd = dtECN.NewRow(); + drAdd["LotNo"] = SLotNo; + drAdd["OrgLotNo"] = dsTemp.Tables["LotState"].Rows[0]["OrgLotNo"].ToString(); + drAdd["CustomerLotNo"] = dsTemp.Tables["LotState"].Rows[0]["CustomerLotNo"].ToString(); + drAdd["MONo"] = dsTemp.Tables["LotState"].Rows[0]["MONo"].ToString(); + dtECN.Rows.Add(drAdd); + + // 依NodeID取得ProcessNo, ProcessVersion, NodeNo + strSQL = "Select ProcessNo, ProcessVersion, NodeNo From tblPRSNodeBasis Where NodeID = '" + + dtSplitLot.Rows[i]["NodeID"] + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + ProcessNo = drTemp["ProcessNo"].ToString(); + ProcessVersion = drTemp["ProcessVersion"].ToString(); + } + else + { + throw new iMESException.MESException("0000-200003", "NodeBasis of NodeID:" + + dtSplitLot.Rows[i]["NodeID"] + " is not exist!"); + } + drTemp.Close(); + + + // 取得流程各站的ECNNo_OP + dsECN = objLot.ShowECNOPData(dtSplitLot.Rows[i]["ProductNo"].ToString(), dtSplitLot.Rows[i]["ProductVersion"].ToString(), dtECN, ProcessNo, ProcessVersion); + + // 先刪 + strSQL = "Delete From TBLWIPLOTOPECNRECORD where LotNo='" + SLotNo + "'"; + CollectionSQL.Add(strSQL); + + foreach (DataRow drECN in dsECN.Tables[0].Rows) + { + strSQL = "Insert into TBLWIPLotOPECNRecord(LotNo,OPNo,ECNNo_OP,Creator,CreateDate,ECNType,AreaNo) " + "Values('" + SLotNo + "','" + drECN["OPNo"].ToString() + "','" + drECN["ECNNo"].ToString() + "','" + UserNo + "', " + " To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + drECN["ECNType"].ToString() + "','" + drECN["AreaNo"].ToString() + "')"; + CollectionSQL.Add(strSQL); + } + + if (dsECN != null) + dsECN = null; + } + } + blnChgProduct = true; + } + // =====94661,生產批歷程 Phase II 分批紀錄 + var objChangeData = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData.clsChangeLot(); + objChangeData.SplitType = SplitType; + objChangeData.FromLotNo = MLotNo; + objChangeData.FromLotSerial = MNewLotSerial; + objChangeData.ToLotNo = SLotNo; + objChangeData.ToLotSerial = SLotSerial; + var clsLotDataSplit = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData(); + clsLotDataSplit.ProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(); + clsLotDataSplit.ProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(); + clsLotDataSplit.CurQty = Convert.ToDecimal(dtSplitLot.Rows[i]["SplitLotQty"]); + clsLotDataSplit.CurUnitNo = dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"].ToString(); + clsLotDataSplit.SysQty = decSLotSysQty; + clsLotDataSplit.SysUnitNo = dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"].ToString(); + if (dtSplitLot.Rows[i]["OPNo"].ToString() != dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString() || dtSplitLot.Rows[i]["NodeId"].ToString() != dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString()) + { + clsLotDataSplit.OPNo = dtSplitLot.Rows[i]["OPNo"].ToString(); + clsLotDataSplit.NodeId = dtSplitLot.Rows[i]["NodeId"].ToString(); + } + else + { + clsLotDataSplit.OPNo = dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString(); + clsLotDataSplit.NodeId = dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString(); + } + clsLotDataSplit.LotStamp = 0; + objLotLog.funCreateSQL(clsLotDataSplit, ChangeLotData: objChangeData, LotNo: SLotNo, LotSerial: SLotSerial, LogGroupSerial: NewLotGroupSerial, SysActiveId: 4, ReferenceLotNo: MLotNo); + // === + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III 產品變更紀錄 + if (blnChgProduct == true) + { + var ChangeProduct = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData.clsChangeProduct(); + ChangeProduct.FromProductNo = dsTemp.Tables["LotState"].Rows[0]["ProductNo"].ToString(); + ChangeProduct.FromProductVersion = dsTemp.Tables["LotState"].Rows[0]["ProductVersion"].ToString(); + ChangeProduct.ToProductNo = dtSplitLot.Rows[i]["ProductNo"].ToString(); + ChangeProduct.ToProductVersion = dtSplitLot.Rows[i]["ProductVersion"].ToString(); + ChangeProduct.ChangePRDType = 4; + var clsLotData3 = new iMESWIPReleaseLogHandler.clsLotReleaseLogHandle.clsLotData(); + clsLotData3.ProductNo = dtSplitLot.Rows[i]["ProductNo"].ToString(); + clsLotData3.ProductVersion = dtSplitLot.Rows[i]["ProductVersion"].ToString(); + clsLotData3.CurQty = Convert.ToDecimal(dtSplitLot.Rows[i]["SplitLotQty"]); + clsLotData3.CurUnitNo = dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"].ToString(); + clsLotData3.SysQty = Convert.ToDecimal(dtSplitLot.Rows[i]["SplitLotQty"]); + clsLotData3.SysUnitNo = dsTemp.Tables["LotState"].Rows[0]["SysUnitNo"].ToString(); + clsLotData3.LotStamp = 0; + // === 2021/09/08 Troy mantis:94662 生產批下線後執行動作紀錄 phase III + if (dtSplitLot.Rows[i]["OPNo"].ToString() != dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString() || dtSplitLot.Rows[i]["NodeID"].ToString() != dsTemp.Tables["LotState"].Rows[0]["NodeID"].ToString()) + { + clsLotData3.OPNo = dtSplitLot.Rows[i]["OPNo"].ToString(); + clsLotData3.NodeId = dtSplitLot.Rows[i]["NodeId"].ToString(); + } + else + { + clsLotData3.OPNo = dsTemp.Tables["LotState"].Rows[0]["OPNo"].ToString(); + clsLotData3.NodeId = dsTemp.Tables["LotState"].Rows[0]["NodeId"].ToString(); + } + objLotLog.funCreateSQL(clsLotData3, ChangeProductData: ChangeProduct, LotNo: SLotNo, LotSerial: SLotSerial, LogGroupSerial: NewLotGroupSerial, SysActiveId: 6, ReferenceLotNo: MLotNo); + } + // === + } + + // 檢查是否刪除庫房母批 + if (blnWIPInv & !blnHaveFromLot) + { + if (dsTemp.Tables["WIPInv_RefLot"] != null && dsTemp.Tables["WIPInv_RefLot"].Rows.Count == 1) + { + + strSQL = "Delete From tblINVWIPInventory_Semi Where InventoryNo = '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["InventoryNo"].ToString() + "' And LotNo = '" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + + // 2019/04/25 Lena, 在製品庫分批且生產批狀態已為99結批,不建立還原點 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dsTemp.Tables["LotState"].Rows[0]["LotState"], 99, false))) + { + // Undo + strSQL = "INSERT INTO TBLINVWIPINVENTORY_SEMI (INVENTORYNO, PRODUCTNO,LOTNO,UNITNO,QTY,INPUTDATE, BASELOTNO,BOUGHTEN,BOOKINGFLAG,PRODUCTVERSION)"; + strSQL += " VALUES ('" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INVENTORYNO"].ToString() + "', "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["PRODUCTNO"].ToString() + "', "; + strSQL += " '" + MLotNo + "', "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["UNITNO"].ToString() + "', "; + strSQL += " " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["QTY"].ToString() + ", "; + strSQL += " TO_DATE('" + Strings.Format(dsTemp.Tables["WIPInv_RefLot"].Rows[0]["INPUTDATE"], "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'), "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["BASELOTNO"].ToString() + "', "; + strSQL += " " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["BOUGHTEN"].ToString() + ", "; + strSQL += " " + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["BOOKINGFLAG"].ToString() + ", "; + strSQL += " '" + dsTemp.Tables["WIPInv_RefLot"].Rows[0]["PRODUCTVERSION"].ToString() + "')"; + + SQLCommandTuning(DataBaseType, ref strSQL); + Collection argcolSQL_Rows3 = null; + objReverse.AddReverseUpdateContent(ref SLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows3); + } + + + } + } + + + // 7.分批紀錄 + if (blnWIPInv) + { + // 16 INVSplit(在製品庫分批) + objLot.SHR_Split_Inherit(ref cnnTemp, ref CollectionSQL, MLotNo, 16, Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["OPNo"]), UserNo, datEventTime, MLotNo, Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["BaseLotNo"]), MReverseId, MNewLotSerial, decSplitQty, dtSplitCont); + } + else + { + objLot.SHR_Split_Inherit(ref cnnTemp, ref CollectionSQL, MLotNo, SplitType, Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["OPNo"]), UserNo, datEventTime, MLotNo, Convert.ToString(dsTemp.Tables["LotState"].Rows[0]["BaseLotNo"]), MReverseId, MNewLotSerial, decSplitQty, dtSplitCont); + } + + + // 8.外包分批 + string OSNo = defString; + // 8.1是否外包且已出貨(確定)但未回貨 + strSQL = "Select A.OSNo, A.LotNo From tblWIPOSDetail A, tblWIPOSBasis B " + " Where A.LotNo='" + MLotNo + "' And A.Status=0" + " And A.OSNo=B.OSNo And B.Status Not In (0,11)"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + OSNo = drTemp["OSNo"].ToString(); + } + drTemp.Close(); + + + if (OSNo != defString) + { + string splitLotNo; + + // 各子批(可能也會包含原母批) + foreach (DataRow rowSplitLot in dtSplitLot.Rows) + { + splitLotNo = rowSplitLot["SplitLotNo"].ToString(); + if (splitLotNo != MLotNo) + { + // 避免PK重複,隨後處理母批 + strSQL = "Insert Into tblWIPOSDetail (OSNo, LotNo, RCVDate, Status, InputQty, InputUnitNo, GoodQty, ScrapQty, OtherQty, Description, UnitPrice)" + " Select OSNo, '" + splitLotNo + "' As LotNo, RCVDate, Status, " + + rowSplitLot["SplitLotQty"] + " As InputQty, InputUnitNo, GoodQty, ScrapQty, OtherQty, Description, UnitPrice" + " From tblWIPOSDetail Where OSNo='" + + OSNo + "' And LotNo='" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + // Reverse + // 不包含母批 + strSQL = "Delete From tblWIPOSDetail Where OSNo='" + OSNo + "' And LotNo='" + splitLotNo + "'"; + Collection argcolSQL_Rows4 = null; + objReverse.AddReverseUpdateContent(ref MNewLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows4); + } + } + + // dtSplitLot是否包含母批MLotNo + if (blnHaveFromLot) + { + // 包含母批 + if (MLotQtyAfterSplit != defInteger) + { + strSQL = "Update tblWIPOSDetail Set InputQty=" + MLotQtyAfterSplit + " Where OSNo='" + OSNo + "' And LotNo='" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + // Reverse + strSQL = "Update tblWIPOSDetail Set InputQty=" + decSplitQty + " Where OSNo='" + OSNo + "'" + " And LotNo='" + MLotNo + "'"; + Collection argcolSQL_Rows5 = null; + objReverse.AddReverseUpdateContent(ref MNewLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows5); + } + } + else + { + // 不包含母批 + strSQL = "Delete From tblWIPOSDetail Where OSNo='" + OSNo + "' And LotNo='" + MLotNo + "'"; + CollectionSQL.Add(strSQL); + // Reverse + strSQL = "Insert Into tblWIPOSDetail(OSNo,LotNo,Status,InputQty,InputUnitNo)" + " Values('" + OSNo + "','" + MLotNo + "',0," + decSplitQty + ",'" + + dsTemp.Tables["LotState"].Rows[0]["CurUnitNo"] + "')"; + Collection argcolSQL_Rows6 = null; + objReverse.AddReverseUpdateContent(ref MNewLotSerial, ref strSQL, CollectionSQL, colSQL_Rows: argcolSQL_Rows6); + } + + } + + // 9.檢查是否允許執行 + Collection argcolSQL_Rows7 = null; + objLot.ChkLotStamp(MLotNo, LotStamp, CollectionSQL, colSQL_Rows: argcolSQL_Rows7); + + // 11.呼叫執行SQL指令 + ExecuteSQLNoneQuery_UPD(DataBaseType, strConnectionString, CollectionSQL); + + // 若有需要入庫的生產批, 統一在此處理, 此時DB已實際產生子批的相關資料 + if (colToINVLotNo.Count > 0) + { + CollectionSQL.Clear(); + loopTo = colToINVLotNo.Count; + for (i = 1; i <= loopTo; i++) + { + objLot.SetLotStateToINV(colToINVLotNo[i].ToString(), CollectionSQL, EventUserNo: UserNo); + } + ExecuteSQLNoneQuery_UPD(DataBaseType, strConnectionString, CollectionSQL); + } + + // //Return success + // 因分批後原批號可能不在,故不繼續Transfer,傳出success,一律由使用者手動Transfer + BR_Manual_LotSplitRet = "success"; + } + + catch (Exception e1) + { + BR_Manual_LotSplitRet = "fail"; + throw; + } + finally + { + CloseConnection(cnnTemp); + dsTemp.Dispose(); + GC.Collect(); + + if (objLot != null) + { + objLot.Dispose(); + } + } + return BR_Manual_LotSplitRet; + + } + + #endregion + + #region "隐藏站生产批转移搬迁" + public static int BRTransferLot_Bin_M(string LotNo, string UserNo, string LinkName, int ERFType = defInteger, string RuleNo = defString, int ScrapQty = defInteger, string RuleMsg = "", string ComputerName = "AUT", bool SPCControl = false, string HoldDescription = defString, bool blnHoldLot = true) + { + int BRTransferLot_BinRet = default(int); + + // 此 Function 將執行BR完成後的連續性處理 + // 傳入值:LotNo,UserNo,LinkName,ERFType,RuleNo + // 傳回值:0(成功), -1(失敗) + // 撰寫人:sammi + // 撰寫日:2006/08/14 + + // //CCC 07,0607: 將 UserNo 傳入 ERF 開立畫面, 做為 ERF 單的開立人 + // //CCC 07,1218: 修改訊息提示, 加上訊息代碼 + // 2011/01/12 Neil:加入RuleMsg,SPC BR的情況沒有RuleNo需可指定RuleMsg + + string strDescription; + //var objEAP = new clsEAP(); + DbDataReader drTemp; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + IDbConnection cnnTemp = CreateConnection(strConnectionString); + + BRTransferLot_BinRet = -1; + + try + { + + if (LinkName == "HOLD" && blnHoldLot) + { + BRTransferLot_BinRet = 0; // 放在顯示異常介面之前.若異常開立不成功,重新刷卡即可. + // 開立異常單 + //var obj = new clsWIP(); + if (SPCControl) + { + tcEAI.clsEAP.BRERFCreateExecute(pUserId: UserNo, pLotNo: LotNo, pERFType: ERFType, pHoldTime: defInteger, pRuleNo: RuleNo, pRepairERF: false, pScrapQty: ScrapQty, pRuleMsg: RuleMsg, pHoldSystem: 1, pHoldDescription: HoldDescription); + } + else + { + tcEAI.clsEAP.BRERFCreateExecute(pUserId: UserNo, pLotNo: LotNo, pERFType: ERFType, pHoldTime: defInteger, pRuleNo: RuleNo, pRepairERF: false, pScrapQty: ScrapQty, pRuleMsg: RuleMsg, pHoldSystem: 1, pHoldDescription: RuleNo); + } + + + if (RuleNo != defString) + { + throw new iMESException.MESException("0000-200011", "[%LotNO%]:" + LotNo + "[%VIOLATE RULENO%]:" + RuleNo + "[%CREATEERF%]"); + } + else + { + throw new iMESException.MESException("0000-200011", "[%LotNO%]:" + LotNo + "[%CREATEERF%]"); + } + } + else if (LinkName == "WAIT") + { + throw new iMESException.MESException("0000-200011", "[%LotNO%]:" + LotNo + "[%WAITBASIS CREATE%]"); + } + else + { + + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + string strSQL = ""; + var objWIP = new kcWIP.clsLot(); + + //判斷品管項目是不是已經都處理完畢,已處理完畢就確認是否需要開立異常單,未處理完畢就強制將LinkName改成NEXT + if (blnHoldLot == false) + { + var dsTempQcitem = objWIP.ShowTemp_QCItem(LotNo: LotNo, AdditionalXml: " InspType_PQC = 1 "); + DataRow[] drSelExe = null; + StringBuilder holdDescriptions = new StringBuilder(); + drSelExe = dsTempQcitem.Tables[0].Select(" ExecuteFlag = 0 "); + if (drSelExe.Length == 0) //確認不存在未驗項目的狀況下,進行異常單的開立或者Transfer + { + strSQL = $" Select HoldDescription From tblWIPERFCreateData Where LotNo = '{LotNo}' And SPCSerial is not Null "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp, strDataBaseType); + while (drTemp.Read()) + { + // 確保欄位值不為 NULL + if (!drTemp.IsDBNull(0)) + { + string strholdDescription = drTemp.GetString(0); + strholdDescription = strholdDescription.Replace(" ", Environment.NewLine); // 或用 "" 空字串移除 + strholdDescription = tcEAI.clsEAP.TranslateMsg(strholdDescription); + holdDescriptions.AppendLine(strholdDescription); + } + } + + if (holdDescriptions.Length != 0 && SPCControl) + tcEAI.clsEAP.BRERFCreateExecute(pUserId: UserNo, pLotNo: LotNo, pERFType: ERFType, pHoldTime: defInteger, pRuleNo: RuleNo, pRepairERF: false, pScrapQty: ScrapQty, pRuleMsg: RuleMsg, pHoldSystem: 1, pHoldDescription: holdDescriptions.ToString()); + } + else + LinkName = "NEXT"; + } + + TransferLot_Bin_M(ComputerName, DateTime.Now, UserNo, LotNo, LinkName, result); + + if (result.ContainsKey("hold_exceedtime")) + { + tcEAI.clsEAP.BRERFCreateExecute(pUserId: UserNo, pLotNo: LotNo, pERFType: 1, pHoldTime: 0, pRuleNo: "EXCEEDTIME"); + throw new iMESException.MESException("0000-200091", "[%LotNO%]:" + LotNo + "[%VIOLATE TIME CONTROL,CREATE ERF%]!"); + } + else if (result.ContainsKey("futurehold")) + { + int intHoldTime = 0; + if (result.ContainsKey("holdtime")) + { + intHoldTime = Conversions.ToInteger(result["holdtime"].ToString()); + } + tcEAI.clsEAP.BRERFCreateExecute(pUserId: UserNo, pLotNo: LotNo, pERFType: 3, pHoldTime: intHoldTime); + throw new iMESException.MESException("0000-200091", "[%LotNO%]:" + LotNo + "[%FUTUREHOLD SET,CREATE ERF%]!"); + } + else if (result.ContainsKey("futurewait")) + { + throw new iMESException.MESException("0000-200091", "[%LotNO%]:" + LotNo + "[%FUTUREWAIT%]!"); + } + else if (result.ContainsKey("futureos")) + { + throw new iMESException.MESException("0000-200091", "[%LotNO%]:" + LotNo + "[%FUTURE OS%]!"); + } + + BRTransferLot_BinRet = 0; + + } + } + + catch (Exception ex) + { + throw ex; + } + finally + { + //数据库一定要关闭 + CloseConnection(cnnTemp); + } + + return BRTransferLot_BinRet; + + } + + + + public static string TransferLot_Bin_M(string ComputerName, DateTime ArriveTime, string UserNo, string LotNo, string LinkName = defString, Dictionary dicReturnValue = null) + { + string TransferLot_BinRet = default(string); + + var objOP = new kcOP.clsOpBasis(); + var objBR = new tcWIP_IC.clsBusinessRule(); + var objLot = new kcWIP.clsLot(); + var objSYS = new clsSYSUserLog(); + + string NextBRNo; + var colNextNode = new Collection(); + DataRow drLotState; + int PhaseNo, HoldTime; + + string[] aryTLot; // ExecuteBR使用 + var dicBRParameter = new Dictionary(); // ExecuteBR使用 + + string strReturnValue = ""; + var strResult = default(string); + string strServiceName = "EAItc_DSC.clsWIP.TransferLot"; + + // 2007/12/18 Acer 用來存放Future Wait所輸入的Description,解決Future Wait所輸入的Description不會帶到Wait Basis中的錯誤 + string strWaitDescription = defString; + string iscycle = ""; + + IDbConnection cnnTemp = null; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + try + { + + + // 2010/08/02,Sam.Hsu,傳入給FunctionBR使用之額外參數 + // + // .. .. + // + // .. + // .. + // + // + // + // If xmlDoc.DocumentElement.GetElementsByTagName("parameters").Count > 0 Then + // If xmlDoc.GetElementsByTagName("parameters").Item(0).SelectNodes("value").Count > 0 Then + // Dim xmlList As Xml.XmlNodeList = xmlDoc.GetElementsByTagName("parameters").Item(0).SelectNodes("value") + // For j As Integer = 0 To xmlList.Count - 1 + // '將資料存入暫存Collection + // dicBRParameter.Add(xmlList(j).SelectNodes("parameterno").Item(0).InnerText, + // xmlList(j).SelectNodes("parametervalue").Item(0).InnerText) + // Next + // End If + // End If + + // //Transfer---------------------------------------------------------------------------------------------------------------- + // objOP = New kcOP.clsOpBasis + // objBR = New tcWIP_IC.clsBusinessRule + + lblGetNextBR: + ; + + + // 0.檢查是否允許執行TransferLot,防止未執行,一直往下轉移 + drLotState = objLot.GetLotState(LotNo); + if (drLotState["LotNo"] is DBNull) + { + throw new iMESException.MESException("0000-200003", "LotNo:" + LotNo + " is not exist!"); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drLotState["Status"], 4, false))) + { + throw new iMESException.MESException("0000-203033", "LotNo:" + LotNo); + } + + // 2007/03/12,sammi.若沒有傳入LinkName,則使用tblWIPLotState.LinkName. + if (LinkName == defString) + { + LinkName = drLotState["LinkName"].ToString(); + } + + // Success不繼續Go,停止 + if (LinkName != null && LinkName.ToUpper() == "SUCCESS") + { + // 2006/05/23,sammi.做為呼叫端是否繼續轉移的依據. + // strReturnValue = CombineXMLReturnValue("stopflag", "StopFlag", "Integer", "", 1, "") + dicReturnValue["stopflag"] = 1.ToString(); + goto lblExit; + } + + switch (LinkName) + { + case "ABORTOP": + { + // 以後再處理 + goto lblExit; + break; + } + } + + // 2009/09/14,yumei,生產批數量為零(GoodQty=0)時,結束該流程,入不良品倉(LotState=12,ScrapINV)---- + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["CurQty"], 0, false))) + { + decimal FinalGoodQtyTmp = defInteger; + decimal FinalFailQtyTmp = defInteger; + objLot.EndOP(ref FinalGoodQtyTmp, ref FinalFailQtyTmp, LotNo, UserNo: UserNo, ReleaseEQP: true); + goto lblExit; + } + // ----------------------------------------------------------- + + + + + + // 1.取出下一個BusinessRule + NextBRNo = objLot.GetNextBR(LotNo, LinkName); + + if (NextBRNo == "END") // 沒有下一個BR,要換Node + { + // PS.不建議在此區塊內使用上述已取出的drLotState,因下述每個個別執行的Function都有可能去變更LotState + // 作業站成功完成,LotLog為有意義的資料 + decimal FinalGoodQtyTmp = defInteger; + decimal FinalFailQtyTmp = defInteger; + objLot.EndOP(ref FinalGoodQtyTmp, ref FinalFailQtyTmp, LotNo, UserNo: UserNo, ReleaseEQP: true); + + // FutureHold/FutureWait檢查 + string HoldDescriptionTmp = ""; + if (objLot.ChkFutureHold(ref HoldDescriptionTmp, LotNo, 1)) + { + HoldTime = 1; // HoldTime:End + goto lblFutureHold; // 至WinForm開單 + } + + else if (objLot.ChkFutureWait(ref strWaitDescription, LotNo, 1)) + { + // Future Wait + objLot.SetLotStateToWait(Conversions.ToLong(objLot.GetLotState(LotNo)["LotStamp"]), LotNo, 3, 1, UserNo, WaitDescription: strWaitDescription); + goto lblFutureWait; + } + + + + + //换NODE前看一下是否有隐藏站,如果有隐藏站的话,生产批状态变成该作业站的完成状态;而不是下一站的待进站状态 + DataSet dsTemp = new DataSet(); + string OPNO = ""; + string FROMNODENO = ""; + strSQL = $@"SELECT * FROM TBLWIPLOTSTATE WHERE LOTNO='{LotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "OPNO", cnnTemp); + if (dsTemp.Tables["OPNO"].Rows.Count > 0) + { + OPNO = dsTemp.Tables["OPNO"].Rows[0]["OPNO"].ToString(); + } + + strSQL = $@" Select A.GROUPNO From TBLPRSNODEBASIS A + join tblwiplotstate B on A.processno = B.processno and A.processversion = B.processversion where B.LOTNO = '{LotNo}' AND NODENO='{OPNO}' AND A.GROUPNO IS NOT NULL"; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "GROUPNO", cnnTemp); + if (dsTemp.Tables["GROUPNO"].Rows.Count > 0) + { + FROMNODENO = "GROUP" + dsTemp.Tables["GROUPNO"].Rows[0]["GROUPNO"].ToString(); + } + else + { + FROMNODENO = OPNO; + } + + strSQL = $@"Select A.* From tblPRSNodeRelation A + join tblwiplotstate B on A.processno = B.processno and A.processversion = B.processversion and A.FROMNODENO = '{FROMNODENO}' + where B.LOTNO = '{LotNo}' + and A.LinkName = 'PASS1' "; + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "tblPRSNodeRelation", cnnTemp); + if (dsTemp.Tables["tblPRSNodeRelation"].Rows.Count > 0) + { + goto lblExit; + } + else + { + if (iscycle == "1") + { + LinkName = "CYCLE"; + } + } + + // 取出下一Node{colNextNode:NodeID,NodeNo,ProcessNo,NextNodeType,PSNo(資料不一定都有)} + colNextNode = objLot.GetNextNode(LotNo, "Null", LinkName, AdditionalXml: ""); + switch (colNextNode["NextNodeType"].ToString()) + { + case "OP": + case "PRS": + case "MOD": + { + objLot.SetLotStateToNextOP(Conversions.ToLong(drLotState["LotStamp"]), LotNo, Convert.ToString(colNextNode["NodeID"]), EventUserNo: UserNo); + + // 取出LotState目前的BRNo(已轉換) + NextBRNo = Convert.ToString(objLot.GetLotState(LotNo)["BRNo"]); + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(objOP.GetBusinessRule(NextBRNo)["RuleMethod"], 0, false))) // Automatic + { + var colParameters = new Collection(); + // TriggerOP + long NewLotStampTmp = defInteger; + strReturnValue = objLot.TriggerOP(ref strWaitDescription, ref NewLotStampTmp, LotNo, UserNo: UserNo, ComputerNo: ComputerName); + if (strReturnValue == "hold_exceedtime") + { + // 2008/01/04,sammi.違反時效管制. + goto lblHold_ExceedTime; + } + else if (strReturnValue == "futurehold") + { + HoldTime = 0; // HoldTime:Start + goto lblFutureHold; + } + else if (strReturnValue == "futurewait") + { + goto lblFutureWait; + } + else if (strReturnValue == "futureos") + { + goto lblFutureOS; + } + drLotState = objLot.GetLotBasisJoinState(LotNo: LotNo); // 取得最新的LotState + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 0, false))) // by Product + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ProductNo"].ToString(), drLotState["ProductVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 1, false))) // by Module + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ModuleNo"].ToString(), drLotState["ModuleVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else + { + throw new iMESException.MESException("0000-200015", "LotNo:" + LotNo + " OPReference is not valid!"); + } + // Trigger Phase(剛做完TriggerOP,不用再執行Attrib的變更) + objLot.TriggerPhase_LotState(LotNo, PhaseNo, UserNo); + + // 加入參數 + colParameters.Add(UserNo, "UserNo"); + + // 2010/08/02,Sam.Hsu + // 加入額外參數,若有相同參數以傳入之參數取代 + // ExecuteBR中會再加入LotNo,LotSerial,MONo,ProductNo,ProductVersion,OPNo + // 因此不可再傳入上述參數 + if (dicBRParameter.Count > 0) + { + if (dicBRParameter.ContainsKey("UserNo") == true) + { + colParameters.Remove("UserNo"); + } + foreach (KeyValuePair KeyVal in dicBRParameter) + colParameters.Add(KeyVal.Value, KeyVal.Key); + } + + // 執行BR + LinkName = objBR.ExecuteBR(LotNo, NextBRNo, colParameters); + + // 06/04/25,sammi.檢查LinkName是否為多批.若是只須執行轉移即可,不用繼續往下做. + aryTLot = Strings.Split(LinkName, ";"); // LinkName=PASS or LinkName=L001,PASS;L002,PASS;L003:Rework + if (aryTLot.Length == 1) + { + // 原本的轉移,仍延用原LotNo + // 繼續找下一個BR,Success不繼續Go,停止 + if (LinkName.ToUpper() == "SUCCESS") + { + // 2006/05/23,sammi.做為呼叫端是否繼續轉移的依據. + strReturnValue = iMESCore.Base.iMESComXML.CombineXMLReturnValue("stopflag", "StopFlag", "Integer", "", 1.ToString(), ""); + goto lblExit; + } + else + { + goto lblGetNextBR; + } + } + else + { + goto lblLotTransfer; + } + + } + + break; + } + + case "END": + { + objLot.SetLotStateToNextOP(Conversions.ToLong(drLotState["LotStamp"]), LotNo, Convert.ToString(colNextNode["NodeID"]), EventUserNo: UserNo); + + // 93/09/13,讓流程轉移時,第一個OP的第一個AutoBR可自動執行 ' + // Q1.SetLotStateToNextOP可能入庫(Status = 11),以避免 + // Q2.SetLotStateToNextOP可能轉移至Group內的OP上(則BR自動執行,將無法選擇要執行那個Group內的OP),目前沒有避免 + // 2008/11/28,sammi.Lot可能結批,故不一定會有資料,加上drLotState("LotNo").ToString <> ""的判斷. + // 取出LotState目前的BRNo(已轉換) + drLotState = objLot.GetLotState(LotNo); + if (!string.IsNullOrEmpty(drLotState["LotNo"].ToString()) && Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["Status"], 0, false))) // 避免Q1 + { + NextBRNo = drLotState["BRNo"].ToString(); + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(objOP.GetBusinessRule(NextBRNo)["RuleMethod"], 0, false))) // Automatic + { + var colParameters = new Collection(); + // TriggerOP + long NewLotStampTmp = defInteger; + strReturnValue = objLot.TriggerOP(ref strWaitDescription, ref NewLotStampTmp, LotNo, UserNo: UserNo, ComputerNo: ComputerName); + if (strReturnValue == "hold_exceedtime") + { + // 2008/01/04,sammi.違反時效管制. + goto lblHold_ExceedTime; + } + else if (strReturnValue == "futurehold") + { + HoldTime = 0; // HoldTime:Start + goto lblFutureHold; + } + else if (strReturnValue == "futurewait") + { + goto lblFutureWait; + } + else if (strReturnValue == "futureos") + { + goto lblFutureOS; + } + drLotState = objLot.GetLotBasisJoinState(LotNo: LotNo); // 取得最新的LotState + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 0, false))) // by Product + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ProductNo"].ToString(), drLotState["ProductVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 1, false))) // by Module + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ModuleNo"].ToString(), drLotState["ModuleVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else + { + throw new iMESException.MESException("0000-200015", "LotNo:" + LotNo + " OPReference is not valid!"); + } + // Trigger Phase(剛做完TriggerOP,不用再執行Attrib的變更) + objLot.TriggerPhase_LotState(LotNo, PhaseNo, UserNo); + + // 加入參數 + colParameters.Add(UserNo, "UserNo"); + + // 2010/08/02,Sam.Hsu + // 加入額外參數,若有相同參數以傳入之參數取代 + // ExecuteBR中會再加入LotNo,LotSerial,MONo,ProductNo,ProductVersion,OPNo + // 因此不可再傳入上述參數 + if (dicBRParameter.Count > 0) + { + if (dicBRParameter.ContainsKey("UserNo") == true) + { + colParameters.Remove("UserNo"); + } + foreach (KeyValuePair KeyVal in dicBRParameter) + colParameters.Add(KeyVal.Value, KeyVal.Key); + } + + // 執行BR + LinkName = objBR.ExecuteBR(LotNo, NextBRNo, colParameters); + + // 06/04/25,sammi.檢查LinkName是否為多批.若是只須執行轉移即可,不用繼續往下做. + aryTLot = Strings.Split(LinkName, ";"); // LinkName=PASS or LinkName=L001,PASS;L002,PASS;L003:Rework + if (aryTLot.Length == 1) + { + // 原本的轉移,仍延用原LotNo + // 繼續找下一個BR,Success不繼續Go,停止 + if (LinkName.ToUpper() == "SUCCESS") + { + // 2006/05/23,sammi.做為呼叫端是否繼續轉移的依據. + // strReturnValue = CombineXMLReturnValue("stopflag", "StopFlag", "Integer", "", 1, "") + dicReturnValue["stopflag"] = 1.ToString(); + goto lblExit; + } + else + { + goto lblGetNextBR; + } + } + else + { + goto lblLotTransfer; + } + + } + } + + break; + } + + case "ANDGROUP": + case "ORGROUP": // Group + { + objLot.SetLotStateToNextOP(Conversions.ToLong(drLotState["LotStamp"]), LotNo, Convert.ToString(colNextNode["NodeID"]), EventUserNo: UserNo); + break; + } + + case "ANDGROUPOP": // ANDGroup的OP + { + objLot.SetLotStateToOtherGroupOP(Conversions.ToLong(drLotState["LotStamp"]), LotNo, true, Convert.ToString(colNextNode["NodeID"]), EventUserNo: UserNo); + break; + } + + default: + { + // Immediate Wait + objLot.SetLotStateToWait(Conversions.ToLong(drLotState["LotStamp"]), LotNo, 2, UserNo: UserNo); + break; + } + + } + } + + else if (NextBRNo == defString) // 找不到下一個BR + { + // Immediate Wait + objLot.SetLotStateToWait(Conversions.ToLong(drLotState["LotStamp"]), LotNo, 2, UserNo: UserNo); + } + + else // Find next BR + { + // 檢查是否Trigger Phase + drLotState = objLot.GetLotBasisJoinState(LotNo: LotNo); // 取得最新的LotState + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 0, false))) // by Product + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ProductNo"].ToString(), drLotState["ProductVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drLotState["OPReference"], 1, false))) // by Module + { + PhaseNo = objLot.GetBusinessRulePhase(drLotState["ModuleNo"].ToString(), drLotState["ModuleVersion"].ToString(), drLotState["OPNo"].ToString(), NextBRNo); + } + else + { + throw new iMESException.MESException("0000-200015", "LotNo:" + LotNo + " OPReference is not valid!"); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drLotState["PhaseNo"], PhaseNo, false))) + { + objLot.TriggerPhase(LotNo, PhaseNo, EventUserNo: UserNo); + } + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(objOP.GetBusinessRule(NextBRNo)["RuleMethod"], 0, false))) // Automatic + { + var colParameters = new Collection(); + // 更新LotState的BR + objLot.SetLotStateToNextBR(Conversions.ToLong(drLotState["LotStamp"]), LotNo, NextBRNo, EventUserNo: UserNo); + // 加入參數 + colParameters.Add(UserNo, "UserNo"); + + // 2010/08/02,Sam.Hsu + // 加入額外參數,若有相同參數以傳入之參數取代 + // ExecuteBR中會再加入LotNo,LotSerial,MONo,ProductNo,ProductVersion,OPNo + // 因此不可再傳入上述參數 + if (dicBRParameter.Count > 0) + { + if (dicBRParameter.ContainsKey("UserNo") == true) + { + colParameters.Remove("UserNo"); + } + foreach (KeyValuePair KeyVal in dicBRParameter) + colParameters.Add(KeyVal.Value, KeyVal.Key); + } + + // 執行BR + LinkName = objBR.ExecuteBR(LotNo, NextBRNo, colParameters); + + // 06/04/25,sammi.檢查LinkName是否為多批.若是只須執行轉移即可,不用繼續往下做. + aryTLot = Strings.Split(LinkName, ";"); // LinkName=PASS or LinkName=L001,PASS;L002,PASS;L003:Rework + if (aryTLot.Length == 1) + { + // 原本的轉移,仍延用原LotNo + // 繼續找下一個BR,Success不繼續Go,停止 + if (LinkName.ToUpper() == "SUCCESS") + { + // 2006/05/23,sammi.傳出LinkName,做為呼叫端是否繼續轉移的依據. + // strReturnValue = CombineXMLReturnValue("stopflag", "StopFlag", "Integer", "", 1, "") + dicReturnValue["stopflag"] = 1.ToString(); + goto lblExit; + } + else + { + goto lblGetNextBR; + } + } + else + { + goto lblLotTransfer; + } + } + + else // Manual + { + objLot.SetLotStateToNextBR(Conversions.ToLong(drLotState["LotStamp"]), LotNo, NextBRNo, EventUserNo: UserNo); + } + + } + + goto lblExit; + + lblHold_ExceedTime: + ; + + // strReturnValue = CombineXMLReturnValue("hold_exceedtime", "Hold_ExceedTime", "String", "", "Hold_ExceedTime", "") + dicReturnValue["Hold_ExceedTime"] = "Hold_ExceedTime"; + goto lblExit; + + lblFutureHold: + ; + + // strReturnValue = CombineXMLReturnValue("futurehold", "FutureHold", "String", "", "FutureHold", "") + // strReturnValue += CombineXMLReturnValue("holdtime", "holdtime", "String", "", HoldTime, "") + dicReturnValue["FutureHold"] = "FutureHold"; + dicReturnValue["HoldTime"] = HoldTime.ToString(); + goto lblExit; + + lblFutureWait: + ; + + strReturnValue = iMESCore.Base.iMESComXML.CombineXMLReturnValue("futurewait", "FutureWait", "String", "", "FutureWait", ""); + dicReturnValue["FutureWait"] = "FutureWait"; + // 2012/02/10 YF, 回傳Wait Description + if (strWaitDescription != defString) + { + // strReturnValue += CombineXMLReturnValue("waitdescription", "WaitDescription", "String", "", strWaitDescription, "") + dicReturnValue["WaitDescription"] = strWaitDescription; + } + goto lblExit; + + lblFutureOS: + ; + + // strReturnValue = CombineXMLReturnValue("futureos", "FutureOS", "String", "", "FutureOS", "") + dicReturnValue["FutureOS"] = "FutureOS"; + goto lblExit; + + lblLotTransfer: + ; + + + // BR可能執行了分批,系統必須轉移傳出的批號 + string strRS; + string[] aryLink; + int i; + var loopTo = aryTLot.Length - 1; + for (i = 0; i <= loopTo; i++) + { + do + { + try + { + aryLink = Strings.Split(aryTLot[i], ","); // aryTLot(i) = L001,PASS + if (aryLink.Length > 0 && string.IsNullOrEmpty(aryLink[0])) + { + break; + } + // Transfer Lot + if (aryLink.Length == 1) // LinkName預設為Pass + { + // strInXmlParameter = CombineXMLParameter("lotno", "LotNo", "String", aryLink(0), "") + Dictionary argdicReturnValue = null; + strRS = TransferLot_Bin_M(ComputerName, DateTime.Now, UserNo, aryLink[0], dicReturnValue: argdicReturnValue); + } + else + { + // strInXmlParameter = CombineXMLParameter("lotno", "LotNo", "String", aryLink(0), "") + // strInXmlParameter = strInXmlParameter & CombineXMLParameter("linkname", "LinkName", "String", aryLink(1), "") + Dictionary argdicReturnValue1 = null; + strRS = TransferLot_Bin_M(ComputerName, DateTime.Now, UserNo, aryLink[0], aryLink[1], dicReturnValue: argdicReturnValue1); + } + + Dictionary argdicReturnValue2 = null; + strRS = TransferLot_Bin_M(ComputerName, DateTime.Now, UserNo, aryLink[0], dicReturnValue: argdicReturnValue2); + if (strRS != "success") + { + throw new iMESException.MESException("0000-203036", "Transfer Lot fail," + strResult); + } + } + catch (iMESException.MESException ex) + { + throw; + } + catch (Exception e1) + { + throw; + } + finally + { + } + } + while (false); + } + + goto lblExit; + + lblExit: + ; + + + strResult = "success"; + + objSYS.AddEventLog(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, "TransferLot,LinKname:" + LinkName, ComputerName: ComputerName); + } + + catch (iMESException.MESException ex) + { + + strResult = ex.Message + " : " + ex.StackTrace; + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, strResult, ComputerName: ComputerName, ErrorCode: Convert.ToString(ex.ErrorCode)); + + throw ex; + } + + catch (Exception ex) + { + + strResult = ex.Message + " : " + ex.StackTrace; + objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, strResult, ComputerName: ComputerName); + + throw ex; + } + + finally + { + if (!(objLot == null)) + objLot = null; + if (!(objOP == null)) + objOP = null; + if (!(objBR == null)) + objBR = null; + if (!(objSYS == null)) + objSYS = null; + + //数据库一定要关闭 + CloseConnection(cnnTemp); + + // 將各部份之XML字串組起來並傳出 + TransferLot_BinRet = strResult; + + + } + + return TransferLot_BinRet; + + } + + + #endregion + /// + /// 写入字符串日志,固定路径 D:\meslog\eai + /// + /// 日志内容 + public static void WriteLog(string message) + { + try + { + // 固定文件夹路径 + string logDirectory = @"D:\meslog\eai"; + + // 不存在则创建目录 + if (!Directory.Exists(logDirectory)) + { + Directory.CreateDirectory(logDirectory); + } + + // 按日期生成日志文件 + string fileName = $"Log_{DateTime.Now:yyyyMMdd}.txt"; + string fullPath = Path.Combine(logDirectory, fileName); + + // 拼接时间与日志内容 + string logLine = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {message}{Environment.NewLine}"; + + // 追加写入文件 + File.AppendAllText(fullPath, logLine); + } + catch (Exception ex) + { + Console.WriteLine($"日志写入异常:{ex.Message}"); + } + } + public string SetLotStateToNextBR(long LotStamp, string LotNo, string BRNo, string AdditionalXml = "", string EventUserNo = "", string EventDescription = "", Collection colSQL = null) + { + string SetLotStateToNextBRRet = default(string); + // 此 Function 將使 Lot 的現況移到下一個 Business Rule + // 傳入值: 索引值 + // 傳回值: success(成功), fail(失敗) + + var CollectionSQL = new Collection(); + + var datEventTime = DateTime.Now; + + try + { + // 呼叫執行SQL指令(1:Run) + strSQL = "Update tblWIPLotState Set BRNo ='" + BRNo + "'," + " EventTime=To_Date('" + Strings.Format(datEventTime, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + " EventUserNo='" + EventUserNo + "'," + " EventDescription='" + EventDescription + "'," + " Status = 1 " + " Where LotNo ='" + LotNo + "'"; + CollectionSQL.Add(strSQL); + + // 2006/07/12,sammi.檢查是否允許執行 + Collection argcolSQL_Rows = null; + objLot.ChkLotStamp(LotNo, LotStamp, CollectionSQL, colSQL_Rows: argcolSQL_Rows); + + if (colSQL == null) + { + // 呼叫執行SQL指令 + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + } + else + { + for (int i = 1, loopTo = CollectionSQL.Count; i <= loopTo; i++) + colSQL.Add(CollectionSQL[i]); + } + + // 2019/10/28 Yenru , Add SignalR BroadCast + try + { + // 站內移轉 + // 設備:加工設備生產批狀態變更、未加工設備刪除顯示生產批。 + // 作業站:生產批狀態變更。 + using (var objMDS = new kcWIP.clsMDS()) + { + + var drLotInfo = objLot.GetLotState(LotNo); + var dTEQPInfo = objLot.ShowTemp_Equipment(LotNo).Tables[0]; + string strEQPList = ""; + var oParameter = new Dictionary(); + + // 整理設備資訊 + foreach (DataRow drTemp in dTEQPInfo.Rows) + strEQPList += drTemp["EquipmentNo"].ToString() + ","; + strEQPList = strEQPList.TrimEnd(','); + + oParameter.Add("ProcessType", "SetLotStateToNextBR"); + oParameter.Add("lotno", LotNo); + oParameter.Add("orgopno", drLotInfo["OPNO"].ToString()); + oParameter.Add("equiplist", strEQPList); + + objMDS.SignalRDataSummary(oParameter); + + // 20200917 雋辰 ,SignalR 生產任務(派工頁簽) + oParameter["ProcessType"] = "SetLotStateToNextBR_Dispatch"; + objMDS.SignalRDataSummary(oParameter); + } + } + catch (Exception ex) + { + } + + // Return success + SetLotStateToNextBRRet = "success"; + } + + catch (Exception e1) + { + SetLotStateToNextBRRet = "fail"; + throw; + + } // New Exception("kcWIP.SetLotStateToNextBR: " & e1.Message) + return SetLotStateToNextBRRet; + + } + + + public static Collection GetNextNode(string LotNo, string NodeID = defString, string LinkName = defString, string AdditionalXml = "") + { + Collection GetNextNodeRet = default(Collection); + // 此 Function 將取得LotNo目前Node的下一Node,或是依指定NodeID,LinkName取得下一Node + // 傳入值: 索引值 + // 傳回值: Collection(成功), fail(失敗) + + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + var colGetNextNode = new Collection(); + string GroupNodeID, CurNodeID, NextNodeID, NextNodeNo; + int GroupType; // 6:AND,7:OR + + try + { + cnnTemp = CreateConnection(strConnectionString); + + // 1.依LotNo取出NodeID,PSNo + if (NodeID == defString) + { + strSQL = "Select NodeID From tblWIPLotState Where LotNo ='" + LotNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + CurNodeID = drTemp["NodeID"].ToString(); + } + else + { + colGetNextNode.Add("WAIT", "NextNodeType"); + goto lblExitProcedure; + } + drTemp.Close(); + } + + else + { + CurNodeID = NodeID; + } + + // 2.檢查OPGroupState內是否有未執行OP(OPGroupState內的一定是要執行的,不執行的不會加入OPGroupState) + strSQL = "Select GroupType,GroupNodeID, NodeID From tblWIPOPGroupState Where LotNo ='" + LotNo + "'" + " And NodeID ='" + CurNodeID + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + GroupType = Conversions.ToInteger(drTemp["GroupType"]); + GroupNodeID = drTemp["GroupNodeID"].ToString(); + + drTemp.Close(); + + + if (GroupType == 6) // AND Group + { + strSQL = "Select NodeID,OPNo From tblWIPOPGroupState Where LotNo ='" + LotNo + "'" + " And NodeID <> '" + CurNodeID + "'" + " And ExecuteFlag = 0 "; // 剔除目前的OP,未執行之OP + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + colGetNextNode.Add(drTemp["NodeID"], "NodeID"); + colGetNextNode.Add(drTemp["OPNo"], "NodeNo"); // OPNo + colGetNextNode.Add("ANDGROUPOP", "NextNodeType"); + goto lblExitProcedure; + } + else // 用GroupNodeID找下個Node + { + CurNodeID = GroupNodeID; + } + drTemp.Close(); + } + + + else if (GroupType == 7) // OR Group + { + CurNodeID = GroupNodeID; + } + } + else + { + drTemp.Close(); + + } + + + lblGetNextNode: + ; + + + + // 3.依 CurNodeID,LinkName 取出 NextNodeID + strSQL = "Select ToNodeID,ToNodeNo From tblPRSNodeRelation Where FromNodeID ='" + CurNodeID + "'"; + if (LinkName == defString || LinkName == null) + { + strSQL = strSQL + " And LinkName ='PASS'"; + } + else + { + strSQL = strSQL + " And LinkName ='" + LinkName.ToUpper() + "'"; + } + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) // 沒有找到下一節點 + { + drTemp.Close(); + + colGetNextNode.Add("WAIT", "NextNodeType"); + goto lblExitProcedure; + } + + // 找到下一節點--------------------------------------------------------------------------------------------------------------- + NextNodeID = drTemp["ToNodeID"].ToString(); + NextNodeNo = drTemp["ToNodeNo"].ToString(); + drTemp.Close(); + + + // '4.檢查下一節點是否不執行 + // strSQL = "Select OPNo From tblWIPLotNotExecuteOP " & _ + // " Where LotNo = '" & LotNo & "' And OPNo = '" & NextNodeNo & "'" + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + // drTemp = cmmTemp.ExecuteReader() + // If drTemp.Read Then '不執行,繼續找下一Node,linkname變更為Pass + // drTemp.Close() + // CurNodeID = NextNodeID + // LinkName = "PASS" + // GoTo lblGetNextNode + // Else + // drTemp.Close() + // End If + + // ---------------------------------------------------------------------------------------------------------------------------- + // 5.依 NextNodeID 取出 Node 的基本資料 + strSQL = "Select ProcessNo, ProcessVersion, NodeID, NodeNo, NodeVersion, NodeType From tblPRSNodeBasis " + " Where NodeID ='" + NextNodeID + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + int iNodeType = -1; + if (!int.TryParse(drTemp["NodeType"].ToString(), out iNodeType)) + iNodeType = -1; + switch (iNodeType) + { + case 0: // OP + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // OPNo + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("OP", "NextNodeType"); + break; + } + + + case 1: // Sub Process + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // Sub ProcessNo + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion(可能是*) + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("PRS", "NextNodeType"); + break; + } + + + case 6: // And Group + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // GroupNo(Ex:GROUP6) + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("ANDGROUP", "NextNodeType"); + break; + } + + + case 7: // OR Group + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // GroupNo(Ex:GROUP7) + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("ORGROUP", "NextNodeType"); + break; + } + + + case 9: // END + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // OPNo + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("END", "NextNodeType"); + break; + } + + + case 2: // Module + { + colGetNextNode.Add(NextNodeID, "NodeID"); + colGetNextNode.Add(drTemp["NodeNo"], "NodeNo"); // Module + colGetNextNode.Add(drTemp["NodeVersion"], "NodeVersion"); // NodeVersion(可能是*) + colGetNextNode.Add(drTemp["ProcessNo"], "ProcessNo"); // ProcessNo + colGetNextNode.Add(drTemp["ProcessVersion"], "ProcessVersion"); // ProcessVersion + colGetNextNode.Add("MOD", "NextNodeType"); + break; + } + + default: + { + colGetNextNode.Add("WAIT", "NextNodeType"); + break; + } + + } + } + else + { + throw new iMESException.MESException("0000-200003", "[%Process%] [%Nodeinformation%] [%not found%], [%please check%] [%processbasis%]" + Constants.vbCrLf + "[%NodeID%]: " + NextNodeID); + } + drTemp.Close(); + + + lblExitProcedure: + ; + + + GetNextNodeRet = colGetNextNode; + } + + catch (Exception e1) + { + GetNextNodeRet = null; + throw; + } // New Exception("kcWIP.GetNextNode: " & e1.Message) + + finally + { + // 關閉連線 + CloseConnection(cnnTemp); + + } + return GetNextNodeRet; + + } + + /// + /// 产生位置号与序号(逐字抽出自 funTrackOut_Inquiry 原 :2829-2873,行为不变) + /// + private static bool funInitDieSerial( + ref List aryMessage, ref List aryException, + string PanleId, string strMLotNo, string strProductNo, string strProductVersion, + string strSeqNoRule, string strSeqNoType, string strSeqNoSize, string strDirection, + int intColumn, int intLine, string[,] unitIdOrPannids, string[,] locations, + IDbConnection cnnTemp) + { + string strSQL = default(string); + DbDataReader drTemp = null; + string strUnitIdOrPannid = "";//UnitId或者Pannid + + try + { + funInitlocation(locations, strSeqNoSize, strDirection, intColumn, intLine); + + for (int i = 0; i < intLine; i++) + { + for (int j = 0; j < intColumn; j++) + { + PanelidOrUnitId: + //校验生成的序号是否有禁用字符 + DataTable dtSeqNo = InitPanleIdOrUnitId(ReserveSerialNo: false, SerialCount: 1L, SerialTypeNo: strSeqNoRule, LotNo: strMLotNo, PanleId: PanleId, ProductNo: strProductNo, SerialType: strSeqNoType, location: locations[i, j]); + + if (dtSeqNo.Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%产品编号%] :" + strProductNo + " [%产品版本%] :" + strProductVersion + "[%生成序号失败%]"); + return false; + } + + strUnitIdOrPannid = Conversions.ToString(dtSeqNo.Rows[0]["SeqNo"]); + + //校验生成的UnitId是否有禁用字符 + strSQL = $"SELECT DISABLE FROM TBLCUSDISABLEDFIELD WHERE PRODUCTNO='{strProductNo}'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTemp.Read()) + { + if (strUnitIdOrPannid.Contains(drTemp["DISABLE"].ToString())) + { + InitPanleIdOrUnitId(ReserveSerialNo: true, SerialCount: 1L, SerialTypeNo: strSeqNoRule, LotNo: strMLotNo, PanleId: PanleId, ProductNo: strProductNo, SerialType: strSeqNoType, location: locations[i, j]); + goto PanelidOrUnitId; + //clsERP.combineMessage(ref aryMessage, mmsg: "[%序号生成%] : " + strUnitIdOrPannid + "存在禁用字符 :" + drTemp["DISABLE"].ToString() + ",请重新生成!"); + //return false; + } + } + drTemp.Close(); + strSQL = $"SELECT UNITID FROM TBLPCSDIELOG_LQ WHERE UNITID='{strUnitIdOrPannid}'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%UNITID在表TBLPCSDIELOG_LQ中已存在%]"); + return false; + } + drTemp.Close(); + //直接回写序号,防止被占用 + InitPanleIdOrUnitId(ReserveSerialNo: true, SerialCount: 1L, SerialTypeNo: strSeqNoRule, LotNo: strMLotNo, PanleId: PanleId, ProductNo: strProductNo, SerialType: strSeqNoType, location: locations[i, j]); + unitIdOrPannids[i, j] = strUnitIdOrPannid; + } + } + + return true; + } + finally + { + drTemp?.Close(); + } + } + + /// + /// 写入客制表 TBLPCSDIELOG_LQ(逐字抽出自 funTrackOut_Inquiry 原 :3171-3185,行为不变) + /// + private static void funSaveDieLog( + string PanleId, string inLotNo, string EQPID, string strOPNO, + int intColumn, int intLine, string carrierId, string strMNewLotSerial, + string[,] unitIdOrPannids, string[,] locations, Collection CollectionSQL) + { + string strSQL = default(string); + + for (int i = 0; i < intLine; i++) + { + for (int j = 0; j < intColumn; j++) + { + strSQL = $@"INSERT INTO TBLPCSDIELOG_LQ ( PANLEID,UNITID,LINE,""COLUMN"",EQPID,OPNO,LOTNO,CREATEDATE,LOCATIONNO ) VALUES('{PanleId}', '{unitIdOrPannids[i, j]}', '{i + 1}', '{j + 1}', '{EQPID}', '{strOPNO}', '{inLotNo}', SYSDATE, '{locations[i, j]}')"; + CollectionSQL.Add(strSQL); + + //回复处理 + strSQL = $"DELETE FROM TBLPCSDIELOG_LQ WHERE PANLEID='{PanleId}' AND LOTNO='{inLotNo}'"; + + objReverse.AddReverseUpdateContent(ref strMNewLotSerial, ref strSQL, CollectionSQL); + SaveWIPPrdStateLog_M(LotNo: inLotNo, ProductID: unitIdOrPannids[i, j], EQPID: EQPID, OPNo: strOPNO, State: 1, ProductType: "1", CarrierID: carrierId, LotSerial: strMNewLotSerial, colSQL: CollectionSQL); + + } + } + } + + /// + /// (xg)解析 mapdata 找出为 0 的位置,依产品走位设定换算成 LOCATIONNO 后打不良(BADFLAG=2、REASONNO='来料异常') + /// (xg)当传入 unitIdOrPannids 与 MotherLotNo 时,同时将不良品批次归属改回母批,并更新客制状态表 tblwipprdstate_LQ(STATE=2) + /// + /// EAP 送出之良品图,依行列自然顺序(row-major)排列,0=不良、1=良品 + /// 该产品之起始角(TBLPRDPRODUCTBASIS.STARTPOINT) + /// 该产品之走向(TBLPRDPRODUCTBASIS.DIRECTION) + /// (xg)各位置对应之 UNITID 二维阵列,传 null 则不更新客制状态表 + /// (xg)母批批号,传 null 则不良品 LOTNO 不变更 + //(xg)原签名: public static bool funMarkBadByMapData(ref List aryMessage, string PanleId, string LotNo, string MapData, string strSeqNoSize, string strDirection, int intColumn, int intLine, Collection colSQL) + //(xg)改签名: 新增 unitIdOrPannids, MotherLotNo 两个可选参数 + public static bool funMarkBadByMapData( + ref List aryMessage, + string PanleId, string LotNo, string MapData, + string strSeqNoSize, string strDirection, + int intColumn, int intLine, Collection colSQL, + string[,] unitIdOrPannids = null, string MotherLotNo = null) + { + string strSQL = default(string); + + //未传 mapdata 则不打不良、不报错 + if (string.IsNullOrEmpty(MapData)) + { + return true; + } + + //长度校验 + if (MapData.Length != intColumn * intLine) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%mapdata长度%]:" + MapData.Length + " [%与行列数不符%]:" + intColumn + "*" + intLine); + return false; + } + + //建立与写入 die log 时同源的走位对照表:LOCATIONNO 系沿走位路径编号, + //并非 mapdata 之行列自然顺序,故不可直接取 k+1(否则仅「左上+全部横向」一种设定会打对) + string[,] locations = new string[intLine, intColumn]; + funInitlocation(locations, strSeqNoSize, strDirection, intColumn, intLine); + + //(xg)新增: 当传入了 unitIdOrPannids 与 MotherLotNo 时,一并执行不良品归母批 + 客制状态表更新 + bool bolUpdateState = (unitIdOrPannids != null && !string.IsNullOrEmpty(MotherLotNo)); + + for (int k = 0; k < MapData.Length; k++) + { + //0 = 不良、1 = 良品 + if (MapData[k] == '0') + { + //mapdata 第 k 位 → 第 (k / intLine) 行、第 (k % intLine) 列 + int intRow = k / intLine; + int intCol = k % intLine; + string strLocationNo = locations[intCol, intRow]; + + if (bolUpdateState) + { + //(xg)新增1.更新 TBLPCSDIELOG_LQ:打不良标记 + 改批次归属为母批 LOTNO=MotherLotNo(只分良品,不分不良品) + //strSQL = $@"UPDATE TBLPCSDIELOG_LQ SET BADFLAG = 2, REASONNO = '来料异常', LOTNO = '{MotherLotNo}' WHERE LOCATIONNO = '{strLocationNo}' AND PANLEID = '{PanleId}' AND LOTNO = '{LotNo}'"; + strSQL = $@"UPDATE TBLPCSDIELOG_LQ SET BADFLAG = 2, REASONNO = '来料异常' WHERE LOCATIONNO = '{strLocationNo}' AND PANLEID = '{PanleId}' AND LOTNO = '{LotNo}'"; + colSQL.Add(strSQL); + + //(xg)新增2.更新客制状态表 tblwipprdstate_LQ:不良品状态 STATE 改为 2 + string strUnitId = unitIdOrPannids[intCol, intRow]; + strSQL = $@"UPDATE TBLWIPPRDSTATE_LQ SET STATE = 2 WHERE PRODUCTID = '{strUnitId}' AND PRODUCTTYPE = '1' AND STATE = 1"; + colSQL.Add(strSQL); + } + else + { + //原版行为:仅打不良标记 BADFLAG=2、REASONNO='来料异常',不做批次归属变更 + strSQL = $@"UPDATE TBLPCSDIELOG_LQ SET BADFLAG = 2, REASONNO = '来料异常' WHERE LOCATIONNO = '{strLocationNo}' AND PANLEID = '{PanleId}' AND LOTNO = '{LotNo}'"; + colSQL.Add(strSQL); + } + } + } + + return true; + } + + + /// + /// 产生位置号与序号并写入 TBLPCSDIELOG_LQ(自 funTrackOut_Inquiry 逐字抽出,行为不变) + /// + /// 母批批号,供序号产生器使用(等同首站接口的 strMLotNo) + /// 记录批号,写入客制表使用;有分批时为子批(等同首站接口的 inLotNo) + public static bool funCreateDieLog( + ref List aryMessage, ref List aryException, + string PanleId, string MotherLotNo, string LotNo, string EQPID, string OPNO, + string ProductNo, string ProductVersion, + string SeqNoRule, string SeqNoType, string SeqNoSize, string Direction, + int intColumn, int intLine, string CarrierId, string LotSerial, + Collection colSQL, IDbConnection cnnTemp) + { + string[,] unitIdOrPannids = new string[intLine, intColumn]; + string[,] locations = new string[intLine, intColumn]; + + //产生位置号与序号:序号产生器用母批 + if (!funInitDieSerial(ref aryMessage, ref aryException, PanleId, MotherLotNo, ProductNo, ProductVersion, SeqNoRule, SeqNoType, SeqNoSize, Direction, intColumn, intLine, unitIdOrPannids, locations, cnnTemp)) + { + return false; + } + + //写入客制表:die log 用记录批号(有分批时为子批) + funSaveDieLog(PanleId, LotNo, EQPID, OPNO, intColumn, intLine, CarrierId, LotSerial, unitIdOrPannids, locations, colSQL); + + return true; + } + + + + + + + + + + + + + + + + + + /// + /// 出站 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + // 17单:作业站属性存在即生效(M7)——服务端直查 TBLOPPROPERTY + private static bool funOPPropertyExists_LQ(string OPNO, string PropertyNo, IDbConnection cnnTemp) + { + DataTable dt = new DataTable(); + string strSQL = $"SELECT 1 FROM TBLOPPROPERTY WHERE OPNO='{OPNO}' AND PROPERTYNO='{PropertyNo}' AND ISSUESTATE=2"; + ExecuteSQLQuery_Adapter(strSQL, dt, cnnTemp); + return dt.Rows.Count > 0; + } + + // 17单 M6(内联,EAItc 不引用 MEStc_LQ):TRAY 上无 carrier 则寿命+1(门槛), + // 达报废(3)/维修(2)则保留该状态,未触门槛才置闲置(0)——等价 MEStc_LQ.clsEQP.EditCarrierLife + M6 优先序 + private static void funUnbindTrayLife_LQ(string CarrierId, string TrayId, string UserNo, string strDataBaseType, string strConnectionString, IDbConnection cnnTemp) + { + // 删该 carrier 在 TRAY 的绑定明细 + Collection colDel = new Collection(); + colDel.Add($"delete from TBLWIPTRAYSTATE_LQ where trayid='{TrayId}' and carrierid='{CarrierId}'"); + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, colDel); + + // TRAY 上是否还有 carrier + DataTable dtRest = new DataTable(); + ExecuteSQLQuery_Adapter($"select 1 from TBLWIPTRAYSTATE_LQ where trayid='{TrayId}'", dtRest, cnnTemp); + if (dtRest.Rows.Count > 0) return; + + // 取 TRAY 的 CarrierType + string strType = ""; + DataTable dtCt = new DataTable(); + ExecuteSQLQuery_Adapter($"select CarrierType from tblWIPCarrierState where CarrierNo='{TrayId}'", dtCt, cnnTemp); + if (dtCt.Rows.Count > 0) strType = dtCt.Rows[0]["CarrierType"].ToString(); + + Collection colLife = new Collection(); + string strNewState = "0"; // 默认闲置 + DataTable dtSet = new DataTable(); + ExecuteSQLQuery_Adapter($"select ALERTCOUNT,LIMITCOUNT,SCRAPCOUNT from TBLCUSCARRIERLIFESET where CARRIERTYPE='{strType}'", dtSet, cnnTemp); + if (dtSet.Rows.Count > 0) + { + DataTable dtLife = new DataTable(); + ExecuteSQLQuery_Adapter($"select ACCUMULATEQTY,ACCTOTALUSEDQTY from TBLCUSCARRIERLIFE where CARRIERNO='{TrayId}'", dtLife, cnnTemp); + if (dtLife.Rows.Count > 0) + { + decimal accQty = decimal.Parse(dtLife.Rows[0]["ACCUMULATEQTY"].ToString()); + decimal accTotal = decimal.Parse(dtLife.Rows[0]["ACCTOTALUSEDQTY"].ToString()); + decimal limitCnt = decimal.Parse(dtSet.Rows[0]["LIMITCOUNT"].ToString()); + decimal scrapCnt = decimal.Parse(dtSet.Rows[0]["SCRAPCOUNT"].ToString()); + if (accTotal + 1 >= scrapCnt) strNewState = "3"; // 报废 + else if (accQty + 1 >= limitCnt) strNewState = "2"; // 维修 + colLife.Add($"update TBLCUSCARRIERLIFE set ACCUMULATEQTY=ACCUMULATEQTY+1, ACCTOTALUSEDQTY=ACCTOTALUSEDQTY+1, REVISER='{UserNo}', REVISEDATE=sysdate where CARRIERNO='{TrayId}'"); + } + } + // M6 优先序:门槛(3/2)优先,未触门槛才置闲置(0) + colLife.Add($"update TBLWIPCARRIERSTATE set CARRIERSTATE={strNewState} where CARRIERNO='{TrayId}'"); + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, colLife); + } + + // 17单 需求二/三:依作业站属性自动解绑(TRAY / 小载具)+ 分批出站(隐藏站转移) + // 回传 false=属性分支执行失败;bolHandled=true 表示已处理完成,呼叫端不再走标准判型出站 + private static bool funAutoUnbindCheckOut_LQ(ref List aryMessage, string Type, string strProductID_Auto, string strCarrierID_Auto, string EQPID, out bool bolHandled) + { + bolHandled = false; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + IDbConnection cnnTemp = CreateConnection(strConnectionString); + const string UserNo = "EAP"; + try + { + // 1.由 ID 反查母批 LotNo + // ★同一载具上可能同时存在多笔 STATE=1 明细:依载具分批出站后,片(PRODUCTTYPE=0)的明细列 + // 仍挂在已分批结批消耗的母批上,与新子批的颗明细共存于同一 CARRIERID。 + // 若不加区别地取第一笔,可能取到已结批的批号(Oracle 不保证回传顺序), + // 下一步在 TBLWIPLOTSTATE 便查无该批而退回标准流程,现象即为「解绑逻辑触发不了」, + // 且随着该载具每次成功解绑而累积残留列,失败机率愈来愈高。 + // 故此处 inner join TBLWIPLOTSTATE 只取仍在制的批,并明确排序确保结果稳定。 + string strSQL; + string strIdCond = Type == "2" + ? $"P.CARRIERID = '{strCarrierID_Auto}'" + : $"P.PRODUCTID = '{strProductID_Auto}'"; + strSQL = $@"select distinct P.LOTNO as LotNo from TBLWIPPRDSTATE_LQ P inner join TBLWIPLOTSTATE S on S.LOTNO = P.LOTNO where {strIdCond} and P.STATE = 1 order by 1"; + DataTable dtLot = new DataTable(); + ExecuteSQLQuery_Adapter(strSQL, dtLot, cnnTemp); + if (dtLot.Rows.Count == 0) + { + // 找不到明细,交回标准流程;留下讯息供现场判读,否则此处静默退出无从追查 + clsERP.combineMessage(ref aryMessage, mmsg: (Type == "2" ? strCarrierID_Auto : strProductID_Auto) + "[%:在TBLWIPPRDSTATE_LQ查无仍在制的在制明细(STATE=1),不执行自动解绑,按标准流程出站%]"); + return true; + } + string strMLotNo = dtLot.Rows[0]["LotNo"].ToString(); + if (dtLot.Rows.Count > 1) + { + // 对应到多个仍在制的生产批属资料异常;取排序后第一笔续行,并留下讯息供现场厘清,不静默带过 + string strLots = ""; + foreach (DataRow rLot in dtLot.Rows) + strLots += (strLots == "" ? "" : ",") + rLot["LotNo"].ToString(); + clsERP.combineMessage(ref aryMessage, mmsg: (Type == "2" ? strCarrierID_Auto : strProductID_Auto) + "[%:对应到多个在制生产批%](" + strLots + ")[%,已取%]" + strMLotNo + "[%续行,请确认明细资料%]"); + } + + // 2.取母批在制信息 + DataTable dtSt = new DataTable(); + strSQL = $"SELECT A.OPNO,A.LOTSTAMP,A.CURQTY,A.CURUNITNO,A.LOTSERIAL,B.PRODUCTNO,B.PRODUCTVERSION FROM TBLWIPLOTSTATE A LEFT JOIN TBLWIPLOTBASIS B ON A.LOTNO = B.BASELOTNO WHERE A.LOTNO = '{strMLotNo}'"; + ExecuteSQLQuery_Adapter(strSQL, dtSt, cnnTemp); + if (dtSt.Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:在TBLWIPLOTSTATE查无该批在制资料,不执行自动解绑,按标准流程出站%]"); + return true; + } + string strOPNO = dtSt.Rows[0]["OPNO"].ToString(); + long lngLotStamp = Conversions.ToLong(dtSt.Rows[0]["LOTSTAMP"].ToString()); + string strUnitNo = dtSt.Rows[0]["CURUNITNO"].ToString(); + string strProductNo = dtSt.Rows[0]["PRODUCTNO"].ToString(); + string strProductVersion = dtSt.Rows[0]["PRODUCTVERSION"].ToString(); + + // 3.读作业站属性(M7 存在即生效)+ M8 互斥 + bool blnAutoTray = funOPPropertyExists_LQ(strOPNO, "自动解绑TRAY", cnnTemp); + bool blnUnitUnbind = funOPPropertyExists_LQ(strOPNO, "unit出站解绑载具", cnnTemp); + if (blnAutoTray && blnUnitUnbind) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%本作业站同时设定【自动解绑TRAY】与【unit出站解绑载具】,请择一%]"); + return false; + } + if (!blnAutoTray && !blnUnitUnbind) + { + // 无属性,走标准流程;留下讯息指明查的是哪一站,便于现场核对作业站属性维护 + clsERP.combineMessage(ref aryMessage, mmsg: strOPNO + "[%:未设定【自动解绑TRAY】或【unit出站解绑载具】属性,不执行自动解绑,按标准流程出站%]"); + return true; + } + + bool blnByCarrier = blnAutoTray; // true=一 carrier 一批(解绑TRAY);false=一 unit 一批(解绑小载具) + + // 4.B1 防呆:一 carrier 一批时,存在未绑载具单位则挡下(否则 Σ子批≠CurQty) + if (blnByCarrier) + { + DataTable dtNoCar = new DataTable(); + ExecuteSQLQuery_Adapter($"select count(*) as CNT from TBLWIPPRDSTATE_LQ where LotNo='{strMLotNo}' and producttype=1 and state=1 and (carrierid is null or carrierid='')", dtNoCar, cnnTemp); + if (dtNoCar.Rows.Count > 0 && decimal.Parse(dtNoCar.Rows[0]["CNT"].ToString()) > 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%存在未绑定载具的单位,不可出站%]"); + return false; + } + } + + // 5.分组(carrier / unit) + DataTable dtGroup = new DataTable(); + if (blnByCarrier) + ExecuteSQLQuery_Adapter($"select carrierid as KEYID, count(*) as CNT from TBLWIPPRDSTATE_LQ where LotNo='{strMLotNo}' and producttype=1 and state=1 group by carrierid", dtGroup, cnnTemp); + else + ExecuteSQLQuery_Adapter($"select productid as KEYID, 1 as CNT from TBLWIPPRDSTATE_LQ where LotNo='{strMLotNo}' and producttype=1 and state=1", dtGroup, cnnTemp); + if (dtGroup.Rows.Count == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:查无PRODUCTTYPE=1且STATE=1的在制明细,无法分批,不执行自动解绑,按标准流程出站%]"); + return true; + } + + // 6.取子批号(整批拆分,不含母批;母批以分批結批消耗) + List lstSubLot = new List(); + using (kcSYS.clsSYSEng objSYSEng = new kcSYS.clsSYSEng()) + { + for (int k = 0; k < dtGroup.Rows.Count; k++) + lstSubLot.Add(objSYSEng.GetSplitLotNo(true, strMLotNo, "")); + } + + // 7.建分批表 + DataTable dtSplitLot = new DataTable("SplitLot"); + dtSplitLot.Columns.Add("SplitLotNo", typeof(string)); + dtSplitLot.Columns.Add("SplitLotQty", typeof(decimal)); + dtSplitLot.Columns.Add("SplitSysQty", typeof(decimal)); + dtSplitLot.Columns.Add("Action", typeof(int)); + dtSplitLot.Columns.Add("NodeID", typeof(string)); + dtSplitLot.Columns.Add("ReturnType", typeof(int)); + dtSplitLot.Columns.Add("FromProductNo", typeof(string)); + dtSplitLot.Columns.Add("FromProductVersion", typeof(string)); + dtSplitLot.Columns.Add("ProductNo", typeof(string)); + dtSplitLot.Columns.Add("ProductVersion", typeof(string)); + dtSplitLot.Columns.Add("UnitNo", typeof(string)); + dtSplitLot.Columns.Add("OPNo", typeof(string)); + dtSplitLot.Columns.Add("KeyId", typeof(string)); + for (int k = 0; k < dtGroup.Rows.Count; k++) + { + DataRow dr = dtSplitLot.NewRow(); + dr["SplitLotNo"] = lstSubLot[k]; + dr["SplitLotQty"] = dtGroup.Rows[k]["CNT"]; + dr["SplitSysQty"] = dtGroup.Rows[k]["CNT"]; + dr["Action"] = 0; + dr["NodeID"] = ""; + dr["ReturnType"] = 0; + dr["FromProductNo"] = strProductNo; + dr["FromProductVersion"] = strProductVersion; + dr["ProductNo"] = strProductNo; + dr["ProductVersion"] = strProductVersion; + dr["UnitNo"] = strUnitNo; + dr["OPNo"] = strOPNO; + dr["KeyId"] = dtGroup.Rows[k]["KEYID"].ToString(); + dtSplitLot.Rows.Add(dr); + } + + // 8.执行分批(kernel;整批拆分,母批消耗结批) + // SplitType 必须为 1(BR分批):kc 註明「若是BR則分批完成,Status要變更為4」, + // 子批 Status=4 才允许後續 BRTransferLot_Bin_M(否则 0000-203033)。SplitType=0 是站中手動分批,不變更狀態。 + using (kcWIP.clsLot objLot = new kcWIP.clsLot()) + { + // LinkName 必须传 "PASS":子批 LINKNAME 若留空,後續 TransferLot_Bin_M 会以空字串去 GetNextBR, + // 查无下一个 BR 而报「Next BR is not exist」。传 PASS 不影响 Status(仅 HOLD/WAIT 走别的分支)。 + objLot.BR_Manual_LotSplit(lngLotStamp, strMLotNo, 1, UserNo, dtSplitLot, LinkName: "PASS"); + } + + // 9.明细更新(carrier:清 TRAYID 留 carrierid;unit:清 carrierid/LOCATIONNO) + Collection CollectionSQL = new Collection(); + // TBLPCSDIELOG_LQ 的两种比对键分开收集:PANLEID 是整片 panel 一起更新(粗), + // UNITID 只动一颗(精确)。粗的先执行、精确的后执行,同一片 panel 的单位分散在 + // 不同载具(=不同子批)时,才不会被 panel 那笔回头盖掉。 + Collection colDiePanel = new Collection(); + Collection colDieUnit = new Collection(); + bool blnPanelCloned = false; // 有补过子批片明细才需要让母批片明细退场 + Dictionary dicTrayCarrier = new Dictionary(); + foreach (DataRow dr in dtSplitLot.Rows) + { + string strSubLot = dr["SplitLotNo"].ToString(); + string strKey = dr["KeyId"].ToString(); + string strSubOP = strOPNO; + DataTable dtSub = new DataTable(); + ExecuteSQLQuery_Adapter($"select OPNO from tblwiplotstate where LotNo='{strSubLot}'", dtSub, cnnTemp); + if (dtSub.Rows.Count > 0) strSubOP = dtSub.Rows[0]["OPNO"].ToString(); + + if (blnByCarrier) + { + // 明细须锁定母批:同一载具上若有其他批的残留单位,未锁批会被一并改挂到子批 + DataTable dtCar = new DataTable(); + ExecuteSQLQuery_Adapter($"select TRAYID from TBLWIPPRDSTATE_LQ where carrierid='{strKey}' and producttype=1 and state=1 and lotno='{strMLotNo}'", dtCar, cnnTemp); + if (dtCar.Rows.Count > 0) + { + // 取第一个非空 TRAYID(不可用 Rows[0],该列 TRAYID 可能为空而漏掉整段解绑) + string strTray = ""; + foreach (DataRow rTray in dtCar.Rows) + { + string strTmpTray = rTray["TRAYID"].ToString(); + if (!string.IsNullOrEmpty(strTmpTray)) { strTray = strTmpTray; break; } + } + if (!string.IsNullOrEmpty(strTray) && !dicTrayCarrier.ContainsKey(strKey)) dicTrayCarrier.Add(strKey, strTray); + } + // 子批号等于母批号代表未真正分批,补片明细会变成自我复制,故略过 + bool blnDoPanel = strSubLot != strMLotNo; + + // 颗明细改挂前先补履历(来源列此时仍在母批上) + if (blnDoPanel) funAddUnitLogForSubLot_LQ(strMLotNo, strSubLot, strSubOP, strKey, CollectionSQL); + + CollectionSQL.Add($"update tblwipprdstate_LQ set lotno='{strSubLot}', opno='{strSubOP}', TRAYID='', TRAYPOSITION='' where carrierid='{strKey}' and producttype='1' and state='1' and lotno='{strMLotNo}'"); + + // 片明细依子批各补一笔 + if (blnDoPanel) + { + funAddPanelRowsForSubLot_LQ(strMLotNo, strSubLot, strSubOP, strKey, CollectionSQL, cnnTemp); + blnPanelCloned = true; + } + + // 同步产品履历表 TBLPCSDIELOG_LQ 的批号与作业站: + // 依该载具下每列的 PRODUCTTYPE 决定比对键——0=Panel 用 PANLEID,1=Unit 用 UNITID + DataTable dtDie = new DataTable(); + ExecuteSQLQuery_Adapter($"select PRODUCTID, PRODUCTTYPE from TBLWIPPRDSTATE_LQ where carrierid='{strKey}' and state=1 and lotno='{strMLotNo}'", dtDie, cnnTemp); + foreach (DataRow rDie in dtDie.Rows) + { + bool blnPanel = rDie["PRODUCTTYPE"].ToString() == "0"; + string strKeyCol = blnPanel ? "PANLEID" : "UNITID"; + string strDieSQL = $"update TBLPCSDIELOG_LQ set LOTNO='{strSubLot}', OPNO='{strSubOP}' where {strKeyCol}='{rDie["PRODUCTID"]}'"; + if (blnPanel) colDiePanel.Add(strDieSQL); else colDieUnit.Add(strDieSQL); + } + } + else + { + CollectionSQL.Add($"update tblwipprdstate_LQ set lotno='{strSubLot}', opno='{strSubOP}', carrierid=null, LOCATIONNO=null where productid='{strKey}' and producttype='1' and state='1'"); + + // 同步产品履历表 TBLPCSDIELOG_LQ:一 unit 一批,分组键即 UNITID + colDieUnit.Add($"update TBLPCSDIELOG_LQ set LOTNO='{strSubLot}', OPNO='{strSubOP}' where UNITID='{strKey}'"); + } + } + // 先粗后精:panel 层全部更新完,再让 unit 层逐颗覆写成各自子批 + foreach (string s in colDiePanel) CollectionSQL.Add(s); + foreach (string s in colDieUnit) CollectionSQL.Add(s); + + // 母批片明细退场:必须排在所有子批片明细 insert 之后(那些 insert 以这些列为来源) + if (blnPanelCloned) + { + CollectionSQL.Add($"update TBLWIPPRDSTATE_LQ set STATE=0 where lotno='{strMLotNo}' and producttype='0' and state=1"); + } + + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + // 10.carrier:解绑TRAY + 寿命门槛(M6) + if (blnByCarrier) + { + foreach (KeyValuePair kv in dicTrayCarrier) + funUnbindTrayLife_LQ(kv.Key, kv.Value, UserNo, strDataBaseType, strConnectionString, cnnTemp); + } + + // 11.逐子批出站转移(BRTransferLot_Bin_M 内含隐藏站规则 —— M11)。 + // 子批 Status 已由步骤 8 的 BR 分批(SplitType=1)置为 4,此处直接转移;比照母本 clsEAP.cs:2975→2987。 + foreach (DataRow dr in dtSplitLot.Rows) + { + string strSubLot = dr["SplitLotNo"].ToString(); + string strComputerName = System.Net.Dns.GetHostName(); + + BRTransferLot_Bin_M(strSubLot, UserNo, "PASS", 0, defString, ComputerName: strComputerName, RuleMsg: ""); + } + + clsERP.combineMessage(ref aryMessage, mmsg: strMLotNo + "[%:出站并自动解绑成功%]"); + bolHandled = true; + return true; + } + catch (Exception ex) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%自动解绑出站失败%]:" + ex.Message); + return false; + } + finally + { + CloseConnection(cnnTemp); + } + } + + // 17单(内联,EAItc 不引用 MEStc_LQ):依载具分批时,片(PRODUCTTYPE=0)明细依子批各补一笔 + // 现况列 + 一笔履历列。★片与颗的对应以产品履历 TBLPCSDIELOG_LQ 的 PANLEID/UNITID 为准, + // 不可直接沿用载具上的片列——同一载具的片未必与该载具的颗同片,而同一片的颗又会散落到不同子批。 + // ★母批原片列的退场(STATE=0)由呼叫端在所有子批处理完后统一执行:先退场会让后续子批取不到来源列。 + // 与 MEStc_LQ.clsWIP.funAddPanelRowsForSubLot_LQ 等价,履历写入比照 14 单既有模式。 + private static void funAddPanelRowsForSubLot_LQ(string LotNo, string strSubLot, string strSubOP, + string strCarrierId, Collection colSQL, IDbConnection cnnTemp) + { + DataTable dtPanel = new DataTable(); + ExecuteSQLQuery_Adapter($"select distinct D.PANLEID from TBLPCSDIELOG_LQ D where D.UNITID in (select PRODUCTID from TBLWIPPRDSTATE_LQ where carrierid='{strCarrierId}' and producttype='1' and state='1' and lotno='{LotNo}')", dtPanel, cnnTemp); + + foreach (DataRow drPanel in dtPanel.Rows) + { + string strPanelId = drPanel["PANLEID"].ToString(); + if (string.IsNullOrEmpty(strPanelId)) continue; + + colSQL.Add($"insert into TBLWIPPRDSTATE_LQ (LOTNO,PRODUCTID,EQPID,STATE,OPNO,CARRIERID,PRODUCTTYPE,CREATEDATE,TRAYID,TRAYPOSITION) select '{strSubLot}',PRODUCTID,EQPID,1,'{strSubOP}',CARRIERID,PRODUCTTYPE,SYSDATE,'','' from TBLWIPPRDSTATE_LQ where lotno='{LotNo}' and productid='{strPanelId}' and producttype='0' and state=1"); + colSQL.Add($"insert into TBLWIPPRDLOG_LQ (LOTNO,PRODUCTID,EQPID,OPNO,CARRIERID,PRODUCTTYPE,CREATEDATE) select '{strSubLot}',PRODUCTID,EQPID,'{strSubOP}',CARRIERID,PRODUCTTYPE,SYSDATE from TBLWIPPRDSTATE_LQ where lotno='{LotNo}' and productid='{strPanelId}' and producttype='0' and state=1"); + } + } + + // 17单(内联):颗明细改挂子批时补一笔履历。★必须在颗明细被 update 改挂之前加入集合。 + private static void funAddUnitLogForSubLot_LQ(string LotNo, string strSubLot, string strSubOP, + string strCarrierId, Collection colSQL) + { + colSQL.Add($"insert into TBLWIPPRDLOG_LQ (LOTNO,PRODUCTID,EQPID,OPNO,CARRIERID,PRODUCTTYPE,CREATEDATE) select '{strSubLot}',PRODUCTID,EQPID,'{strSubOP}',CARRIERID,PRODUCTTYPE,SYSDATE from TBLWIPPRDSTATE_LQ where lotno='{LotNo}' and carrierid='{strCarrierId}' and producttype='1' and state=1"); + } + + } + + +} diff --git a/MESEAI/EAItc/clsERP.cs b/MESEAI/EAItc/clsERP.cs new file mode 100644 index 0000000..6836851 --- /dev/null +++ b/MESEAI/EAItc/clsERP.cs @@ -0,0 +1,4172 @@ +using iMESCIO.SCI.SMES.Request; +using iMESCIOC.Request.EAP; +using iMESCIOC.Request.WMS_Request; +using iMESCore.Base; +using iMESCore.DataBase; +using iMESCore.DataBase; +using iMESCore.Settings; +using iMESCore.Settings; +using kcOE; +using kcSYS; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.ApplicationServices; +using Microsoft.VisualBasic.CompilerServices; +using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Engines; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math; +using Org.BouncyCastle.Math.EC; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities.Encoders; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Xml; +using static iMESCore.Base.iMESComXML; +using static iMESCore.Base.iMESConst; +using static iMESCore.DataBase.iMESSql; + +namespace tcEAI_C +{ + public class clsERP + { + #region --- Combine (Exception, Message) --- + + public static bool combineException(ref List strException, string code = null, string sysmsg = null, string mesmsg = null, string stack = null) + { + bool result = false; + try + { + var al = new ArrayList(); + al.Add(code); + al.Add(sysmsg); + al.Add(mesmsg); + al.Add(stack); + strException.Add(al); + result = true; + } + catch (Exception ex) + { + result = false; + } + + return default(bool); + + } + + public static bool combineMessage(ref List strMessage, string mcode = null, string mtype = null, string mmsg = null) + { + bool result = false; + try + { + var al = new ArrayList(); + al.Add(mcode); + al.Add(mtype); + al.Add(mmsg); + strMessage.Add(al); + result = true; + } + catch (Exception ex) + { + result = false; + } + + return default(bool); + } + + public static bool combineFileMessage(ref List aryFileMessage, string mmsg) + { + bool result = false; + + try + { + var al = new ArrayList(); + al.Add(mmsg); + aryFileMessage.Add(al); + result = true; + } + catch (Exception ex) + { + result = false; + } + + return result; + } + #endregion + + + #region "add by 14166 for 加密接口" + + /// + /// 检查用户 + /// + /// + /// + /// + /// + /// + public static string funCheckUser(string UserNo, string UserPassword) + { + string funCheckUserRet = default(string); + funCheckUserRet = "fail"; + + AppSettings objSetting = new AppSettings(); + + DbDataReader drTemp = null; + IDbConnection cnnTemp = null; + string strSQL = ""; + + var objSYS = new kcSYS.clsSYSFunction(); + + string PasswordDecoding = "";//接口传入密码 + string sysPassword = "";//MES系统绑定DS密码 + + try + { + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); // Create connection + + strSQL = " select PASSWORD from tblusruserbasis where userno='" + UserNo + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + sysPassword = drTemp["PASSWORD"].ToString(); + } + else + { + throw new iMESException.MESException("0000-202001", "[%UserNo%] : " + "DS"); + } + drTemp.Close(); + + + + sysPassword = objSYS.PasswordDecoding(sysPassword); + + + //SM2解密 + // 生成密钥对 + + string privateKey = "Ja4UIUJz7XRNDhIiuWXwL78qd1Pc7SC0/Z9LzyF4SL8="; + //string publicKey = "BGe1BZDFN+NhCQtc2qlVk8nUlXrIwcyjT3mMt7Xx3BkDNBGBQjFPV0+h3/cGUYXo2TFI1SShS7hWl9zi6SxUHvg="; + + //解密 + PasswordDecoding = Decrypt(UserPassword, privateKey); + + + if (sysPassword != PasswordDecoding) + { + throw new iMESException.MESException("", "用户:" + UserNo + "权限校验失败"); + } + + //if (strException.Count > 0) + // goto exitfun; + + + funCheckUserRet = "success"; + + + //exitfun: + ; + + } + catch (Exception ex) + { + throw; + //clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%CheckUserFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + + finally + { + CloseConnection(cnnTemp); + } + return funCheckUserRet; + + + } + + + + /// + /// 生成 SM2 密钥对,密钥对使用 Base64 进行编码 + /// + /// + /// + public static void GenerateSM2KeyPair(out string privateKey, out string publicKey) + { + // 获取 SM2 曲线参数 + X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1"); + KeyGenerationParameters parameters = new ECKeyGenerationParameters(new ECDomainParameters(curve), new SecureRandom()); + + // 创建 SM2 密钥对生成器 + ECKeyPairGenerator generator = new ECKeyPairGenerator(); + generator.Init(parameters); + + // 创建密钥对 + var keyPair = generator.GenerateKeyPair(); + + // 私钥 + ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters)keyPair.Private; + privateKey = Base64.ToBase64String(privateKeyParameters.D.ToByteArrayUnsigned()); + + // 公钥 + ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters)keyPair.Public; + publicKey = Base64.ToBase64String(publicKeyParameters.Q.GetEncoded()); + } + + + /// + /// SM2公钥加密 + /// + /// + /// + /// + public static string Encrypt(string strs, string publicKey) + { + //获取SM2曲线参数 + X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1"); + + ECPoint q = curve.Curve.DecodePoint(Convert.FromBase64String(publicKey)); + ECDomainParameters domainParameters = new ECDomainParameters(curve); + ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters("EC", q, domainParameters); + + //创建SM2加密器 + SM2Engine engine = new SM2Engine(); + engine.Init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom())); + + //把待加密的字符串转换成字节数组 + byte[] bytes = Encoding.UTF8.GetBytes(strs); + + //执行加密 + byte[] result = engine.ProcessBlock(bytes, 0, bytes.Length); + + //将加密结果转换成Base64字符串,并返回 + return Convert.ToBase64String(result); + } + + /// + /// SM2私钥解密 + /// + /// + /// + /// + public static string Decrypt(string strs, string privateKey) + { + + try + { + //获取SM2曲线参数 + X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1"); + + ECDomainParameters domainParameters = new ECDomainParameters(curve); + BigInteger bigInteger = new BigInteger(1, Convert.FromBase64String(privateKey)); + ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(bigInteger, domainParameters); + + //创建SM2解密器 + SM2Engine engine = new SM2Engine(); + engine.Init(false, privateKeyParameters); + + //把待解密的Base64字符串转换成字节数组 + byte[] bytes = Convert.FromBase64String(strs); + + //执行解密 + byte[] result = engine.ProcessBlock(bytes, 0, bytes.Length); + + //将解密结果转换成字符串,并返回 + return Encoding.UTF8.GetString(result); + } + catch (FormatException) + { + throw new ArgumentException("Base64格式无效", nameof(strs)); + } + catch (Exception ex) + { + // 其他所有异常包装后重新抛出 + throw new InvalidOperationException($"SM2解密失败: {ex.Message}", ex); + } + + //try + //{ + // // 获取SM2曲线参数 + // var curve = ECNamedCurveTable.GetByName("sm2p256v1"); + // var domainParameters = new ECDomainParameters(curve); + + // var privateKeyBytes = Convert.FromBase64String(_privateKey); + // var bigInteger = new BigInteger(1, privateKeyBytes); + // var privateKeyParameters = new ECPrivateKeyParameters(bigInteger, domainParameters); + + // // 创建SM2解密器 + // using var engine = new SM2Engine(); + // engine.Init(false, privateKeyParameters); + + // // 解密 + // var encryptedBytes = Convert.FromBase64String(encryptedText); + // var resultBytes = engine.ProcessBlock(encryptedBytes, 0, encryptedBytes.Length); + + // return Encoding.UTF8.GetString(resultBytes); + //} + //catch (FormatException) + //{ + // throw new ArgumentException("Base64格式无效", nameof(encryptedText)); + //} + //catch (Exception ex) + //{ + // // 记录日志 + // LogError($"SM2解密失败: {ex.Message}"); + // throw new CryptographicException("解密过程中发生错误", ex); + //} + + + } + + + + + + + + #endregion + + public static bool addTransactionLog_ErrorCode(string TransactionID, string ModuleID, string FunctionID, string ComputerName, string CurUserNo, string SendTime, string Result, string KeyValue, List strMessage, List strException, string InXml, string OutXml, string ExceptionFun, int KeepDays, int KeepXML, string ErrorCode = "0000-999999", string LogClass = null) + { + bool r = false; + var CollectionSQL = new Collection(); + + try + { + AppSettings objSetting = new AppSettings(); + // 2017/12/06 OwenLiu, mantis:0042964 修正ERP交易紀錄刪除舊資料因時間不同步造成的問題 + var datEventTime = DateTime.Now; + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + List> parameters = new List>(); + List pars1 = new List(); + List pars2 = new List(); + + parameters.Add(pars1); + + // Transaction(ID) + string g = Guid.NewGuid().ToString(); + // 2022/12/2,Ning,122356: 台基---erp交易记录无法查询 + g = g.Replace(Constants.vbNullChar, ""); + + + if (TransactionID == null) + pars1.Add(new clsDbParameter("TransactionID", DBNull.Value)); + else + pars1.Add(new clsDbParameter("TransactionID", TransactionID)); + if (ModuleID == null) + pars1.Add(new clsDbParameter("ModuleID", DBNull.Value)); + else + pars1.Add(new clsDbParameter("ModuleID", ModuleID)); + if (FunctionID == null) + pars1.Add(new clsDbParameter("FunctionID", DBNull.Value)); + else + pars1.Add(new clsDbParameter("FunctionID", FunctionID)); + if (ComputerName == null) + pars1.Add(new clsDbParameter("ComputerName", DBNull.Value)); + else + pars1.Add(new clsDbParameter("ComputerName", ComputerName)); + if (CurUserNo == null) + pars1.Add(new clsDbParameter("CurUserNo", DBNull.Value)); + else + pars1.Add(new clsDbParameter("CurUserNo", CurUserNo)); + if (SendTime == null || !Information.IsDate(SendTime)) + pars1.Add(new clsDbParameter("SendTime", DBNull.Value)); + else + pars1.Add(new clsDbParameter("SendTime", Convert.ToDateTime(SendTime))); + if (Result == null) + pars1.Add(new clsDbParameter("Result", DBNull.Value)); + else + pars1.Add(new clsDbParameter("Result", Result)); + if (KeyValue == null) + pars1.Add(new clsDbParameter("KeyValue", DBNull.Value)); + else + pars1.Add(new clsDbParameter("KeyValue", KeyValue)); + + // 2017/12/06 OwenLiu, mantis:0042964 修正ERP交易紀錄刪除舊資料因時間不同步造成的問題 + pars1.Add(new clsDbParameter("CreateDate", datEventTime)); + + if (LogClass == null) + pars1.Add(new clsDbParameter("LogClass", DBNull.Value)); + else + pars1.Add(new clsDbParameter("LogClass", LogClass)); + if (Result != null && Result.ToUpper() == "SUCCESS") + pars1.Add(new clsDbParameter("ErrorCode", DBNull.Value)); + else + pars1.Add(new clsDbParameter("ErrorCode", ErrorCode)); + if (Result != null && Result.ToUpper() == "SUCCESS") + pars1.Add(new clsDbParameter("ErrorType", DBNull.Value)); + else if (ErrorCode == "0000-999999") + pars1.Add(new clsDbParameter("ErrorType", 2)); + else + pars1.Add(new clsDbParameter("ErrorType", 1)); + + CollectionSQL.Add("insert into tblERPTransactionLog(id,transactionid,moduleid,functionid,computername,curuserno,sendtime,result,keyvalue,createdate,logclass,errorcode,errortype) " + + "values('" + g + "',:TransactionID, :ModuleID, :FunctionID, :ComputerName, :CurUserNo, :SendTime, :Result, :KeyValue, :CreateDate, :LogClass, :ErrorCode, :ErrorType)"); + + // ----- Transaction XML Log 組參數----- + if (KeepXML != 0) + { + parameters.Add(pars2); + + if (strMessage.Count == 0) + { + pars2.Add(new clsDbParameter("Message", DBNull.Value)); + } + else + { + // mcode, mtype, mmsg + string str = string.Empty; + foreach (ArrayList al in strMessage) + { + // 2018/05/10 OwenLiu, 調整TransactionLog針對 ArrayList處理邏輯,以便與中台EAI共用 + if (!string.IsNullOrEmpty(str)) + str += Convert.ToString(ControlChars.Cr); + if (!string.IsNullOrEmpty(Convert.ToString(al[0]))) + { + str = str + "mcode: " + al[0] + ";".ToString(); + } + if (!string.IsNullOrEmpty(Convert.ToString(al[0]))) + { + str = str + "mtype: " + al[1] + ";".ToString(); + } + // str += "mmsg: " & al.Item(2) + if (!string.IsNullOrEmpty(Convert.ToString(al[0]))) + { + str = str + "mmsg: " + al[2] + ";".ToString(); + } + } + pars2.Add(new clsDbParameter("Message", str)); + } + + if (strException.Count == 0) + { + pars2.Add(new clsDbParameter("Exception", DBNull.Value)); + } + else + { + // code, sysmsg, mesmsg, stack + string str = string.Empty; + foreach (ArrayList al in strException) + { + // 2018/05/10 OwenLiu, 調整TransactionLog針對 ArrayList處理邏輯,以便與中台EAI共用 + if (!string.IsNullOrEmpty(str)) + str += Convert.ToString(ControlChars.Cr); + if (!string.IsNullOrEmpty(Convert.ToString(al[0]))) + { + str = str + "code: " + al[0] + ";".ToString(); + } + if (!string.IsNullOrEmpty(Convert.ToString(al[1]))) + { + str = str + "sysmsg: " + al[1] + ";".ToString(); + } + if (!string.IsNullOrEmpty(Convert.ToString(al[2]))) + { + str = str + "mesmsg: " + al[2].ToString().Replace("[%", "").Replace("%]", "") + ";"; + } + if (!string.IsNullOrEmpty(Convert.ToString(al[3]))) + { + str = str + "stack: " + al[3].ToString(); + } + } + pars2.Add(new clsDbParameter("Exception", str)); + } + + if (InXml == null) + pars2.Add(new clsDbParameter("InXml", DBNull.Value)); + else + pars2.Add(new clsDbParameter("InXml", InXml)); + if (OutXml == null) + pars2.Add(new clsDbParameter("OutXml", DBNull.Value)); + else + pars2.Add(new clsDbParameter("OutXml", OutXml)); + if (ExceptionFun == null) + pars2.Add(new clsDbParameter("ExceptionFun", DBNull.Value)); + else + pars2.Add(new clsDbParameter("ExceptionFun", ExceptionFun)); + + // -----執行Transaction XML Log----- + CollectionSQL.Add("insert into tblERPTransactionXMLLog(id,messagexml,exceptionxml,inxml,outxml,exceptionfun) values('" + g + + "',:Message, :Exception, :InXml, :OutXml, :ExceptionFun)"); + } + ExecuteSQLNoneQuery_UPD_Parameter(strDataBaseType, strConnectionString, CollectionSQL, parameters); + + r = true; + } + + catch (Exception ex) + { + r = false; + throw; + } + + return r; + } + + + #region-----------add by 14166 for 新增人员接口----------- + /// + /// (ref strMessage, ref strException, UserNo, UserName, UserLevel, Creator, CreateDate, Description, IssueState, ChangeDate, ResetPassword, UserType, UserDP, UserEmail); + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool funAddUser(ref List aryMessage, ref List aryException, string UserNo = defString, string UserName = defString, string UserLever = defString, string Creator = defString, string CreateDate = defString, string Description = defString, string IssueState = defString, string ChangeDate = defString, string ResetPassword = defString, string UserType = defString, string UserDP = defString, string UserEmail = defString, string Password = defString) + { + bool result = false; + DataRow dr; + int i, j; + string strSQLAddField, strSQLAddValue; + Collection MTLCollection = new Collection(); + Collection CollectionSQL = new Collection(); + + + string strSQL = ""; + + IDbConnection cnnTemp = null; + DbDataReader drTemp; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + bool blnAdd = false; ; + string PasswordDecoding = ""; + try + { + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + //默认用户密码123 + using (var objsys = new clsSYSFunction()) + { + PasswordDecoding = objsys.PasswordEncoding(Password); + } + + try + { + strSQL = " SELECT * FROM TBLUSRUSERBASIS WHERE USERNO='" + UserNo + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + throw new iMESException.MESException("0000-003000", "[%UserNo : " + UserNo + "人员已存在!%]"); + } + else + { + blnAdd = true; + } + drTemp.Close(); + + // ----- Exception => Fail ----- + if (aryException.Count > 0) + goto exitfun; + + // Add + if (blnAdd) + { + strSQLAddField = " INSERT INTO TBLUSRUSERBASIS (USERNO,USERNAME,USERLEVEL,PASSWORD,DEPARTMENTNO,EMAILADDRESS,DESCRIPTION,USERTYPE,ISSUESTATE,RESETPASSWORD,CREATOR,CREATEDATE,CHANGEDATE"; + strSQLAddValue = " Values ('" + UserNo + "','" + UserName + "','" + UserLever + "','" + PasswordDecoding + "','" + UserDP + "','" + UserEmail + "','" + Description + "','" + UserType + "','" + IssueState + "','" + ResetPassword + "','" + Creator + "',To_Date('" + Strings.Format(Conversions.ToDate(CreateDate), "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),To_Date('" + Strings.Format(Conversions.ToDate(ChangeDate), "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')"; + + // 當沒有額外的欄位時,直接給定strSQL + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + + CollectionSQL.Add(strSQL); + + } + else + { + // Edit + //strSQL = " UPDATE TBLUSRUSERBASIS set USERNAME='" + UserName + "',USERLEVEL='" + UserLever + "',DEPARTMENTNO='" + UserDP + "',EMAILADDRESS='" + UserEmail + "' WHERE USERNO='" + UserNo + "' "; + strSQL = " UPDATE TBLUSRUSERBASIS set USERNAME='" + UserName + "',USERLEVEL='" + UserLever + "' WHERE USERNO='" + UserNo + "' "; + CollectionSQL.Add(strSQL); + + } + // 呼叫執行SQL指令 + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + result = true; + + //clsERP.combineMessage(ref aryMessage, null, null, "[%AddUserSuccess%]"); + } + catch (Exception ex) + { + // trans.Rollback() + clsERP.combineException(ref aryException, null, ex.Message, "[%AddUserFail%]", CInput(ex.StackTrace)); + } + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, null, ex.Message, "[%AddUserFail%]", CInput(ex.StackTrace)); + } + + exitfun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, null, ex.Message, "[%AddUserFail%]", CInput(ex.StackTrace)); + } + finally + { + CloseConnection(cnnTemp); + } + + + return result; + } + + + public static bool funDelUser(ref List aryMessage, ref List aryException, string UserNo = defString, string UserName = defString, string UserLever = defString, string Creator = defString, string CreateDate = defString, string Description = defString, string IssueState = defString, string ChangeDate = defString, string ResetPassword = defString, string UserType = defString, string UserDP = defString, string UserEmail = defString, string Password = defString) + { + bool result = false; + + Collection CollectionSQL = new Collection(); + + + string strSQL = ""; + + IDbConnection cnnTemp = null; + DbDataReader drTemp; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + + try + { + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + ////默认用户密码123 + //using (var objsys = new clsSYSFunction()) + //{ + // PasswordDecoding = objsys.PasswordEncoding(Password); + //} + + try + { + strSQL = " SELECT * FROM TBLUSRUSERBASIS WHERE USERNO='" + UserNo + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (!drTemp.Read()) + { + throw new iMESException.MESException("0000-003000", "[%UserNo : " + UserNo + "人员不存在!%]"); + } + drTemp.Close(); + + // ----- Exception => Fail ----- + if (aryException.Count > 0) + goto exitfun; + + + strSQL = "DELETE FROM TBLUSRUSERBASIS WHERE USERNO='" + UserNo + "' "; + CollectionSQL.Add(strSQL); + + // 呼叫執行SQL指令 + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + result = true; + + } + catch (Exception ex) + { + // trans.Rollback() + clsERP.combineException(ref aryException, null, ex.Message, "[%DelUserFail%]", CInput(ex.StackTrace)); + } + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, null, ex.Message, "[%DelUserFail%]", CInput(ex.StackTrace)); + } + + exitfun: + ; + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, null, ex.Message, "[%DelUserFail%]", CInput(ex.StackTrace)); + } + finally + { + CloseConnection(cnnTemp); + } + + + return result; + } + + + #endregion + + + + #region 辅料调拨接口 + + public static bool funAddMaterial_WIP(string SubInventoryTransferNo, string Description, string Creator, int Status, DateTime CreateDate = default(DateTime), DataTable dtMTL = null, List aryMessage = null, List aryException = null, List aryAlert = null) + { + bool AddMaterial_WIPRet = default(bool); + + bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp; + + AppSettings objSetting = new AppSettings(); + var CollectionSQL = new Collection(); + + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + try + { + if (dtMTL.Rows.Count > 0) + { + //status:0为发料,1为退料; + if (Status == 0) + { + foreach (DataRow row in dtMTL.Rows) + { + //若是同仓库编号、同物料编号、同物料批号,则数量进行叠加,若是其中一项不一样,则进行新增; + strSQL = " select * from TBLINVWIPINVENTORY_RAW where INVENTORYNO = '" + row["ToInventoryNo"] + "' and MATERIALNO = '" + row["MaterialNo"] + "' and MATERIALLOTNO = '" + row["MaterialLotNo"] + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + //叠加 + strSQL = " update TBLINVWIPINVENTORY_RAW set QTY = QTY + " + Convert.ToInt32(row["TransferQty"]) + " where INVENTORYNO = '" + row["ToInventoryNo"] + "' and MATERIALNO = '" + row["MaterialNo"] + "' and MATERIALLOTNO = '" + row["MaterialLotNo"] + "' "; + CollectionSQL.Add(strSQL); + } + else + { + //TBLMTLMATERIALBASIS + strSQL = " select * from TBLMTLMATERIALBASIS where MATERIALNO = '" + row["MaterialNo"] + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + //新增 + strSQL = " insert into TBLINVWIPINVENTORY_RAW(INVENTORYNO,MATERIALNO,MATERIALLOTNO,UNITNO,QTY,INPUTDATE,LOCATORNO,MATERIALTYPE) "; + strSQL += " values('" + row["ToInventoryNo"] + "','" + row["MaterialNo"] + "','" + row["MaterialLotNo"] + "','" + row["MaterialUnitNo"] + "'," + Convert.ToInt32(row["TransferQty"]) + ",To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'N/A','" + drTemp["MATERIALTYPE"] + "') "; + CollectionSQL.Add(strSQL); + } + else + { + combineException(ref aryException, mesmsg: "[%物料基本资料无相关信息%]"); + } + + } + + //记录调拨以及取消调拨记录 + strSQL = " insert into TBLINVWIPINVENTORY_RAWLOG(subinventorytransferno,materialno,materiallotno,transferqty,materialunitno,frominventoryno,fromlocatorno,toinventoryno,tolocatorno,description,creator,createdate,Status) "; + strSQL += " values('" + SubInventoryTransferNo + "','" + row["MaterialNo"] + "','" + row["MaterialLotNo"] + "'," + Convert.ToInt32(row["TransferQty"]) + ",'" + row["MaterialUnitNo"] + "','" + row["FromInventoryNo"] + "','" + row["FromLocatorNo"] + "','" + row["ToInventoryNo"] + "','" + row["ToLocatorNo"] + "','" + Description + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + Status + ") "; + CollectionSQL.Add(strSQL); + } + } + else if (Status == 1) + { + foreach (DataRow row in dtMTL.Rows) + { + //取消调拨:则直接扣减数量即可,若是扣减数量 > 库存数,则直接回复失败:库存不足; + strSQL = " select * from TBLINVWIPINVENTORY_RAW where INVENTORYNO = '" + row["FromInventoryNo"] + "' and MATERIALNO = '" + row["MaterialNo"] + "' and MATERIALLOTNO = '" + row["MaterialLotNo"] + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + if (Convert.ToInt32(row["TransferQty"]) > Convert.ToInt32(drTemp["QTY"])) + { + combineException(ref aryException, mesmsg: "[%库存不足%]"); + } + else + { + //扣减 + strSQL = " update TBLINVWIPINVENTORY_RAW set QTY = QTY - " + Convert.ToInt32(row["TransferQty"]) + " where INVENTORYNO = '" + row["FromInventoryNo"] + "' and MATERIALNO = '" + row["MaterialNo"] + "' and MATERIALLOTNO = '" + row["MaterialLotNo"] + "' "; + CollectionSQL.Add(strSQL); + + //记录调拨以及取消调拨记录 + strSQL = " insert into TBLINVWIPINVENTORY_RAWLOG(subinventorytransferno,materialno,materiallotno,transferqty,materialunitno,frominventoryno,fromlocatorno,toinventoryno,tolocatorno,description,creator,createdate,Status) "; + strSQL += " values('" + SubInventoryTransferNo + "','" + row["MaterialNo"] + "','" + row["MaterialLotNo"] + "'," + Convert.ToInt32(row["TransferQty"]) + ",'" + row["MaterialUnitNo"] + "','" + row["FromInventoryNo"] + "','" + row["FromLocatorNo"] + "','" + row["ToInventoryNo"] + "','" + row["ToLocatorNo"] + "','" + Description + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + Status + ") "; + CollectionSQL.Add(strSQL); + + } + + } + + } + } + } + else + { + combineException(ref aryException, mesmsg: "[%无调拨信息%]"); + } + + if (aryException.Count > 0) + goto exitfun; + + ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL); + r = true; + combineMessage(ref aryMessage, mmsg: "[%AddMaterial_WIPSuccess%]"); + } + + catch (Exception ex) + { + combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + + } + + exitfun: + ; + } + catch (Exception ex) + { + combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMaterial_WIPFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + CloseConnection(cnnTemp); + AddMaterial_WIPRet = r; + } + + return AddMaterial_WIPRet; + } + + #endregion + + #region MES箱号变更 + #endregion + + #region 湿敏接口 + #endregion + + #region MES退料 + #endregion + + #region "WMS发料回传前,先回传发料明细关联reel信息,datahub调用MES服务,推送发料明细数据至MES;" + public static bool funAddMaterial_WIP(string factory, DataTable dtReel) + { + bool funAddMaterial_WIP = default(bool); + bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp; + + AppSettings objSetting = new AppSettings(); + var CollectionSQL = new Collection(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataRow[] dataRows = null; + try + { + + if (dtReel.Rows.Count == 0) + { + throw new Exception("无明细数据!"); + } + + //先取出dtReel所有的MATERIALNO字段,拼接成IN语句 + string strMaterialNo = ""; + for (int i = 0; i <= dtReel.Rows.Count - 1; i++) + { + if (strMaterialNo == "") + { + strMaterialNo = "'" + dtReel.Rows[i]["MCODE"] + "'"; + } + else + { + strMaterialNo = strMaterialNo + ",'" + dtReel.Rows[i]["MCODE"] + "'"; + } + } + + strSQL = "SELECT MATERIALNO,MATERIALTYPE,UNITNO FROM TBLMTLMATERIALBASIS WHERE MATERIALNO IN (" + strMaterialNo + ") AND ISSUESTATE = 2"; + DataTable dtMaterial = new DataTable("TBLMTLMATERIALBASIS"); + ExecuteSQLQuery_Adapter(strSQL, dtMaterial, cnnTemp); + if (dtMaterial.Rows.Count == 0) + { + throw new Exception("MES无物料信息!"); + } + + + for (int i = 0; i <= dtReel.Rows.Count - 1; i++) + { + + //物料单位 + string strUnitNo = ""; + + dataRows = dtMaterial.Select("MATERIALNO = '" + dtReel.Rows[i]["MCODE"] + "'"); + if (dataRows.Length > 0) + { + strUnitNo = dataRows[0]["UNITNO"].ToString(); + } + else + { + throw new Exception($"{dtReel.Rows[i]["MCODE"]}找不到对应的物料信息!"); + } + + //数量 + decimal QTY = 0; + if (dtReel.Rows[i]["QTY"].ToString() != "") + { + QTY = Convert.ToDecimal(dtReel.Rows[i]["QTY"]); + } + + //物料类别 MATERIALTYPE 来着dtMaterial + string strMaterialType = ""; + if (dataRows.Length > 0) + { + strMaterialType = dataRows[0]["MATERIALTYPE"].ToString(); + } + + //输入时间 INPUTDATE 来着于 dtReel的MTIME,时间格式,orcal + DateTime InputDate = DateTime.Now; + if (dtReel.Rows[i]["MTIME"].ToString() != "") + { + //InputDate = Convert.ToDateTime(dtReel.Rows[i]["MDATE"]); + InputDate = DateTime.ParseExact(dtReel.Rows[i]["MDATE"].ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); + } + + ////制造日期 MANUFACTUREDATE 来着于 dtReel的VENDERDATE,时间格式 + DateTime ManufactureDate = ConvertYearWeekToMonday(dtReel.Rows[i]["VENDERDATE"].ToString()); + //if (dtReel.Rows[i]["VENDERDATE"].ToString() != "") + //{ + // ManufactureDate = Convert.ToDateTime(dtReel.Rows[i]["VENDERDATE"]); + //} + + + //超限日期 EXDATE + DateTime EXDATE = DateTime.Now; + if (dtReel.Rows[i]["EXDATE"].ToString() != "") + { + EXDATE = DateTime.ParseExact(dtReel.Rows[i]["EXDATE"].ToString(), "yyyyMMdd", CultureInfo.InvariantCulture); + } + string MONO = ""; + strSQL = $"SELECT * from TBLCUSMATERIALSUMDETAIL where MATERIALINNO = '{dtReel.Rows[i]["RECEIPTNO"].ToString()}'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + MONO = drTemp["MONO"].ToString(); + } + drTemp.Close(); + + ////插入 TBLINVWIPINVENTORY_RAW + //strSQL = @"INSERT INTO TBLINVWIPINVENTORY_RAW(INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,DATECODE,LOTCODE,VENDORCODE,VENDORITEMCODE,MANUFACTURER,SNSCALE) "; + //strSQL += " VALUES('" + dtReel.Rows[i]["STORAGECODE"].ToString() + "','" + dtReel.Rows[i]["MCODE"].ToString() + "','" + dtReel.Rows[i]["REELID"].ToString() + "', '" + strUnitNo + "'," + QTY + ",'" + strMaterialType + "','" + dtReel.Rows[i]["MTIME"].ToString() + + // "','"+ dtReel.Rows[i]["VENDERDATE"] + "','" + dtReel.Rows[i]["RECEIPTNO"].ToString() + "' ,'" + dtReel.Rows[i]["REELID"].ToString() + "',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + $"','YYYY/MM/DD HH24:MI:SS'),'{dtReel.Rows[i]["DATECODE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}','{dtReel.Rows[i]["VENDORCODE"].ToString()}','{dtReel.Rows[i]["VENDORITEMCODE"].ToString()}','{dtReel.Rows[i]["MANUFACTURER"].ToString()}','{dtReel.Rows[i]["SNSCALE"].ToString()}')"; + + //CollectionSQL.Add(strSQL); + + ////插入 TBLINVWIPINVENTORY_RAWLOG + //strSQL = @"INSERT INTO TBLINVWIPINVENTORY_RAWLOG(INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,EVENTTIME,DATECODE,LOTCODE,VENDORCODE,VENDORITEMCODE,MANUFACTURER,SNSCALE) "; + //strSQL += " VALUES('" + dtReel.Rows[i]["STORAGECODE"].ToString() + "','" + dtReel.Rows[i]["MCODE"].ToString() + "','" + dtReel.Rows[i]["REELID"].ToString() + "', '" + strUnitNo + "'," + QTY + ",'" + strMaterialType + "','"+ dtReel.Rows[i]["MTIME"].ToString() + + // "','"+ dtReel.Rows[i]["VENDERDATE"] + "','" + dtReel.Rows[i]["RECEIPTNO"].ToString() + "' ,'" + dtReel.Rows[i]["REELID"].ToString() + "',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + $"','YYYY/MM/DD HH24:MI:SS'),'{dtReel.Rows[i]["DATECODE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}','{dtReel.Rows[i]["VENDORCODE"].ToString()}','{dtReel.Rows[i]["VENDORITEMCODE"].ToString()}','{dtReel.Rows[i]["MANUFACTURER"].ToString()}','{dtReel.Rows[i]["SNSCALE"].ToString()}')"; + + //CollectionSQL.Add(strSQL); + + //插入 TBLINVWIPINVENTORY_RAW + strSQL = @"INSERT INTO TBLINVWIPINVENTORY_RAW(INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,DATECODE,LOTCODE,VENDORCODE,VENDORITEMCODE,MANUFACTURER,SNSCALE,VENDERLOTNO,EXPIREDATE,MONO) "; + strSQL += " VALUES('" + dtReel.Rows[i]["STORAGECODE"].ToString() + "','" + dtReel.Rows[i]["MCODE"].ToString() + "','" + dtReel.Rows[i]["REELID"].ToString() + "', '" + strUnitNo + "'," + QTY + ",'" + strMaterialType + "',To_Date('" + Strings.Format(InputDate, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + + ",To_Date('" + Strings.Format(ManufactureDate, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + dtReel.Rows[i]["RECEIPTNO"].ToString() + "' ,'" + dtReel.Rows[i]["REELID"].ToString() + + "',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + $"','YYYY/MM/DD HH24:MI:SS'),'{dtReel.Rows[i]["DATECODE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}','{dtReel.Rows[i]["VENDORCODE"].ToString()}','{dtReel.Rows[i]["VENDORITEMCODE"].ToString()}','{dtReel.Rows[i]["MANUFACTURER"].ToString()}','{dtReel.Rows[i]["SNSCALE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'"+MONO+"')"; + + CollectionSQL.Add(strSQL); + + //插入 TBLINVWIPINVENTORY_RAWLOG + strSQL = @"INSERT INTO TBLINVWIPINVENTORY_RAWLOG(INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,EVENTTIME,DATECODE,LOTCODE,VENDORCODE,VENDORITEMCODE,MANUFACTURER,SNSCALE,VENDERLOTNO,EXPIREDATE,MONO) "; + strSQL += " VALUES('" + dtReel.Rows[i]["STORAGECODE"].ToString() + "','" + dtReel.Rows[i]["MCODE"].ToString() + "','" + dtReel.Rows[i]["REELID"].ToString() + "', '" + strUnitNo + "'," + QTY + ",'" + strMaterialType + "',To_Date('" + Strings.Format(InputDate, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')" + + ",To_Date('" + Strings.Format(ManufactureDate, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + dtReel.Rows[i]["RECEIPTNO"].ToString() + "' ,'" + dtReel.Rows[i]["REELID"].ToString() + + "',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + $"','YYYY/MM/DD HH24:MI:SS'),'{dtReel.Rows[i]["DATECODE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}','{dtReel.Rows[i]["VENDORCODE"].ToString()}','{dtReel.Rows[i]["VENDORITEMCODE"].ToString()}','{dtReel.Rows[i]["MANUFACTURER"].ToString()}','{dtReel.Rows[i]["SNSCALE"].ToString()}','{dtReel.Rows[i]["VENDERLOTNO"].ToString()}',To_Date('" + Strings.Format(EXDATE, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'"+MONO+"')"; + + CollectionSQL.Add(strSQL); + + + + } + + if (CollectionSQL.Count > 0) + { + ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL); + } + + + + exitfun: + ; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + finally + { + CloseConnection(cnnTemp); + } + return funAddMaterial_WIP; + + } + + public static DateTime ConvertYearWeekToMonday(string yearWeek) + { + if (string.IsNullOrEmpty(yearWeek) || yearWeek.Length != 4) + throw new ArgumentException("输入格式必须为4位数字,前2位为年份,后2位为周数"); + + int year = int.Parse(yearWeek.Substring(0, 2)) + 2000; // 26 -> 2026 + int week = int.Parse(yearWeek.Substring(2, 2)); // 21 -> 21 + + return GetMondayOfWeek(year, week); + } + + /// + /// 获取指定年份第几周的周一日期 + /// + public static DateTime GetMondayOfWeek(int year, int week) + { + // 1. 计算该年1月1日 + DateTime jan1 = new DateTime(year, 1, 1); + + // 2. 计算1月1日所在周的周一 + int daysOffset = ((int)jan1.DayOfWeek + 6) % 7; // 周一=0, 周日=6 + DateTime firstMonday = jan1.AddDays(-daysOffset); + + // 3. 计算目标周周一(第1周从第一个周一开始) + DateTime targetMonday = firstMonday.AddDays((week - 1) * 7); + + return targetMonday; + } + #endregion + + + #region "SPC 接收数据" + + //计量 + public static bool funGetJLSPCData(ref List aryMessage, ref List aryException, string SPCSerial_QMS, string MaterialNo, string MTLVendor, string Employee, string LotNo, string OPNo, string QCItemNo, string DC, string PartNo, List listTestValue) + { + bool funGetJLSPCData = default(bool); + //bool r = false; + //string strSQL = default(string); + //IDbConnection cnnTemp = null; + //DbDataReader drTemp; + + AppSettings objSetting = new AppSettings(); + + + //string strDataBaseType = objSetting.GetDataBaseType(); + //string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + //cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + DataRow addrow; + DataRow addrow2; + string strReturn = ""; + + int intSerial; + + try + { + if (dsData.Tables.Contains("SPCData")) + { + dsData.Tables.Remove("SPCData"); + } + + dsData.Tables.Add("SPCData"); + dsData.Tables["SPCData"].Columns.Add("Execute", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("Result", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("LotNo", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("QCItemNo", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("Employee", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("OP", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("OpNo", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("ComponentNo", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("LotSerial", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("intResult", System.Type.GetType("System.String")); + + + dsData.Tables["SPCData"].Columns.Add("SPCSerial_QMS", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("Material", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("MTLVendor", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("DC", System.Type.GetType("System.String")); + dsData.Tables["SPCData"].Columns.Add("PartNo", System.Type.GetType("System.String")); + + + + + if (dsData.Tables.Contains("TestValue")) + { + dsData.Tables.Clear(); + } + else + { + dsData.Tables.Add("TestValue"); + dsData.Tables["TestValue"].Columns.Add("LotNo", System.Type.GetType("System.String")); + dsData.Tables["TestValue"].Columns.Add("QCItemNo", System.Type.GetType("System.String")); + dsData.Tables["TestValue"].Columns.Add("SerialNo", System.Type.GetType("System.Int32")); + dsData.Tables["TestValue"].Columns.Add("TestValue", System.Type.GetType("System.Double")); + dsData.Tables["TestValue"].Columns.Add("MEMO", System.Type.GetType("System.String")); + dsData.Tables["TestValue"].Columns.Add("ComponentNo", System.Type.GetType("System.String")); + dsData.Tables["TestValue"].Columns.Add("LotSerial", System.Type.GetType("System.String")); + } + + addrow = dsData.Tables["SPCData"].NewRow(); + addrow["Execute"] = "True"; + addrow["LotNo"] = LotNo; + addrow["QCItemNo"] = QCItemNo; + addrow["Employee"] = Employee; + addrow["OP"] = OPNo; + addrow["OpNo"] = OPNo; + addrow["LotSerial"] = 0; + //addrow["PartNo"] = PartNo; + addrow["SPCSerial_QMS"] = SPCSerial_QMS; + addrow["Material"] = MaterialNo; + addrow["MTLVendor"] = MTLVendor; + addrow["DC"] = DC; + addrow["PartNo"] = PartNo; + dsData.Tables["SPCData"].Rows.Add(addrow); + + intSerial = 0; + foreach (decimal TestValue in listTestValue) + { + + + intSerial += 1; + addrow2 = dsData.Tables["TestValue"].NewRow(); + addrow2["LotNo"] = LotNo; + addrow2["QCItemNo"] = QCItemNo; + addrow2["SerialNo"] = intSerial; + addrow2["TestValue"] = TestValue; + addrow2["LotSerial"] = 0; + addrow2["ComponentNo"] = ""; + + dsData.Tables["TestValue"].Rows.Add(addrow2); + + + } + + string LotSerialTmp = string.Empty; + string LogGroupSerialTmp = string.Empty; + string LotStampTmp = string.Empty; + string ProductNoTmp = string.Empty; + string CustomerNoTmp = "N/A"; + + var drDataTmp = dsData.Tables["SPCData"].Rows[0]; + var dvValue = default(DataView); + dvValue = dsData.Tables["TestValue"].DefaultView; + + bool blnChkOnly = false; + bool blnAttachChart = true; + + //tcSPC_IC.clsSPC objtc_SPC = new tcSPC_IC.clsSPC(); + //objtc_SPC.funAutoBRSPCContorl_Var(ref LotSerialTmp, ref LogGroupSerialTmp, ref LotStampTmp, ref ProductNoTmp, ref CustomerNoTmp, ref drDataTmp, dvValue, blnChkOnly: blnChkOnly, blnAttachChart: blnAttachChart); + strReturn = funAutoBRSPCContorl_Var_M(ref LotSerialTmp, ref LogGroupSerialTmp, ref LotStampTmp, ref ProductNoTmp, ref CustomerNoTmp, ref drDataTmp, dvValue, blnChkOnly: blnChkOnly, blnAttachChart: blnAttachChart); + + if (!strReturn.ToLower().Contains("success")) + { + throw new Exception(strReturn); + } + + + + + + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + dsData?.Dispose(); + //CloseConnection(cnnTemp); + } + return funGetJLSPCData; + + } + + //计数 计数不需要开立异常单或者任何法则检查,只需要做数据收集(多计数品管项目) + public static bool funGetJSSPCData(ref List aryMessage, ref List aryException, string SPCSerial_QMS, string MaterialNo, string MTLVendor, string Employee, string LotNo, string ProDuct, string EquipMent, string DC, List listQCItemDetail) + { + bool funGetJSSPCData = default(bool); + //bool r = false; + //string strSQL = default(string); + IDbConnection cnnTemp = null; + //DbDataReader drTemp; + + AppSettings objSetting = new AppSettings(); + + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + string SpcSerial = string.Empty; + Collection CollectionSQL = new Collection(); + Collection CollectionSQL_Rows = new Collection(); + DateTime nowTime = DateTime.Now; + var oSQLContent = new Dictionary(); + uint intSQLIndex = 1U; + kcSPC.clsSPC objSPC = new kcSPC.clsSPC(); + + try + { + + foreach (var item in listQCItemDetail) + { + //这里的回写序号,防止多人操作时序号被占用,导致数据录不进,且序号不要求连续 + SpcSerial = objSPC.InitSPCSerial(ref cnnTemp); + + if (string.IsNullOrEmpty(SpcSerial)) + { + throw new Exception("[%SpcSerial生成失败%]"); + } + + //参考兆驰 + + //计量计数项目基础资料 + funCreateSPCATTBASIS(ref aryMessage, ref aryException, ref CollectionSQL, + SpcSerial, item.QCITEMNO, LotNo, item.SAMPLEQTY.ToString(), item.GOODQTY.ToString(), item.DefectQty.ToString(), + "0", item.RESULT, SPCSerial_QMS, MaterialNo, MTLVendor, + Employee, ProDuct, EquipMent, DC, nowTime.ToString("yyyy/MM/dd H:mm:ss")); + + //TBLSPCATTDETAILLOG 计数线上检验明细资料历史纪录 + //不良原因填QMS,顾问固定的 + funCreateSPCATTDETAIL(ref aryMessage, ref aryException, ref CollectionSQL, + SpcSerial, item.QCITEMNO, "QMS", item.DefectQty.ToString(), nowTime.ToString("yyyy/MM/dd H:mm:ss")); + + //TBLSPCATTDETAILLOGSECTION 计数线上检验区域明细资料历史纪录档 + //funCreateSPCATTSECTION(ref aryMessage, ref aryException, ref CollectionSQL, + // SpcSerial,"", "QMS","2", item.DefectQty.ToString()); + + } + + + + //执行数据库 + if (CollectionSQL.Count > 0) + { + for (int k = 1, loopTo10 = CollectionSQL.Count; k <= loopTo10; k++) + CollectionSQL_Rows.Add(-1); + funAddSQLContent(oSQLContent, ref intSQLIndex, CollectionSQL, CollectionSQL_Rows); + ExecuteSQLNoneQuery_ArrayBinding(strDataBaseType, strConnectionString, oSQLContent); + } + + + + + + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + if (objSPC != null) + { + objSPC.Dispose(); + } + + CloseConnection(cnnTemp); + } + return funGetJSSPCData; + + } + + + // 2020/11/25 Grace 增加傳入前端畫面輸入的要因, 若有傳, 直接使用 + public static string funAutoBRSPCContorl_Var_M(ref string LotSerial, ref string LogGroupSerial, ref string LotStamp, ref string ProductNo, ref string CustomerNo, + ref DataRow drData, DataView dvValue = null, + string MClassNo = defString, bool blnChkOnly = true, bool blnAttachChart = false, + Collection CollectionSQL = null, + DataTable dtQCItemFactorAll = null, string UserNo = defString, string ShiftNo = defString, bool BrControl = false, bool EAPControl = false, bool blnReleaseLog = true, bool blnHoldLot = true) + { + string funAutoBRSPCContorl_VarRet = default(string); + + // 此 Function 將自動判別檢測數據_計量 + // 傳入值: drData (一次傳入一組檢驗資料,內有LotNo,OpNo,QCItemNo,PratNo,Employee)TestValue 等 + // 傳回值funAutoBRSPCContorl_Var: success(成功), QCItemNo(找不到品管項目編號), LotNo(找不到批號)... + // 傳回值: drData(檢測結果) + + IDbConnection cnnTemp = null; + // 'Dim cmmTemp As OleDb.OleDbCommand + DbDataReader drTemp = null; + string strSQL; + + var kcQC = new kcQC.clsQCBasis(); + var kcWIP = new kcWIP.clsLot(); + var kcSPC = new kcSPC.clsSPC(); + var udSPC = new udSPC.clsSPC(); + var udWIP = new udWIP.clsWIP(); + + // Table + DataSet dsTemp; + var dtQCItemBasis = default(DataTable); + var dtQCItemFactor = default(DataTable); + DataTable dtLotData; + var dtWIPFactor = default(DataTable); + DataTable dtQCItem; // 主要是儲存Check後的結果 + DataRow drAdd; + DataRow[] drSel; + + // 傳入的資料 + var LotNo = default(string); + var OpNo = default(string); + var QCItemNo = default(string); + var QCItemName = default(string); + var Employee = default(string); + + int i, j; + var ERFAction = default(string); + var ERFMsg = default(string); + var strSPCSerial = new string[2]; + + + int intResult; + int intERFSource; + string LinkName; + // Dim LotSerial As String + // Dim LogGroupSerial As String + string ExecuteSPCSerial; + string PopulationQty = ""; + // Dim ProductNo As String + // Dim CustomerNo As String = "N/A" '開異常單時 customerNo不能 Null + // Dim LotStamp As String + bool MailNotice = false; + string[] aryAdditionalSQL; + + string[] aryUpdateSQLReplace; // Added by Neil 2008/05/19 + bool blnCheckOK = true; // Added by Neil 2008/05/19 作為各項檢查的指標,任何一項檢查不過則為False + var strCheckNotOKMessage = default(string); // Added by Neil 2008/05/19 + DataSet dsChartData = null; // Added by Neil 2008/05/20 存放管制圖資料 + + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + + tcSPC_IC.clsSPC objtc_SPC = new tcSPC_IC.clsSPC(); + + try + { + + funAutoBRSPCContorl_VarRet = "error"; // Initial + + // ===== 整理傳入的資料 ========= + if (drData.Table.Columns.Contains("LotNo")) + { + LotNo = drData["LotNo"] + "".ToString(); + } + if (drData.Table.Columns.Contains("QCItemNo")) + { + QCItemNo = (drData["QCItemNo"] + "").ToString().ToUpper(); // 請注意一定要轉大寫 + } + if (drData.Table.Columns.Contains("OpNo")) + { + OpNo = drData["OpNo"] + "".ToString(); + } + if (drData.Table.Columns.Contains("Employee")) + { + Employee = drData["Employee"] + "".ToString(); + } + + DataTable dtTestValue; + + if (dvValue != null) + { + dtTestValue = dvValue.Table.Clone(); + var loopTo = dvValue.Count - 1; + for (i = 0; i <= loopTo; i++) + dtTestValue.ImportRow(dvValue[i].Row); + } + else + { + dtTestValue = new DataTable("TestValue"); + dtTestValue.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtTestValue.Columns.Add("SerialNo", Type.GetType("System.Int32")); + dtTestValue.Columns.Add("TestValue", Type.GetType("System.Double")); + dtTestValue.Columns.Add("MEMO", Type.GetType("System.String")); + dtTestValue.Columns.Add("ComponentNo", Type.GetType("System.String")); + + for (j = 0; j <= 19; j++) + { + if (drData.Table.Columns.Contains("S" + Strings.Format(j + 1, "00")) && !(drData["S" + Strings.Format(j + 1, "00")] is DBNull) && !string.IsNullOrEmpty(drData["S" + Strings.Format(j + 1, "00")].ToString())) + { + drAdd = dtTestValue.NewRow(); + drAdd["QCItemNo"] = QCItemNo; + drAdd["SerialNo"] = j + 1; + drAdd["TestValue"] = drData["S" + Strings.Format(j + 1, "00")]; + dtTestValue.Rows.Add(drAdd); + } + else + { + break; + } + } + + } + + if (dtTestValue.Rows.Count == 0) + { + strCheckNotOKMessage = "No Data"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + + // ===== 檢查資料是否正確 ========= + // 1.取出品管項目 + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + + dtQCItemBasis = kcQC.ShowQCItemForVariables(QCItemNo, IssueState: 2).Tables[0]; + + if (dtQCItemBasis == null || dtQCItemBasis.Rows.Count == 0) + { + strCheckNotOKMessage = "QCItemNo Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + + } + + + // 2 取出Lot資料 + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + + dtLotData = kcWIP.ShowLotBasisJoinState(LotNo).Tables[0]; + if (dtLotData == null || dtLotData.Rows.Count == 0) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItemBasis.Rows[0]["LotIsValid"], 1, false))) // 必須檢查批號有效,但找不到批號資料 + { + strCheckNotOKMessage = "LotData Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + } + else + { + PopulationQty = dtLotData.Rows[0]["CurQty"].ToString(); + LotSerial = dtLotData.Rows[0]["LotSerial"] + "".ToString(); + LogGroupSerial = dtLotData.Rows[0]["LogGroupSerial"] + "".ToString(); + LotStamp = dtLotData.Rows[0]["LotStamp"] + "".ToString(); + ProductNo = dtLotData.Rows[0]["ProductNo"] + "".ToString(); + CustomerNo = dtLotData.Rows[0]["CustomerNo"] + "".ToString(); + OpNo = dtLotData.Rows[0]["OpNo"] + "".ToString(); + } + + } + + + // ===== 整理要因資料 ========= + // 3.1 取出 QCItemFactor + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (!(dtQCItemFactorAll == null)) + { + dtQCItemFactor = dtQCItemFactorAll; + } + else + { + dtQCItemFactor = kcQC.ShowQCItemFactor(QCItemNo).Tables[0]; + } + + dtQCItemFactor = kcQC.ShowQCItemFactor(QCItemNo).Tables[0]; + if (dtQCItemFactor == null || dtQCItemFactor.Rows.Count == 0) + { + strCheckNotOKMessage = "QCItemFactor Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + + } + + + // 3.2 取得檢驗批的要因資料 + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + dtWIPFactor = udSPC.LoadLotFactorValue(LotNo).Tables[0]; + foreach (DataColumn dcFactor in drData.Table.Columns) + { + if (dcFactor.ColumnName.ToUpper() == "OPNO") + { + drSel = dtWIPFactor.Select("ParameterNo = 'OP'"); + + //0144256: [607]SC107匯入報錯 19120 + if (drSel != null && drSel.Length > 0) + { + drSel[0]["Value"] = drData[dcFactor]; + } + + } + + drSel = dtWIPFactor.Select("ParameterNo = '" + dcFactor.ColumnName + "'"); + if (drSel.Length > 0) + { + drSel[0]["Value"] = drData[dcFactor]; + } + } + } + + + // 3.3.將取得的要因值填入品管項目要因,取不到值的則填入N/A + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + dtQCItemFactor.Columns.Add("FactorValue", Type.GetType("System.String")); + var loopTo1 = dtQCItemFactor.Rows.Count - 1; + for (i = 0; i <= loopTo1; i++) + { + drSel = dtWIPFactor.Select("ParameterNo = '" + dtQCItemFactor.Rows[i]["FactorNo"] + "'".ToString()); + if (drSel.Length > 0) + { + dtQCItemFactor.Rows[i]["FactorValue"] = drSel[0]["Value"]; + } + else if (drData.Table.Columns.Contains(Convert.ToString(dtQCItemFactor.Rows[i]["FactorNo"])) && !(drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()] is DBNull) && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()], "", false))) + { + dtQCItemFactor.Rows[i]["FactorValue"] = drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()]; // 從傳入的drData 中取得要因 + } + else + { + dtQCItemFactor.Rows[i]["FactorValue"] = "N/A"; + } + } + + //0190824: 【澳洋】SPC接口 Edison 251023 補上SC101取得自定義要因值的做法 + var dtTempSPCFactorData = new DataTable(); + var dtValueList = new DataTable("ConditionValueList"); + dtValueList.Columns.Add("InspLotNo", typeof(string)); + var drValueList = dtValueList.NewRow(); + drValueList["InspLotNo"] = LotNo; + dtValueList.Rows.Add(drValueList); + foreach (DataRow drw in dtQCItemFactor.Rows) + { + dtValueList.Columns.Add(Convert.ToString(drw["FactorNo"]), typeof(string)); + dtValueList.Rows[0][drw["FactorNo"].ToString()] = drw["FactorValue"].ToString(); + } + + using (var objSys = new kcSYS.clsSYSMesParameter()) + { + // 以SQLCMDMap方式取要因值 + IDbConnection argcnnTemp = null; + objSys.LoadMesParameterValueBySQLCMD(ref dtValueList, cnnTemp: argcnnTemp); + } + + if (dtValueList.Rows.Count > 0) + { + foreach (DataRow drw in dtQCItemFactor.Rows) + { + // 填入要因預設值 + drw["FactorValue"] = dtValueList.Rows[0][drw["FactorNo"].ToString()].ToString().Trim(); + + if (dtQCItemFactorAll == null) + continue; + var drSel2 = dtQCItemFactorAll.Select("ParameterNo = '" + drw["FactorNo"].ToString() + "'"); + // 填入要因預設值 + if (drSel2.Length > 0) + { + foreach (DataRow dr in drSel2) + { + dr["FactorValue"] = dtValueList.Rows[0][drw["FactorNo"].ToString()].ToString().Trim(); + } + } + + } + } + + // 取得暫存要因資料 + strSQL = " Select * From tblWIPTemp_SPCFactorData Where LotNo = '" + LotNo + "' And OPNO = '" + OpNo + "' And LotSerial = '" + LotSerial + "'"; + + dtTempSPCFactorData = new DataTable("WIPTemp_SPCFactorData"); + using (IDbConnection cnnQ = CreateConnection(strConnectionString)) + { + ExecuteSQLQuery_Adapter(SQLCommandTuning(strDataBaseType, ref strSQL), dtTempSPCFactorData, connection: cnnQ); + + if (dtTempSPCFactorData.Rows.Count > 0) + { + foreach (DataRow drw in dtQCItemFactor.Rows) + { + var drtTempSPCFactorData = dtTempSPCFactorData.Select( + "FactorNo = '" + drw["FactorNo"].ToString() + + "' And QCItemNo ='" + drw["QCItemNo"].ToString() + "'"); + + // 填入要因預設值 + if (drtTempSPCFactorData.Length > 0) + { + drw["FactorValue"] = drtTempSPCFactorData[0]["FactorValue"]; + + if (dtQCItemFactorAll == null) + continue; + + var drQCItemFactorAll = dtQCItemFactorAll.Select( + "ParameterNo = '" + drw["FactorNo"].ToString() + + "' And QCItemNo ='" + drw["QCItemNo"].ToString() + "'"); + + // 填入要因預設值 + if (drQCItemFactorAll.Length > 0) + { + foreach (DataRow dr in drQCItemFactorAll) + { + dr["FactorValue"] = drtTempSPCFactorData[0]["FactorValue"]; + } + } + } + } + } + } + } + + // ===== 檢查此筆檢測資料是否已經存過 ========= + var LatestLotsMappingCreateDateTmp = defDateTime; + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (blnChkOnly == true) + { + if (kcSPC.ShowVarFactorLog(ref LatestLotsMappingCreateDateTmp, QCItemNo, LotNo).Tables["SPCVarFactorLog"].Rows.Count > 0) + { + strCheckNotOKMessage = "Already Exist"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + } + } + + // ===== Check 規格與管制法則 ========= + var FactorSerial = default(string); + string strChkTemp; + + var dtViolation = new DataTable("Violation"); // 執行 funChkQCChartValue 後回傳結果 + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + + dtViolation.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtViolation.Columns.Add("SPCSerial", Type.GetType("System.String")); + dtViolation.Columns.Add("ComponentNo", Type.GetType("System.String")); + dtViolation.Columns.Add("SPCID", Type.GetType("System.String")); + dtViolation.Columns.Add("SerialNo", Type.GetType("System.String")); // Raw ID , 非Raw=-1 + dtViolation.Columns.Add("ViolationID", Type.GetType("System.String")); // 違反類型:WE001, WE002, ..,WE008 + + if (blnAttachChart == true) // 若blnAttachChart = True 則建立dsXlsChartData基本架構,待經過funChkQCChartValue後取得資料,後續畫管制圖用 + { + + dsChartData = new DataSet(); + DataRow tmprow; + + dsChartData.Tables.Add("ChartInfo"); + dsChartData.Tables["ChartInfo"].Columns.Add("SpecLineType"); + dsChartData.Tables["ChartInfo"].Columns.Add("SampleSize"); + dsChartData.Tables["ChartInfo"].Columns.Add("TUCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("TLCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("TCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("TUS"); + dsChartData.Tables["ChartInfo"].Columns.Add("TLS"); + dsChartData.Tables["ChartInfo"].Columns.Add("XUCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("XLCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("XCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("XUS"); + dsChartData.Tables["ChartInfo"].Columns.Add("XLS"); + dsChartData.Tables["ChartInfo"].Columns.Add("GUCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("GLCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("GCL"); + dsChartData.Tables["ChartInfo"].Columns.Add("GUS"); + dsChartData.Tables["ChartInfo"].Columns.Add("GLS"); + dsChartData.Tables["ChartInfo"].Rows.Add(dsChartData.Tables["ChartInfo"].NewRow()); + + // dsChartData.Tables.Add("TrendData") + // dsChartData.Tables.Add("XbarData") + // dsChartData.Tables.Add("GraphData") + + } + + string argEnterpriseNo = ""; + strChkTemp = kcSPC.funChkQCChartValue(LotNo, QCItemNo, Employee, + dtQCItemFactor, dtTestValue, ref FactorSerial, ref dtViolation, + ref ERFAction, ref ERFMsg, dsChartData, + EnterpriseNo: argEnterpriseNo); + if (Convert.ToBoolean(Strings.InStr(strChkTemp, "fail"))) // 無管制圖或檢查過程錯誤 + { + strCheckNotOKMessage = "ChkQCChartValue" + strChkTemp; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/19 + } + } + + + // 若純檢查,只要做到這裡為止 'Added by Yun 2007/11/2 + if (blnChkOnly == true) + { + funAutoBRSPCContorl_VarRet = strCheckNotOKMessage; // last modify by Neil 2008/06/03 + return funAutoBRSPCContorl_VarRet; + } + + // Added by Neil 2008/05/19 + if (blnCheckOK == false) + { + drData["Execute"] = strCheckNotOKMessage; // Add Yun 2017/11/28 將Check 結果傳出 + + // 檢查沒過回寫狀態 + if (drData.Table.Columns.Contains("UpdateSQL") && !(drData["UpdateSQL"] is DBNull)) + { + if (drData.Table.Columns.Contains("UpdateSQLReplace") && !(drData["UpdateSQLReplace"] is DBNull)) + { + var CollectSQL = new Collection(); + // drData("Execute") = strCheckNotOKMessage 'Marked Yun 2017/11/28 移到上面 + objtc_SPC.CollectUpdateSQL(ref drData, ref CollectSQL); + if (CollectSQL.Count != 0) + { + kcSPC.ExecuteSQL(CollectSQL); + } + } + } + + funAutoBRSPCContorl_VarRet = strCheckNotOKMessage; + return funAutoBRSPCContorl_VarRet; + + } + + + // 備用 + DataTable dtComponent; + dtComponent = new DataTable("Component"); + dtComponent.Columns.Add("SPCSerial", Type.GetType("System.String")); + dtComponent.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtComponent.Columns.Add("ComponentNo", Type.GetType("System.String")); + dtComponent.Columns.Add("CompResult", Type.GetType("System.String")); + + + // ===== 整理生產批(各品管項目綜合)結果,並存入資料庫 ========= + if (Strings.InStr(ERFAction, "Hold") > 0) + { + LinkName = "Hold"; + intResult = 1; + } + else if (Strings.InStr(ERFAction, "Alarm") > 0) + { + LinkName = "Alarm"; + intResult = 4; + } + else if (Strings.InStr(ERFAction, "Alert") > 0) + { + LinkName = "Alert"; + intResult = 4; + } + else if (Strings.InStr(ERFAction, "Wait") > 0) + { + LinkName = "Wait"; + intResult = 2; + } + else if (Strings.InStr(ERFAction, "Warning") > 0) + { + LinkName = "Warning"; + intResult = 3; + } + else + { + LinkName = "Pass"; + intResult = 0; + } + drData["Result"] = LinkName; // 回傳出去給人看的所以用字串 + drData["intResult"] = intResult; + + // Add QCItem Test Value + dtQCItem = new DataTable("QCItem"); + dtQCItem.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtQCItem.Columns.Add("FactorSerial", Type.GetType("System.String")); + dtQCItem.Columns.Add("RetestLotNo", Type.GetType("System.String")); + dtQCItem.Columns.Add("ERFMsg", Type.GetType("System.String")); + dtQCItem.Columns.Add("Result", Type.GetType("System.String")); // 紀錄結果 0,1,2,.... + dtQCItem.Columns.Add("SPCSerial", Type.GetType("System.String")); // 在UpdVar_TestValue中會將SPCSerial 填入 + + drAdd = dtQCItem.NewRow(); + drAdd["QCItemNo"] = QCItemNo; + drAdd["FactorSerial"] = FactorSerial; + drAdd["RetestLotNo"] = ""; + drAdd["ERFMsg"] = ERFMsg; + drAdd["Result"] = intResult.ToString(); + dtQCItem.Rows.Add(drAdd); + + //EAP过站组件信息 + if (EAPControl) + { + DataView dataView = dtTestValue.DefaultView; + DataTable QcItemNoDistinct = dataView.ToTable(true, "ComponentNo", "QCItemNo"); + DataRow[] drSelCom; + // 將資料存入暫存Table + for (int q = 0; q < QcItemNoDistinct.Rows.Count; q++) + { + var drcomData = dtComponent.NewRow(); + drcomData["QCItemNo"] = QCItemNo; + if (QcItemNoDistinct.Rows[q]["QCItemNo"].ToString() == QCItemNo) + { + drcomData["ComponentNo"] = QcItemNoDistinct.Rows[q]["ComponentNo"].ToString(); + } + + if (dtViolation.Rows.Count > 0) + { + drSelCom = dtViolation.Select("ComponentNo='" + QcItemNoDistinct.Rows[q]["ComponentNo"].ToString() + "'"); + if (drSelCom.Length > 0) + { + drcomData["CompResult"] = "1"; + } + else + { + drcomData["CompResult"] = "0"; + } + } + else + { + drcomData["CompResult"] = "0"; + } + dtComponent.Rows.Add(drcomData); + } + + } + + var colSQL = new Collection(); + string strGSPCSerialTmp = defString; + kcSPC.UpdVar_TestValue(ref strGSPCSerialTmp, dtQCItemFactor, dtQCItem, dtTestValue, LotNo, LotSerial, Employee, dtComponent: dtComponent, colSQL: colSQL, LogGroupSerial: LogGroupSerial, OPNo: OpNo); + + // 取得 SPCSerial + strSPCSerial[0] = dtQCItem.Rows[0]["SPCSerial"].ToString(); + if (drData.Table.Columns.Contains("SPCSerial")) + { + drData["SPCSerial"] = dtQCItem.Rows[0]["SPCSerial"]; + } + + // 2020/01/20 ,Yenru Add ERFMSG + if (drData.Table.Columns.Contains("ERFMsg")) + { + drData["ERFMsg"] = dtQCItem.Rows[0]["ERFMsg"]; + } + //回写法则编号 + string ruleno = ""; + if (drData.Table.Columns.Contains("RuleNo")) + { + if (dtViolation.Rows.Count > 0) + { + for (int r = 0; r < dtViolation.Rows.Count; r++) + { + if (dtViolation.Rows[r]["QCItemNo"].ToString() == QCItemNo && dtViolation.Rows[r]["ComponentNo"].ToString() == drData["ComponentNo"].ToString()) + { + ruleno = dtViolation.Rows[r]["ViolationID"].ToString(); + } + } + } + drData["RuleNo"] = ruleno; + } + + // Add SPC待檢清單 + kcSPC.UpdSpcLotQCList(LotNo, OpNo, 1, dtQCItem, strSPCSerial, colSQL); + //争对EAP处理 + if (EAPControl) + { + //对生产批的处理 + if (BrControl || intResult != 0) + { + // WIP的BR_SPCControl + DataTable dtSamplePara = new DataTable("SamplePara"); + dtSamplePara.Columns.Add("ParameterNo", Type.GetType("System.String")); + dtSamplePara.Columns.Add("ParameterValue", Type.GetType("System.String")); + kcWIP.BR_SPCControl(long.Parse(LotStamp), LotNo, ref LinkName, QCItemNo, UserNo, ShiftNo, colSQL, dtSamplePara, strMsg: ERFMsg, blnFirstLotOf2ndInsp: false, blnReleaseLog: blnReleaseLog); + funAutoBRSPCContorl_VarRet = LinkName; + // 紀錄Cont_QCItem + var loopTo13 = dtQCItem.Rows.Count - 1; + string[] comp_SPCSerial; + string[] comp_ERFMsg; + for (i = 0; i <= loopTo13; i++) + { + comp_SPCSerial = strSPCSerial[i].Split(';'); // 當計算方式為 ByComponent時會用;隔開 + var loopTo14 = comp_SPCSerial.Length - 1; + for (int c = 0; c <= loopTo14; c++) + kcSPC.AddWIPQCItemContent(LotNo, LotSerial, OpNo, QCItemNo, Convert.ToString(dtQCItem.Rows[i]["QCItemNo"]), 1, comp_SPCSerial[c], UserNo, LogGroupSerial, colSQL); + } + } + } + + // Add Limit + dsTemp = kcSPC.ShowQCChartDetail(FactorSerial); + if (!(dsTemp.Tables["QCChartDetail"] == null) && dsTemp.Tables["QCChartDetail"].Rows.Count > 0) + { + dsTemp.Tables["QCChartDetail"].Columns.Add("SPCSerial", Type.GetType("System.String")); + var loopTo2 = dsTemp.Tables["QCChartDetail"].Rows.Count - 1; + for (i = 0; i <= loopTo2; i++) + dsTemp.Tables["QCChartDetail"].Rows[i]["SPCSerial"] = dtQCItem.Rows[0]["SPCSerial"]; + kcSPC.AddSPCVarLimitContent(dsTemp.Tables["QCChartDetail"], colSQL); + } + + // Add Violation + if (!(dtViolation == null) && dtViolation.Rows.Count > 0) + { + var loopTo3 = dtViolation.Rows.Count - 1; + if (EAPControl && Convert.ToInt32(dtQCItemBasis.Rows[0]["CalType"]) == 1) + { + DataTable dtComSpcserial = dtComponent; + for (i = 0; i <= loopTo3; i++) + { + for (int s = 0; s < dtComSpcserial.Rows.Count; s++) + { + if (dtViolation.Rows[i]["QCItemNo"].ToString() == dtComSpcserial.Rows[s]["QCItemNo"].ToString() && dtViolation.Rows[i]["ComponentNo"].ToString() == dtComSpcserial.Rows[s]["ComponentNo"].ToString()) + { + dtViolation.Rows[i]["SPCSerial"] = dtComSpcserial.Rows[s]["SPCSerial"]; + } + } + } + } + else + { + for (i = 0; i <= loopTo3; i++) + dtViolation.Rows[i]["SPCSerial"] = dtQCItem.Rows[0]["SPCSerial"]; + } + kcSPC.AddSPCViolationContent(dtViolation, colSQL); + } + + //0173294: [6.0.7]SDD240326_01-04 / Execute_InLineSPC_Judge 將異常單訊息上提到新增ERFCrerateData之前 Edison 241126 + var strMsg = default(string); + // ↓=================================================================================================================== + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 4, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 1, false))) + { + strMsg = "Auto SPC " + "[" + QCItemNo + "]" + Strings.Replace(dtQCItem.Rows[0]["ERFMsg"].ToString(), "$", ""); + } + + string strSPCSerialPlitByDot = string.Join(",", + dtViolation.AsEnumerable() + .Select(row => row.Field("SPCSerial")) + .Distinct()); + if (!blnHoldLot && strMsg != default(string)) + kcWIP.AddERFCreateData(LotNo, OpNo, "1", 0, strMsg, PopulationQty, UserNo, strSPCSerialPlitByDot, Conversions.ToInteger(dtQCItemBasis.Rows[0]["LotIsValid"]), 1, LotSerial: LotSerial, colSQL: colSQL); + + // 額外需執行的指令 + if (drData.Table.Columns.Contains("AdditionalSQL") && !(drData["AdditionalSQL"] is DBNull)) + { + aryAdditionalSQL = Strings.Split(drData["AdditionalSQL"].ToString(), "|"); + var loopTo4 = aryAdditionalSQL.Length - 1; + for (i = 0; i <= loopTo4; i++) + colSQL.Add(aryAdditionalSQL[i]); + } + + // 額外需執行的指令 Added by Neil 2008/05/19 + if (drData.Table.Columns.Contains("UpdateSQL") && !(drData["UpdateSQL"] is DBNull)) + { + objtc_SPC.CollectUpdateSQL(ref drData, ref colSQL); + } + + + // 呼叫執行SQL指令 + if (CollectionSQL == null) + { + // Call ExecuteSQLNoneQuery_UPD(DataBaseType, strConnectionString, CollectionSQL) + + // 執行彙總的 SQL 指令 + kcSPC.ExecuteSQL(colSQL); + drData["Execute"] = "success"; // 表示SPC資料已儲存成功 + } + else + { + // 2020/11/23 Grace 不執行指令,將指令傳出 + var loopTo5 = colSQL.Count; + for (i = 1; i <= loopTo5; i++) + CollectionSQL.Add(colSQL[i]); + } + + + + // ↑=================================================================================================================== + + + // 開立異常單 + string ERFNo; + + intERFSource = 1; + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 1, false)) && blnAttachChart == true) + { + + if (MClassNo == defString) + { + + // 取得MClassNo (取不到則不開 )=============================================== + cnnTemp = CreateConnection(strConnectionString); + strSQL = "Select MClassNo, QCItemName From tblQCItemForVariables Where QCItemNo = '" + QCItemNo + "'"; + + // 'cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) 'Select data + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + MClassNo = drTemp["MClassNo"] + "".ToString(); + QCItemName = drTemp["QCItemName"] + "".ToString(); + if (!string.IsNullOrEmpty(MClassNo)) // Added by Yun 2007/12/19 + { + ERFNo = udWIP.InitERFNo(InitNo: "SPC"); + kcWIP.UpdERF_Create(1, -1, LotNo, intERFSource, ERFNo, 0, MClassNo, strMsg, Employee, CreateERF: true, OPNo: OpNo, CustomerNo: CustomerNo, ProductNo: ProductNo, SPCSerial: strSPCSerial[0], QCItemType: 1, MailNotice: false); + // 建立異常單附件並發送 Added by Neil 2008/05/21============================================================================ + // Dim dtHoldReason As New DataTable("HoldReason") + var AttachFileContent = default(byte[]); // Added by Neil 2008/05/21 mail附件 + if (objtc_SPC.funCreateAttachFile(ERFNo + ".pdf", QCItemNo, LotNo, ERFNo, ProductNo, CustomerNo, OpNo, MClassNo, Strings.Replace(Convert.ToString(dtQCItem.Rows[0]["ERFMsg"]), "$", ""), Employee, dsChartData, drData, dtTestValue, dtQCItemFactor, ref AttachFileContent, true, QCItemName) == true) + { + kcSPC.SendAlertMail(OpNo, MClassNo, QCItemNo, "1", "[ERF Create Notice]: ERFNo:" + ERFNo + " LotNo:" + LotNo, "ERFNo:" + ERFNo, ERFNo + ".pdf", AttachFileContent); + } + } + } + drTemp.Close(); + CloseConnection(cnnTemp); + + } + + } + + // ===== 發Mail ========= + // ↓=================================================================================================================== + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 4, false))) // Alert 發 mail + { + // Last Modify:Neil 2008/05/22 + var AttachAlertFileContent = default(byte[]); // Added by Neil 2008/05/21 mail附件 + if (objtc_SPC.funCreateAttachFile("Alert.pdf", QCItemNo, LotNo, "", ProductNo, CustomerNo, OpNo, MClassNo, Strings.Replace(Convert.ToString(dtQCItem.Rows[0]["ERFMsg"]), "$", ""), Employee, dsChartData, drData, dtTestValue, dtQCItemFactor, ref AttachAlertFileContent, false, QCItemName) == true) + { + kcSPC.SendAlertMail(OpNo, MClassNo, QCItemNo, "1", "[Alert Mail]: QCItemNo:" + QCItemNo, "QCItemNo:" + QCItemNo, "Alert.pdf", AttachAlertFileContent); + } + } + // ↑=================================================================================================================== + if (EAPControl) + { + if (!BrControl) + { + if (intResult == 0) + { + funAutoBRSPCContorl_VarRet = "success"; // 表示 Function 執行成功 + } + } + } + else + { + funAutoBRSPCContorl_VarRet = "success"; // 表示 Function 執行成功 + } + + } + + + catch (Exception e1) + { + funAutoBRSPCContorl_VarRet = "fail"; + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("kcSPC.funBRSPConlinetrans: " & e1.Message) + + finally + { + if (kcWIP != null) + kcWIP = null; + if (kcQC != null) + kcQC = null; + if (kcSPC != null) + kcSPC = null; + if (objtc_SPC != null) + objtc_SPC = null; + + if (cnnTemp != null) + CloseConnection(cnnTemp); + } + + return funAutoBRSPCContorl_VarRet; + + + } + + + + + /// + /// 计数标准-标版备用 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public string funAutoBRSPCContorl_Att(ref string LotSerial, ref string LogGroupSerial, ref string LotStamp, ref string ProductNo, ref string CustomerNo, + ref DataRow drData, DataView dvError = null, + string MClassNo = defString, bool blnChkOnly = true, bool blnCreateERF = true, + bool blnChkAttRule = true, Collection CollectionSQL = null, + long AQLRejectNum = defInteger, string LotRuleNo = defString, + DataTable dtQCItemFactorAll = null, string UserNo = defString, string ShiftNo = defString, bool BrControl = false, bool EAPControl = false, DataTable dtAttDetailLogComponent = null, bool blnReleaseLog = true, bool blnHoldLot = true) + { + string funAutoBRSPCContorl_AttRet = default(string); + + + // 此 Function 將自動判別檢測數據_計數 + // 傳入值: drData (一次傳入一組檢驗資料,內有LotNo,OpNo,QCItemNo,PratNo,Employee)等 + // 傳入 : dtError (不良原因) + // 傳回值funAutoBRSPCContorl_Att: success(成功), QCItemNo(找不到品管項目編號), LotNo(找不到批號)... + // 傳回值: drData(檢測結果) + + IDbConnection cnnTemp = null; + // 'Dim cmmTemp As OleDb.OleDbCommand + DbDataReader drTemp = null; + string strSQL; + + var kcQC = new kcQC.clsQCBasis(); + var kcWIP = new kcWIP.clsLot(); + var kcSPC = new kcSPC.clsSPC(); + var udSPC = new udSPC.clsSPC(); + var udWIP = new udWIP.clsWIP(); + + // Table + DataSet dsTemp; + var dtQCItemBasis = default(DataTable); + var dtQCItemFactor = default(DataTable); + var dtFactorOnline = default(DataTable); + DataTable dtLotData; + var dtWIPFactor = default(DataTable); + DataTable dtQCItem; // 主要是儲存Check後的結果 + var dtError = default(DataTable); + DataRow drAdd; + DataRow[] drSel; + + // 傳入的資料 + var LotNo = default(string); + var OpNo = default(string); + var QCItemNo = default(string); + string QCItemName; + var Employee = default(string); + decimal SampleQty = default(decimal), ScrapQty = default(decimal), DefectQty = default(decimal), GoodQty = default(decimal); + + int i, j; + string ERFAction; + var ERFMsg = default(string); + var strSPCSerial = new string[2]; + + + var intResult = default(int); + int intERFSource; + var LinkName = default(string); + // Dim LotSerial As String + // Dim LogGroupSerial As String + string ExecuteSPCSerial; + string PopulationQty = ""; + // Dim ProductNo As String + // Dim CustomerNo As String = "N/A" '開異常單時 customerNo不能 Null + // Dim LotStamp As String + bool MailNotice = false; + string[] aryAdditionalSQL; + int LimitLotNum; // 計數品管項目的最大顯示批數 + + string[] aryUpdateSQLReplace; // Added by Neil 2008/05/22 + bool blnCheckOK = true; // Added by Neil 2008/05/22 作為各項檢查的指標,任何一項檢查不過則為False + var strCheckNotOKMessage = default(string); // Added by Neil 2008/05/22 + + tcSPC_IC.clsSPC objtc_SPC = new tcSPC_IC.clsSPC(); + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + try + { + funAutoBRSPCContorl_AttRet = "error"; // Initial + + // ===== 整理傳入的資料 ========= + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (drData.Table.Columns.Contains("LotNo")) + { + LotNo = drData["LotNo"] + "".ToString(); + } + else + { + strCheckNotOKMessage = "No LotNo"; + // Exit Function + blnCheckOK = false; + } // Added by Neil 2008/05/22 + } + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (drData.Table.Columns.Contains("QCItemNo")) + { + QCItemNo = drData["QCItemNo"] + "".ToString().ToUpper(); // 請注意一定要轉大寫 + } + else + { + strCheckNotOKMessage = "No QCItemNo"; + // Exit Function + blnCheckOK = false; + } // Added by Neil 2008/05/22 + } + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (drData.Table.Columns.Contains("OpNo")) + { + OpNo = drData["OpNo"] + "".ToString(); + } + + if (drData.Table.Columns.Contains("Employee")) + { + Employee = drData["Employee"] + "".ToString(); + } + + if (drData.Table.Columns.Contains("Product")) + { + ProductNo = drData["Product"] + "".ToString(); + } + if (drData.Table.Columns.Contains("SampleQty")) + { + SampleQty = Convert.ToDecimal(drData["SampleQty"]); + } + else + { + strCheckNotOKMessage = "No SampleQty"; + // Exit Function + blnCheckOK = false; + } // Added by Neil 2008/05/22 + } + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (drData.Table.Columns.Contains("ScrapQty")) + { + ScrapQty = Convert.ToDecimal(drData["ScrapQty"]); + } + else + { + strCheckNotOKMessage = "No ScrapQty"; + // Exit Function + blnCheckOK = false; + } // Added by Neil 2008/05/22 + } + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + if (drData.Table.Columns.Contains("DefectQty")) + { + DefectQty = Convert.ToDecimal(drData["DefectQty"]); + } + else + { + DefectQty = 0m; + } + if (drData.Table.Columns.Contains("GoodQty")) + { + GoodQty = Convert.ToDecimal(drData["GoodQty"]); + } + else + { + strCheckNotOKMessage = "No GoodQty"; + // Exit Function + blnCheckOK = false; + } // Added by Neil 2008/05/22 + } + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + // 不良原因 + if (dvError != null) + { + dtError = dvError.Table.Clone(); + var loopTo = dvError.Count - 1; + for (i = 0; i <= loopTo; i++) + dtError.ImportRow(dvError[i].Row); + if (funChkReasonsExist(dtError, ref ScrapQty, ref DefectQty, ref GoodQty, ref SampleQty) == false) + { + strCheckNotOKMessage = "ReasonNo is not exist"; + blnCheckOK = false; + } + } + + + // ===== 檢查資料是否正確 ========= + // 1.取出品管項目 + dtQCItemBasis = kcQC.ShowQCItemForAttributes(QCItemNo, IssueState: 2).Tables[0]; + + if (dtQCItemBasis == null || dtQCItemBasis.Rows.Count == 0) + { + strCheckNotOKMessage = "QCItemNo Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/22 + } + } + + + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + // 2 取出Lot資料 + dtLotData = kcWIP.ShowLotBasisJoinState(LotNo).Tables[0]; + if (dtLotData == null || dtLotData.Rows.Count == 0) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItemBasis.Rows[0]["LotIsValid"], 1, false))) // 必須檢查批號有效,但找不到批號資料 + { + strCheckNotOKMessage = "LotData Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/22 + } + } + else + { + PopulationQty = dtLotData.Rows[0]["CurQty"].ToString(); + LotSerial = dtLotData.Rows[0]["LotSerial"] + "".ToString(); + LogGroupSerial = dtLotData.Rows[0]["LogGroupSerial"] + "".ToString(); + LotStamp = dtLotData.Rows[0]["LotStamp"] + "".ToString(); + ProductNo = dtLotData.Rows[0]["ProductNo"] + "".ToString(); + CustomerNo = dtLotData.Rows[0]["CustomerNo"] + "".ToString(); + OpNo = dtLotData.Rows[0]["OpNo"] + "".ToString(); + } + } + + // ===== 整理要因資料 ========= + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + // 3.1 取出 QCItemFactor + if (!(dtQCItemFactorAll == null)) + { + dtQCItemFactor = dtQCItemFactorAll; + } + else + { + dtQCItemFactor = kcQC.ShowQCItemFactor(QCItemNo).Tables[0]; + } + + if (dtQCItemFactor == null || dtQCItemFactor.Rows.Count == 0) + { + strCheckNotOKMessage = "QCItemFactor Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/22 + } + } + + + // 3.2 取得檢驗批的要因資料 + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + dtWIPFactor = udSPC.LoadLotFactorValue(LotNo).Tables[0]; + } + + + // 3.3.將取得的要因值填入品管項目要因,取不到值的則填入N/A + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + dtQCItemFactor.Columns.Add("FactorValue", Type.GetType("System.String")); + dtFactorOnline = dtQCItemFactor.Clone(); // 複製Table Schema + var loopTo1 = dtQCItemFactor.Rows.Count - 1; + for (i = 0; i <= loopTo1; i++) + { + drSel = dtWIPFactor.Select("ParameterNo = '" + dtQCItemFactor.Rows[i]["FactorNo"] + "'".ToString()); + if (drSel.Length > 0) + { + dtQCItemFactor.Rows[i]["FactorValue"] = drSel[0]["Value"]; + } + else if (drData.Table.Columns.Contains(Convert.ToString(dtQCItemFactor.Rows[i]["FactorNo"])) && !(drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()] is DBNull) && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()], "", false))) + { + dtQCItemFactor.Rows[i]["FactorValue"] = drData[dtQCItemFactor.Rows[i]["FactorNo"].ToString()]; // 從傳入的drData 中取得要因 + } + else + { + dtQCItemFactor.Rows[i]["FactorValue"] = "N/A"; + } + + // 取出線上管制要因 + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItemFactor.Rows[i]["FactorOnline"], "Y", false))) + { + dtFactorOnline.ImportRow(dtQCItemFactor.Rows[i]); + } + } + } + + + // '===== 檢查此筆檢測資料是否已經存過 ========= + // If blnChkOnly = True Then + // If kcSPC.ShowVarFactorLog(, , QCItemNo, LotNo).Tables("SPCVarFactorLog").Rows.Count > 0 Then + // funAutoBRSPCContorl_Var = "Already Exist" + // Exit Function + // End If + // End If + + + // 若純檢查,只要做到這裡為止 + if (blnChkOnly == true) + { + funAutoBRSPCContorl_AttRet = ""; + return funAutoBRSPCContorl_AttRet; + } + + // '===== Check 規格與管制法則 ========= + var dtViolation = new DataTable("Violation"); // 執行 funChkAttRule 後回傳結果 + if (blnChkAttRule == true) + { + if (blnCheckOK == true) // 前項檢查通過才繼續下面的動作 + { + dtViolation.Columns.Add("SPCSerial", Type.GetType("System.String")); + dtViolation.Columns.Add("ViolationID", Type.GetType("System.String")); // 違反類型:WE001, WE002, ..,WE008 + dtViolation.Columns.Add("PChartFlag", Type.GetType("System.Int16")); // 0:否 1:是 + + if (!(dtQCItemBasis.Rows[0]["LimitLotNum"] is DBNull)) + { + LimitLotNum = Conversions.ToInteger(dtQCItemBasis.Rows[0]["LimitLotNum"]); + } + else + { + LimitLotNum = defInteger; + } + + // 檢查法則(取出LinkeName,ERFMsg,intResult,dtViolation) + if (Convert.ToBoolean(objtc_SPC.funChkAttRule(QCItemNo, dtError, Convert.ToString(dtQCItemBasis.Rows[0]["RuleNo"] + + ""), (long)Math.Round(SampleQty), ref LinkName, ref ERFMsg, ref intResult, ref dtViolation, ScrapQty / SampleQty, dtFactorOnline, LimitLotNum, AQLRejectNum, LotRuleNo)) == false) + { + strCheckNotOKMessage = "Check Rule Error"; + // Exit Function + blnCheckOK = false; // Added by Neil 2008/05/22 + } + } + } + + // Added by Neil 2008/05/19 + if (blnCheckOK == false) + { + drData["Execute"] = strCheckNotOKMessage; // 從下面搬移過來 Yun 2009/6/4 + + // 檢查沒過回寫狀態 + if (drData.Table.Columns.Contains("UpdateSQL") && !(drData["UpdateSQL"] is DBNull)) + { + if (drData.Table.Columns.Contains("UpdateSQLReplace") && !(drData["UpdateSQLReplace"] is DBNull)) + { + var CollectSQL = new Collection(); + // drData("Execute") = strCheckNotOKMessage '搬移 Yun 2009/6/4 + objtc_SPC.CollectUpdateSQL(ref drData, ref CollectSQL); + if (CollectSQL.Count != 0) + { + kcSPC.ExecuteSQL(CollectSQL); + } + } + } + + funAutoBRSPCContorl_AttRet = strCheckNotOKMessage; + return funAutoBRSPCContorl_AttRet; + + } + + drData["Result"] = LinkName; // 回傳出去給人看的所以用字串 + drData["intResult"] = intResult; + + // Add QCItem Test Value + dtQCItem = new DataTable("QCItem"); + dtQCItem.Columns.Add("QCItemNo", Type.GetType("System.String")); + dtQCItem.Columns.Add("QCAttSPSerial", Type.GetType("System.String")); + dtQCItem.Columns.Add("SampleQty", Type.GetType("System.Int32")); + dtQCItem.Columns.Add("GoodQty", Type.GetType("System.Int32")); + dtQCItem.Columns.Add("ScrapQty", Type.GetType("System.Int32")); + dtQCItem.Columns.Add("DefectQty", Type.GetType("System.Int32")); + dtQCItem.Columns.Add("Result", Type.GetType("System.Int32")); + dtQCItem.Columns.Add("ERFMsg", Type.GetType("System.String")); + dtQCItem.Columns.Add("SPCSerial", Type.GetType("System.String")); // 產生SPCSerial後可存在此欄位 + + if (blnChkAttRule == true) + { + drAdd = dtQCItem.NewRow(); + drAdd["QCItemNo"] = QCItemNo; + drAdd["QCAttSPSerial"] = ""; + drAdd["SampleQty"] = SampleQty; + drAdd["GoodQty"] = GoodQty; + drAdd["ScrapQty"] = ScrapQty; + drAdd["DefectQty"] = DefectQty; + drAdd["Result"] = intResult.ToString(); + drAdd["ERFMsg"] = ERFMsg; + drAdd["SPCSerial"] = ""; + if (MClassNo != defString) + { + drAdd["MClassNo"] = MClassNo; + } + dtQCItem.Rows.Add(drAdd); + + // 2020/01/20 ,Yenru Add ERFMSG + if (drData.Table.Columns.Contains("ERFMsg")) + { + drData["ERFMsg"] = dtQCItem.Rows[0]["ERFMsg"]; + } + //回写法则编号 + string ruleno = ""; + if (drData.Table.Columns.Contains("RuleNo")) + { + drData["RuleNo"] = dtQCItemBasis.Rows[0]["RuleNo"]; + } + } + else + { + drAdd = dtQCItem.NewRow(); + drAdd["QCItemNo"] = drData["QCItemNo"]; + drAdd["QCAttSPSerial"] = ""; + drAdd["SampleQty"] = drData["SampleQty"]; + drAdd["GoodQty"] = drData["GoodQty"]; + drAdd["ScrapQty"] = drData["ScrapQty"]; + drAdd["DefectQty"] = 0; + drAdd["Result"] = drData["DefaultResult"]; + drAdd["ERFMsg"] = ""; + drAdd["SPCSerial"] = ""; + if (MClassNo != defString) + { + drAdd["MClassNo"] = MClassNo; + } + dtQCItem.Rows.Add(drAdd); + } + + // 收集要執行的指令 + var colSQL = new Collection(); + string strReturnValue; + + // Update SPC Log + if (!dtQCItem.Columns.Contains("Rank")) + { + dtQCItem.Columns.Add("Rank", Type.GetType("System.String")); // 2010/06/28 Lai + } + if (!dtQCItem.Columns.Contains("RankDetail")) + { + dtQCItem.Columns.Add("RankDetail", Type.GetType("System.String")); // 2010/06/28 Lai + } + + strReturnValue = kcSPC.UpdAtt_TestValue(dtQCItemFactor, dtQCItem, dtError, LotNo, LotSerial, Creator: Employee, colSQL: colSQL, LogGroupSerial: LogGroupSerial); + + // 取得 SPCSerial + strSPCSerial = Strings.Split(strReturnValue, "|"); + if (drData.Table.Columns.Contains("SPCSerial")) + { + drData["SPCSerial"] = strSPCSerial[0]; + } + + // Add SPC待檢清單 + kcSPC.UpdSpcLotQCList(LotNo, OpNo, 0, dtQCItem, strSPCSerial, colSQL); + + //争对EAP处理 + if (EAPControl) + { + //对生产批的处理 + if (BrControl || intResult != 0) + { + // WIP的BR_SPCControl + DataTable dtSamplePara = new DataTable("SamplePara"); + dtSamplePara.Columns.Add("ParameterNo", Type.GetType("System.String")); + dtSamplePara.Columns.Add("ParameterValue", Type.GetType("System.String")); + kcWIP.BR_SPCControl(long.Parse(LotStamp), LotNo, ref LinkName, QCItemNo, UserNo, ShiftNo, colSQL, dtSamplePara, strMsg: ERFMsg, blnFirstLotOf2ndInsp: false, blnReleaseLog: blnReleaseLog); + funAutoBRSPCContorl_AttRet = LinkName; + // 紀錄Cont_QCItem + var loopTo13 = dtQCItem.Rows.Count - 1; + string[] comp_SPCSerial; + string[] comp_ERFMsg; + for (i = 0; i <= loopTo13; i++) + { + comp_SPCSerial = strSPCSerial[i].Split(';'); // 當計算方式為 ByComponent時會用;隔開 + var loopTo14 = comp_SPCSerial.Length - 1; + for (int c = 0; c <= loopTo14; c++) + kcSPC.AddWIPQCItemContent(LotNo, LotSerial, OpNo, QCItemNo, Convert.ToString(dtQCItem.Rows[i]["QCItemNo"]), 1, comp_SPCSerial[c], UserNo, LogGroupSerial, colSQL); + } + } + } + + string strPChcartViolationID; + // Add Att Violation + if (!(dtViolation == null) && dtViolation.Rows.Count > 0) + { + strPChcartViolationID = ""; + var loopTo2 = dtViolation.Rows.Count - 1; + for (i = 0; i <= loopTo2; i++) + { + dtViolation.Rows[i]["SPCSerial"] = dtQCItem.Rows[0]["SPCSerial"]; + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtViolation.Rows[i]["PChartFlag"], 1, false))) + { + strPChcartViolationID = strPChcartViolationID + (string.IsNullOrEmpty(strPChcartViolationID) ? "" : "|") + + dtViolation.Rows[i]["ViolationID"]; + } + } + kcSPC.AddSPCAttViolationContent(dtViolation, colSQL); + kcSPC.AddSPCPChartFailLog(strSPCSerial[0], QCItemNo, (ScrapQty / SampleQty).ToString(), strPChcartViolationID, ProductNo, OpNo); // P-Chart 不良紀錄 + } + + //0173294: [6.0.7]SDD240326_01-04 / Execute_InLineSPC_Judge 將異常單訊息上提到新增ERFCrerateData之前 Edison 241126 + + var strMsg = default(string); + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 4, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 3, false))) // Alert 或 Hold 要發 mail (4=Alert,計數的Result,與計量不同) + { + strMsg = "Auto SPC " + "[" + QCItemNo + "]" + Strings.Replace(dtQCItem.Rows[0]["ERFMsg"].ToString(), "$", ""); + // Call kcSPC.SendAlertMail(OpNo, MClassNo, QCItemNo, "0", "[Alert Mail]:" & QCItemNo, strMsg) + } + + string strSPCSerialPlitByDot = string.Join(",", + dtViolation.AsEnumerable() + .Select(row => row.Field("SPCSerial")) + .Distinct()); + if (!blnHoldLot && strMsg != default(string)) + kcWIP.AddERFCreateData(LotNo, OpNo, "1", 0, strMsg, PopulationQty, UserNo, strSPCSerialPlitByDot, Conversions.ToInteger(dtQCItemBasis.Rows[0]["LotIsValid"]), 1, LotSerial: LotSerial, colSQL: colSQL); + + if (!(dtAttDetailLogComponent == null)) + { + var loopTo14 = dtAttDetailLogComponent.Rows.Count - 1; + for (i = 0; i <= loopTo14; i++) + kcSPC.AddSPCAttDetailLogComponent(strSPCSerial[0], dtAttDetailLogComponent.Rows[i]["ComponentNo"].ToString(), dtAttDetailLogComponent.Rows[i]["ErrorNo"].ToString(), Convert.ToDecimal(dtAttDetailLogComponent.Rows[i]["ErrorQty"]), dtAttDetailLogComponent.Rows[i]["Area"].ToString(), dtAttDetailLogComponent.Rows[i]["Memo"].ToString(), colSQL); + } + + // 額外需執行的指令 + if (drData.Table.Columns.Contains("AdditionalSQL") && Operators.ConditionalCompareObjectNotEqual(drData["AdditionalSQL"] + "", "", false)) + { + aryAdditionalSQL = Strings.Split(drData["AdditionalSQL"].ToString(), "|"); + var loopTo3 = aryAdditionalSQL.Length - 1; + for (i = 0; i <= loopTo3; i++) + colSQL.Add(aryAdditionalSQL[i]); + } + + // 額外需執行的指令 Added by Neil 2008/05/22 + if (drData.Table.Columns.Contains("UpdateSQL") && !(drData["UpdateSQL"] is DBNull)) + { + objtc_SPC.CollectUpdateSQL(ref drData, ref colSQL); + } + + + // 呼叫執行SQL指令 + if (CollectionSQL == null) + { + // Call ExecuteSQLNoneQuery_UPD(DataBaseType, strConnectionString, CollectionSQL) + // 執行彙總的 SQL 指令 + kcSPC.ExecuteSQL(colSQL); + drData["Execute"] = "success"; // 表示SPC資料已儲存成功 + } + else + { + // 2020/11/23 Grace 不執行指令,將指令傳出 + var loopTo4 = colSQL.Count; + for (i = 1; i <= loopTo4; i++) + CollectionSQL.Add(colSQL[i]); + } + + if (blnCreateERF == true) + { + // ===== 發Mail ========= + // //Create connection + //var strMsg = default(string); + + //// ↓=================================================================================================================== + //if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 4, false)) || Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 3, false))) // Alert 或 Hold 要發 mail (4=Alert,計數的Result,與計量不同) + //{ + // strMsg = "Auto SPC " + "[" + QCItemNo + "]" + Strings.Replace(dtQCItem.Rows[0]["ERFMsg"].ToString(), "$", ""); + // // Call kcSPC.SendAlertMail(OpNo, MClassNo, QCItemNo, "0", "[Alert Mail]:" & QCItemNo, strMsg) + //} + // ↑=================================================================================================================== + + + // 開立異常單 + string ERFNo; + string OPName = defString; // added by Neil 2008/07/29 + + intERFSource = 1; + + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dtQCItem.Rows[0]["Result"], 3, false))) // Hold + { + + if (MClassNo == defString) + { + // 取得MClassNo (取不到則不開) ======================================================== 'update by Yun 2007/12/19 + cnnTemp = CreateConnection(strConnectionString); + strSQL = "Select MClassNo, QCItemName From tblQCItemForAttributes Where QCItemNo = '" + QCItemNo + "'"; + + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) 'Select data + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + MClassNo = drTemp["MClassNo"] + "".ToString(); + QCItemName = drTemp["QCItemName"] + "".ToString(); + if (!string.IsNullOrEmpty(MClassNo)) // Added by Yun 2007/12/19 + { + ERFNo = udWIP.InitERFNo(InitNo: "SPC"); + kcWIP.UpdERF_Create(1, Conversions.ToLong(LotStamp), LotNo, intERFSource, ERFNo, 0, MClassNo, strMsg, Employee, CreateERF: true, OPNo: OpNo, CustomerNo: CustomerNo, ProductNo: ProductNo, SPCSerial: strSPCSerial[0], QCItemType: 0); + } + } + drTemp.Close(); + CloseConnection(cnnTemp); + } + } + } + + + if (EAPControl) + { + if (!BrControl) + { + if (intResult == 0) + { + funAutoBRSPCContorl_AttRet = "success"; // 表示 Function 執行成功 + } + } + } + else + { + funAutoBRSPCContorl_AttRet = "success"; // 表示 Function 執行成功 + } + } + + + catch (Exception e1) + { + funAutoBRSPCContorl_AttRet = "fail"; + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("kcSPC.funBRSPConlinetrans: " & e1.Message) + + finally + { + if (kcWIP != null) + kcWIP = null; + if (kcQC != null) + kcQC = null; + if (kcSPC != null) + kcSPC = null; + + if (objtc_SPC != null) + objtc_SPC = null; + + if (cnnTemp != null) + CloseConnection(cnnTemp); + } + + return funAutoBRSPCContorl_AttRet; + + + } + + // Added by Neil 2008/07/29 檢查原因是否存在並更新ScrapQty,DefectQty,GoodQty資料 + private bool funChkReasonsExist(DataTable dtError, ref decimal ScrapQty, ref decimal DefectQty, ref decimal GoodQty, ref decimal SampleQty) + { + bool funChkReasonsExistRet = default(bool); + + IDbConnection cnnTemp = null; + // Dim cmmTemp As OleDb.OleDbCommand + DbDataReader drTemp = null; + + var ScrapCount = default(decimal); + var DefectCount = default(decimal); + + int inti; + + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + string strSQL = ""; + + try + { + + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + // cmmTemp = New OleDb.OleDbCommand + // cmmTemp.Connection = cnnTemp + + funChkReasonsExistRet = true; + + var loopTo = dtError.Rows.Count - 1; + for (inti = 0; inti <= loopTo; inti++) + { + // 檢查資料在 TBL_QUICS_SPCDETAILLOG 中是否存在 + strSQL = "SELECT REASONTYPE FROM TBLQCREASONBASIS " + "WHERE " + "REASONNO = '" + + dtError.Rows[inti]["ErrorNo"] + "' AND ISSUESTATE = 2"; + + // cmmTemp.CommandText = strSQL + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + + if (drTemp.Read() == false) // 若不存在則結束 + { + funChkReasonsExistRet = false; + return funChkReasonsExistRet; + } + else + { + + switch (drTemp["ReasonType"].ToString()) + { + case "0": // Scrap + { + ScrapCount = (decimal)((double)ScrapCount + Conversion.Val(dtError.Rows[inti]["ErrorQty"])); + break; + } + case "1": // Defect + { + DefectCount = (decimal)((double)DefectCount + Conversion.Val(dtError.Rows[inti]["ErrorQty"])); + break; + } + } + } + drTemp.Close(); + } + + ScrapQty = ScrapCount; + DefectQty = DefectCount; + GoodQty = SampleQty - (ScrapQty + DefectQty); + } + + catch (Exception ex) + { + funChkReasonsExistRet = false; + throw; + } + finally + { + if (!(cnnTemp == null)) + CloseConnection(cnnTemp); + + } + + return funChkReasonsExistRet; + + } + + + //建立计数检验数据收集接口 + public static bool funCreateSPCATTBASIS(ref List aryMessage, ref List aryException, ref Collection CollectionSQL, string SpcSerial, string QCItemNo, string LotNo, string SampleQty, string GoodQty, string ScrapQty, string DefectQty, string Result, string SPCSerial_QMS, string MaterialNo, string MTLVendor, string Employee, string ProDuct, string EquipMent, string DC, string CreateDate) + { + bool result = false; + //int i; + string strSQL = ""; + string strSQL_Value = ""; + //IDbConnection cnnTemp = null; + //DbDataReader drTemp = null; + //Collection CollectionSQL = new Collection(); + + //AppSettings objSetting = new AppSettings(); + //string strDataBaseType = objSetting.GetDataBaseType(); + //string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + decimal decResult = 0; + try + { + //cnnTemp = CreateConnection(strConnectionString); + + //因为前面先锁住序号,所有这里不需要再次检查 + + ////先检查是否已经存在相同数据 + //strSQL = $@"Select * From tblSPCAttBasisLog Where SpcSerial ='{SpcSerial}'"; + //drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + //if (drTemp.Read()) + //{ + // //combineException(ref aryException, null, null, "[%已经存在对应的计数检验数据!%]"); + // //return result; + // throw new Exception("已经存在对应的计数检验数据!"); + //} + //drTemp.Dispose(); + + //主档 + strSQL = "Insert Into tblSPCAttBasisLog(SpcSerial,QCItemNo,LotNo,CreateDate,Creator,Product,Equipment,SPCSerial_QMS,MATERIAL,MTLVendor,EMPLOYEE,DC"; + strSQL_Value = $@" Values('{SpcSerial}','{QCItemNo}','{LotNo}',To_Date('{Strings.Format(Convert.ToDateTime(CreateDate), "yyyy/MM/dd H:mm:ss")}','YYYY/MM/DD HH24:MI:SS'),'QMS','{ProDuct}', +'{EquipMent}','{SPCSerial_QMS}','{MaterialNo}','{MTLVendor}','{Employee}','{DC}'"; + + if (SampleQty != "") + { + strSQL += ",SampleQty"; + strSQL_Value += $@",{SampleQty}"; + } + if (GoodQty != "") + { + strSQL += ",GoodQty"; + strSQL_Value += $@",{GoodQty}"; + } + if (ScrapQty != "") + { + strSQL += ",ScrapQty"; + strSQL_Value += $@",{ScrapQty}"; + } + if (DefectQty != "") + { + strSQL += ",DefectQty"; + strSQL_Value += $@",{DefectQty}"; + } + if (Result != "") + { + if (Result.ToUpper() == "PASS") + { + //成功 + decResult = 0; + } + else + { + //失败 //先默认4 + decResult = 4; + } + + + strSQL += ",Result"; + strSQL_Value += $@",{decResult}"; + } + + strSQL += ")"; + strSQL_Value += ")"; + + CollectionSQL.Add(strSQL + strSQL_Value); + + //ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + result = true; + + } + catch (Exception ex) + { + //combineException(ref aryException, null, ex.Message, "[%新增计数检验数据失败%]", ex.StackTrace); + throw; + } + finally + { + //if (drTemp != null && !drTemp.IsClosed) + //{ + // drTemp.Close(); + //} + //CloseConnection(cnnTemp); + } + + return result; + } + //建立计数检验数据明细记录接口 + public static bool funCreateSPCATTDETAIL(ref List aryMessage, ref List aryException, ref Collection CollectionSQL, string SpcSerial, string QCItemNo, string ErrorNo, string strErrorQty, string CreateDate) + { + bool result = false; + string strSQL = ""; + string strSQL_Value = ""; + //IDbConnection cnnTemp = null; + //DbDataReader drTemp = null; + //Collection CollectionSQL = new Collection(); + + //AppSettings objSetting = new AppSettings(); + //string strDataBaseType = objSetting.GetDataBaseType(); + //string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + decimal ErrorQty = 0; + + try + { + //cnnTemp = CreateConnection(strConnectionString); + + //因为前面先锁住序号,所有这里不需要再次检查 + + ////先检查是否已经存在相同数据 + //strSQL = $@"Select * From tblSPCAttDetailLog Where SpcSerial ='{SpcSerial}'"; + //drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + //if (drTemp.Read()) + //{ + // combineException(ref aryException, null, null, "[%已经存在对应的计数检验数据!%]"); + // return result; + //} + //drTemp.Dispose(); + + if (!decimal.TryParse(strErrorQty, out ErrorQty)) + { + throw new Exception("不良数量格式错误!"); + } + + //主档 + + strSQL = "Insert Into tblSPCAttDetailLog(SpcSerial,QCItemNo,ErrorNo,ErrorQty,CreateDate"; + strSQL_Value = $@" Values('{SpcSerial}','{QCItemNo}','{ErrorNo}',{ErrorQty},To_Date('{Strings.Format(Convert.ToDateTime(CreateDate), "yyyy/MM/dd H:mm:ss")}','YYYY/MM/DD HH24:MI:SS')"; + + strSQL += ")"; + strSQL_Value += ")"; + + CollectionSQL.Add(strSQL + strSQL_Value); + + + + //ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + result = true; + + } + catch (Exception ex) + { + //combineException(ref aryException, null, ex.Message, "[%新增计数检验数据失败%]", ex.StackTrace); + throw; + } + finally + { + //if (drTemp != null && !drTemp.IsClosed) + //{ + // drTemp.Close(); + //} + //CloseConnection(cnnTemp); + } + + return result; + } + //建立计数检验数据区域明细接口 + public static bool funCreateSPCATTSECTION(ref List aryMessage, ref List aryException, ref Collection CollectionSQL, string SpcSerial, string SectionNo, string ErrorNo, string Area, string strErrorQty) + { + bool result = false; + //int i; + string strSQL = ""; + string strSQL_Value = ""; + //IDbConnection cnnTemp = null; + //DbDataReader drTemp = null; + //Collection CollectionSQL = new Collection(); + + //AppSettings objSetting = new AppSettings(); + //string strDataBaseType = objSetting.GetDataBaseType(); + //string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + decimal ErrorQty = 0; + try + { + //cnnTemp = CreateConnection(strConnectionString); + + //因为前面先锁住序号,所有这里不需要再次检查 + + ////先检查是否已经存在相同数据 + //strSQL = $@"Select * From tblSPCAttDetailLogSection Where SpcSerial ='{SpcSerial}'"; + //drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + //if (drTemp.Read()) + //{ + // combineException(ref aryException, null, null, "[%已经存在对应的计数检验数据区域明细!%]"); + // return result; + //} + //drTemp.Dispose(); + + + + + //主档 + + strSQL = "Insert Into tblSPCAttDetailLogSection(SpcSerial,SectionNo,ErrorNo,Area"; + strSQL_Value = $@" Values('{SpcSerial}','{SectionNo}','{ErrorNo}','{Area}'"; + + if (strErrorQty != "") + { + if (!decimal.TryParse(strErrorQty, out ErrorQty)) + { + throw new Exception("不良数量格式错误!"); + } + + strSQL += ",ErrorQty"; + strSQL_Value += $@",{ErrorQty}"; + } + + strSQL += ")"; + strSQL_Value += ")"; + + CollectionSQL.Add(strSQL + strSQL_Value); + + + + ////sql集合一起执行 + //ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + ////成功后回写最大码 + //funGetSPCSerialNo(true); + + result = true; + + } + catch (Exception ex) + { + //combineException(ref aryException, null, ex.Message, "[%新增计数检验数据失败%]", ex.StackTrace); + throw; + } + finally + { + //if (drTemp != null && !drTemp.IsClosed) + //{ + // drTemp.Close(); + //} + //CloseConnection(cnnTemp); + } + + return result; + } + + public static string funGetSPCSerialNo(bool ReserveSerialNo) + { + string funExeSerialCreate_SerialRet = default(string); + + DbDataReader drTemp = null; + var colSQL = new Collection(); + var colSQL_Rows = new Collection(); + var arySerial = new ArrayList(); + + string SerialType = "SPCAPI"; + string SerialString = "SPCSERIAL"; + int SerialLength = 4; + int DecimalType = 1; + long SerialCount = 1; + int PadLeft = defInteger; + string strSQL = ""; + IDbConnection cnnTemp = null; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + + try + { + + cnnTemp = CreateConnection(strConnectionString); + + // 取出最大碼. + bool blnInsert; + long lngMaxSerialNo; // 起始碼. + long lngSerialNo_Last; // 最大一個序號. + var strSerialNo_Last_nn = default(string); // 轉換成10,16,36表示式. + + strSQL = "Select MaxSerialNo From tblSYSSerialCreateMax " + " Where SerialType='" + SerialType + "'" + " And SerialString='" + SerialString + "'" + " And SerialLength=" + SerialLength + " And DecimalType=" + DecimalType + ""; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + blnInsert = false; + lngMaxSerialNo = Conversions.ToLong(drTemp["MaxSerialNo"]); + } + else + { + blnInsert = true; + lngMaxSerialNo = 0L; + } + drTemp.Close(); + + // 最大的序號 + lngSerialNo_Last = lngMaxSerialNo + SerialCount; + + if (DecimalType == 1) + { + strSerialNo_Last_nn = lngSerialNo_Last.ToString(); + } + else if (DecimalType == 2) + { + strSerialNo_Last_nn = Tran10_16(lngSerialNo_Last); + } + else if (DecimalType == 3) + { + strSerialNo_Last_nn = Tran10_36(lngSerialNo_Last); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + strSerialNo_Last_nn = Tran10_34(lngSerialNo_Last); + // ===================================== 86774 End ===================================== + + } + + // 最大碼是否超出序號長度. + if (strSerialNo_Last_nn != null && strSerialNo_Last_nn.Length > SerialLength) + { + throw new iMESException.MESException("9P12-200028", "[%SerialString%]: " + SerialString + Constants.vbNewLine + "[%SerialLength%]: " + SerialLength + Constants.vbNewLine + "[%SerialNo%]: " + strSerialNo_Last_nn); + } + + if (ReserveSerialNo == true) + { + // 回填最大碼(利用MaxSerialNo來確保資料的一致性及使用的序號為唯一) + if (blnInsert) + { + strSQL = "Insert into tblSYSSerialCreateMax " + " (SerialType,SerialString,SerialLength,DecimalType,MaxSerialNo) " + " Values('" + SerialType + "','" + SerialString + "'," + SerialLength + "," + DecimalType + "," + lngSerialNo_Last + ")"; + colSQL.Add(strSQL); + colSQL_Rows.Add(1); + } + else + { + strSQL = "Update tblSYSSerialCreateMax Set MaxSerialNo=" + lngSerialNo_Last + " Where SerialType='" + SerialType + "'" + " And SerialString='" + SerialString + "'" + " And SerialLength=" + SerialLength + " And DecimalType=" + DecimalType + " And MaxSerialNo=" + lngMaxSerialNo; + colSQL.Add(strSQL); + colSQL_Rows.Add(1); + } + + ExecuteSQLNoneQuery_ChkRowCount(Convert.ToString(strDataBaseType), strConnectionString, colSQL, colSQL_Rows); + } + + for (int i = 1, loopTo = (int)SerialCount; i <= loopTo; i++) + { + if (PadLeft == 0) + { + if (DecimalType == 1) + { + arySerial.Add((lngMaxSerialNo + i).ToString()); + } + else if (DecimalType == 2) + { + arySerial.Add(Tran10_16(lngMaxSerialNo + i).ToString()); + } + else if (DecimalType == 3) + { + arySerial.Add(Tran10_36(lngMaxSerialNo + i).ToString()); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + arySerial.Add(Tran10_34(lngMaxSerialNo + i).ToString()); + // ===================================== 86774 End ===================================== + } + } + else if (DecimalType == 1) + { + arySerial.Add((lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + else if (DecimalType == 2) + { + arySerial.Add(Tran10_16(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + else if (DecimalType == 3) + { + arySerial.Add(Tran10_36(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + } + + // 86774: [6.0.5] 序號規則新增34進位序號 + // ===================================== 86774 Start ===================================== + else if (DecimalType == 4) + { + arySerial.Add(Tran10_34(lngMaxSerialNo + i).ToString().PadLeft(SerialLength, '0')); + // ===================================== 86774 End ===================================== + } + } + + // 回傳最大碼 + if (arySerial.Count > 0) + { + funExeSerialCreate_SerialRet = arySerial[0].ToString(); + } + else + { + funExeSerialCreate_SerialRet = null; + } + } + + catch (Exception e1) + { + funExeSerialCreate_SerialRet = null; + throw; + } + finally + { + CloseConnection(cnnTemp); + } + + return funExeSerialCreate_SerialRet; + + } + + /// + /// 拼接异常信息:Message + StackTrace,用于日志/输出 + /// + public static string GetExceptionFullMessage(Exception ex) + { + if (ex == null) + return "无异常信息"; + + return $"异常信息:{ex.Message} 堆栈信息:{ex.StackTrace}"; + } + #endregion + + #region "工单砍单、取消卡控接口" + public static bool funCheckMONoCanEditCancel_M(ref List aryMessage, ref List aryException, ref decimal InputQty, ref decimal OutputQty, ref string CurrentStatus, string MONo, decimal decQuantity, int intStatus) + { + bool funCheckMONoCanEditCancel_M = default(bool); + //bool r = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsData = new DataSet(); + + + + string strReturn = ""; + + var ReleaseQty = default(decimal); + + kcWIP.clsLot objLot = new kcWIP.clsLot(); + DataRow drOE = null; + try + { + + //标准基础检查 + using (var objOE = new clsOEBasis()) + { + + drOE = objOE.GetMOBasis(MONo.ToUpper()); + if (drOE["MONo"] is DBNull == true) + { + //clsERP.combineException(aryException, mesmsg: "[%MONo%]:" + drOE["MONo"] + " [%MONoNotExist%]"); + //break; + + //throw new Exception("工单号不存在"); + + clsERP.combineMessage(ref aryMessage, mmsg: "[%工单号不存在!%]"); + return false; + } + + // 如果MES這邊是不使用IssueState = -1, 也要可以改,以EPR那邊為主, + if (!(drOE["MOState"] is DBNull)) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drOE["MOState"], 99, false))) + { + //clsERP.combineException(aryException, mesmsg: "[%MONo%]:" + drOE["MONo"] + " [%MONoClosed%]"); + //break; + + //throw new Exception("工单状态已经结案!"); + + clsERP.combineMessage(ref aryMessage, mmsg: "[%工单状态已经结案!%]"); + return false; + } + + + } + + // ----- 3. 檢查MO剩餘數量 ----- + if (!(drOE["MOQty"] is DBNull)) + { + ReleaseQty = Convert.ToDecimal(Operators.SubtractObject(drOE["MOQty"], drOE["UnReleaseLotQty"])); + if (decQuantity > ReleaseQty && intStatus == 0) + { + //clsERP.combineException(aryException, mesmsg: "[%MONo%]:" + + // drOE["MONo"] + " [%MOQtyLessThenReleaseLotQty%]"); + //break; + + //throw new Exception("砍单数量小于现在工单未下线数量!"); + + clsERP.combineMessage(ref aryMessage, mmsg: "[%砍单数量大于现在工单未下线数量/工单数量!%]"); + return false; + } + } + + } + + //如当前设置A站点前可以砍单/取消,可以手动变更为B站点前可以砍单/取消;在作业站属性中配置标识:Delflag(只针对线上的生产批) + //找到目前线上的生产批 + + strSQL = $"SELECT A.BASELOTNO,B.STATUS,B.LotStamp FROM TBLWIPLOTBASIS A INNER JOIN TBLWIPLOTSTATE B ON A.BASELOTNO = B.LOTNO WHERE A.MONO='{MONo}' AND B.STATUS IN (0,1,2,3,4,5) AND A.LotState = '1'"; + ExecuteSQLQuery_Adapter(strSQL, dsData, "TBLWIPLOTBASIS", cnnTemp); + + if (dsData.Tables["TBLWIPLOTBASIS"].Rows.Count > 0) + { + //有线上生产批 + //检查线上生产批是否过了有 【在作业站属性中配置标识:Delflag】 + + //拼接成IN语句 + string strLotNo = ""; + foreach (DataRow dr in dsData.Tables["TBLWIPLOTBASIS"].Rows) + { + strLotNo += "'" + dr["BASELOTNO"] + "',"; + } + strLotNo = strLotNo.Substring(0, strLotNo.Length - 1); + + strSQL = $@"SELECT 1 +FROM DUAL +WHERE EXISTS ( + SELECT 1 + FROM TBLOPPROPERTY A + INNER JOIN TBLOPBASIS B + ON A.OPNO = B.OPNO AND B.ISSUESTATE = 2 + INNER JOIN TBLWIPLOTLOG C + ON C.OPNO = B.OPNO AND C.STATUS = 1 + WHERE A.PROPERTYNO = 'Delflag' + AND A.ISSUESTATE = 2 + AND C.LOTNO IN ({strLotNo}) +)"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + //存在,说明过了特殊站点,不能变更 + clsERP.combineMessage(ref aryMessage, mmsg: "[%线上生产批已经过了带有Delflag站点,不能变更!%]"); + return false; + } + else + { + //不存在,说明没有过特殊站点,可以变更 + + //可以变更,先将线上的生产批全部wait,顾问说一搬流程就是 一个批,这里直接调用标准wait + foreach (DataRow dr in dsData.Tables["TBLWIPLOTBASIS"].Rows) + { + //如果是 STATUS 字段是 3或者4则,则不wait + if (Convert.ToInt32(dr["STATUS"]) == 3 || Convert.ToInt32(dr["STATUS"]) == 4) + { + continue; + } + else + { + int intLotStamp = dr["LotStamp"].ToString().Trim() == "" ? 0 : Convert.ToInt32(dr["LotStamp"]); + + //wait + objLot.SetLotStateToWait(LotStamp: intLotStamp, dr["BASELOTNO"].ToString(), + WaitType: 2, UserNo: "ERP", WaitSource: 0, WaitDescription: "砍单接口立即暂停所有批次"); + } + } + + + + } + drTemp.Close(); + } + + + //若是成功,返回 工单投入、产出数量 、工单状态工单状态 + if (drOE != null) + { + //工单投入(InputQty) = 工单数量(MOQTY) - 未下线数量(UNRELEASELOTQTY) + if (!(drOE["MOQty"] is DBNull) && !(drOE["UnReleaseLotQty"] is DBNull)) + { + //使用三元运算符转换工单数量和未下线数量,防止出现空值报错 + decimal MOQty = Convert.ToDecimal(drOE["MOQty"] is DBNull ? 0 : drOE["MOQty"]); + decimal UnReleaseLotQty = Convert.ToDecimal(drOE["UnReleaseLotQty"] is DBNull ? 0 : drOE["UnReleaseLotQty"]); + InputQty = MOQty - UnReleaseLotQty; + + } + + //产出数量 OnputQty MOFINISHQTY + decimal MOFINISHQTY = Convert.ToDecimal(drOE["MOFINISHQTY"] is DBNull ? 0 : drOE["MOFINISHQTY"]); + OutputQty = MOFINISHQTY; + + //工单状态 根据 MOSTATE判断,赋值给CurrentStatus + + // 工单状态 + //0:未确认 + //1:确认中 + //2:已确认 + //3:生产中 + //4:已在客托仓或退货仓 + //99:结案 + + int MOSTATE = Convert.ToInt32(drOE["MOSTATE"] is DBNull ? 0 : drOE["MOSTATE"]); + switch (MOSTATE) + { + case 0: + CurrentStatus = "未确认"; + break; + case 1: + CurrentStatus = "确认中"; + break; + case 2: + CurrentStatus = "已确认"; + break; + case 3: + CurrentStatus = "生产中"; + break; + case 4: + CurrentStatus = "已在客托仓或退货仓"; + break; + case 99: + CurrentStatus = "结案"; + break; + default: + CurrentStatus = "未知状态"; + break; + } + + } + + + funCheckMONoCanEditCancel_M = true; + exitfun: + ; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + if (objLot != null) + { + objLot.Dispose(); + } + + + drTemp?.Close(); + + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funCheckMONoCanEditCancel_M; + + } + + + + + + + + #endregion + + #region"Mapping反转" + public static bool funGetPrdMapping(ref List aryMessage, ref List aryException, string Productid, string Eqp_id, ref int REVERSALMETHOD) + { + bool funGetPrdMappingref = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + + DataSet dsData = new DataSet(); + + + + + try + { + strSQL = "select d.* from TBLWIPPRDSTATE_LQ a inner join TBLWIPLOTSTATE b on a.LotNo=b.LotNo inner join TBLWIPLOTBASIS c on b.LotNo=c.BaseLotNo inner join TBLPRDMAPPING_LQ d on d.OPNO=b.OPNO and d.ProductNo=c.ProductNo where a.productid ='" + Productid + "'and a.state = '1'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + REVERSALMETHOD = Convert.ToInt16(drTemp["REVERSALMETHOD"].ToString()); + funGetPrdMappingref = true; + } + else + { + throw new Exception("产品作业站未配置反转方式!"); + } + drTemp.Close(); + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funGetPrdMappingref; + + } + + public static bool funGetMaterialhold(ref List aryMessage, ref List aryException, string source, string materialno, string materiallotno, string holdstate, string creator, string date, string reasonno) + { + bool funGetPrdMappingref = false; + string strSQL = default(string); + IDbConnection cnnTemp = null; + DbDataReader drTemp = null; + + AppSettings objSetting = new AppSettings(); + + Collection CollectionSQL = new Collection(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + + DataSet dsData = new DataSet(); + + + string MaterialFrom; + + try + { + if (materiallotno == "*") + { + materiallotno = "ALL"; + } + if (holdstate == "0") + { + + if (source == "0") + { + //工单 + MaterialFrom = "工单"; + strSQL = "select * from TBLOEMOMATERIALSTATE WHERE MaterialNo='" + materialno + "' AND QTY>0"; + if (!string.IsNullOrWhiteSpace(materiallotno) && !materiallotno.Equals("ALL", StringComparison.OrdinalIgnoreCase) && !materiallotno.Equals("*", StringComparison.OrdinalIgnoreCase)) + { + strSQL += " AND MaterialLotNo ='" + materiallotno + "'"; + + } + } + else + { + MaterialFrom = "虚拟库"; + strSQL = "select * from TBLINVWIPINVENTORY_RAW WHERE MaterialNo='" + materialno + "' AND QTY>0"; + if (!string.IsNullOrWhiteSpace(materiallotno) && !materiallotno.Equals("ALL", StringComparison.OrdinalIgnoreCase) && !materiallotno.Equals("*", StringComparison.OrdinalIgnoreCase)) + { + strSQL += " AND MaterialLotNo ='" + materiallotno + "'"; + + } + } + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + + strSQL = "INSERT INTO TBLCUSHOLDMATERIALSTATE ( MATERIALFROM , MATERIALNO , MATERIALLOTNO , REASONNO , CREATOR ) VALUES ('" + MaterialFrom + "', '" + materialno + "', '" + materiallotno + "', '" + reasonno + "', '" + creator + "')"; + CollectionSQL.Add(strSQL); + strSQL = "INSERT INTO TBLCUSHOLDMATERIALLOG ( MATERIALFROM , MATERIALNO , MATERIALLOTNO , HOLDSTATE , REASONNO , CREATOR) VALUES ('" + MaterialFrom + "', '" + materialno + "', '" + materiallotno + "',1, '" + reasonno + "', '" + creator + "')"; + CollectionSQL.Add(strSQL); + } + else + { + throw new Exception("物料不存在或数量不足!"); + + } + drTemp.Close(); + } + else + { + DataTable dtdata = new DataTable(); + if (source == "0") + { + //工单 + MaterialFrom = "工单"; + } + else + { + MaterialFrom = "虚拟库"; + } + strSQL = "select * from TBLCUSHOLDMATERIALSTATE where 1=1 "; + if (materiallotno != "*") + { + strSQL += " AND MaterialNo='" + materialno + "'"; + } + if (MaterialFrom != "*") + { + strSQL += " AND MaterialFrom='" + MaterialFrom + "'"; + } + if ( reasonno != "ERPhold") + { + strSQL += " AND REASONNO='" + reasonno + "'"; + } + if (materiallotno != "*") + { + strSQL += " AND MaterialLotNo='" + materiallotno + "'"; + } + else + { + strSQL += " AND MaterialLotNo='ALL'"; + } + ExecuteSQLQuery_Adapter(strSQL, dtdata, cnnTemp); + + if (dtdata.Rows.Count == 0) + { + throw new Exception("物料未被Hold!"); + } + foreach (DataRow dr in dtdata.Rows) + { + strSQL = "delete from TBLCUSHOLDMATERIALSTATE where MaterialNo='" + dr["MATERIALNO"] + "' AND MaterialFrom='" + dr["MaterialFrom"] + "' AND REASONNO='" + dr["REASONNO"] + "' AND MaterialLotNo='" + dr["MaterialLotNo"] + "' AND Creator='" + dr["Creator"] + "'"; + CollectionSQL.Add(strSQL); + strSQL = "INSERT INTO TBLCUSHOLDMATERIALLOG ( MATERIALFROM , MATERIALNO , MATERIALLOTNO , HOLDSTATE , REASONNO , CREATOR) VALUES ('" + dr["MaterialFrom"] + "', '" + dr["MATERIALNO"] + "', '" + dr["MaterialLotNo"] + "',0, '" + dr["REASONNO"] + "', '" + creator + "')"; + CollectionSQL.Add(strSQL); + } + + } + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + funGetPrdMappingref=true; + } + catch (Exception ex) + { + // 一行调用,拿到完整异常字符串 + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + dsData?.Dispose(); + CloseConnection(cnnTemp); + } + return funGetPrdMappingref; + + } + + #endregion + + #region"钢片绑定" + public static bool funSteelBind(ref List aryMessage, ref List aryException, + string equipmentno, string steelno, string carrierno, ref string lotno) + { + bool result = false; + IDbConnection cnnTemp = null; + DataSet dsTemp = new DataSet(); + AppSettings objSetting = new AppSettings(); + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + // 1. 根据设备编号查询 TBLWIPTEMP_Equipment 获取 LotNo + cnnTemp = CreateConnection(strConnectionString); + string strSQL; + lotno = carrierno; + + // 2. 检查钢片是否已被绑定(被其他批次占用) + dsTemp.Tables.Clear(); + strSQL = string.Format("SELECT STEELNO, LOTNO, STEELSTATE FROM TBLCUSSTEELSTATE WHERE STEELNO = '{0}'", steelno); + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "tblSteel", cnnTemp); + + if (dsTemp.Tables["tblSteel"].Rows.Count > 0) + { + string existLotNo = dsTemp.Tables["tblSteel"].Rows[0]["LOTNO"].ToString(); + if (!string.IsNullOrEmpty(existLotNo) && existLotNo != lotno) + { + throw new Exception("钢片已被绑定:" + steelno); + } + } + + // 3. 检查该批次是否已绑定其他钢片,有则先解绑 + dsTemp.Tables.Clear(); + strSQL = string.Format("SELECT STEELNO FROM TBLCUSSTEELSTATE WHERE LOTNO = '{0}' AND STEELSTATE = '1' AND STEELNO != '{1}'", lotno, steelno); + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "tblOldSteel", cnnTemp); + + var CollectionSQL = new Collection(); + foreach (DataRow dr in dsTemp.Tables["tblOldSteel"].Rows) + { + string oldSteelNo = dr["STEELNO"].ToString(); + CollectionSQL.Add(string.Format("UPDATE TBLCUSSTEELSTATE SET LOTNO = '', STEELSTATE = '0' WHERE STEELNO = '{0}'", oldSteelNo)); + CollectionSQL.Add(string.Format("INSERT INTO TBLCUSSTEELLOG(STEELNO, LOTNO, STEELSTATE, CREATOR, CREATDATE) VALUES('{0}', '{1}', '0', 'DS', SYSDATE)", oldSteelNo, lotno)); + } + + // 4. 绑定新钢片 + CollectionSQL.Add(string.Format("UPDATE TBLCUSSTEELSTATE SET LOTNO = '{0}', STEELSTATE = '1' WHERE STEELNO = '{1}'", lotno, steelno)); + CollectionSQL.Add(string.Format("INSERT INTO TBLCUSSTEELLOG(STEELNO, LOTNO, STEELSTATE, CREATOR, CREATDATE) VALUES('{0}', '{1}', '1', 'DS', SYSDATE)", steelno, lotno)); + + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + + result = true; + } + catch (Exception ex) + { + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + CloseConnection(cnnTemp); + dsTemp?.Dispose(); + } + + return result; + } + #endregion + + #region" 产品BOM信息接口" + // OPNO,NODENO,STDQTY,DECREASERATE,SUBMTL + public static bool GetProdBOMInfo(ref List aryMessage, ref List aryException, string PRODUCTNO = defString, + string PRODUCTVERSION = defString, BomRequest bomRequest = null) + { + // tcEAI_C.clsERP.AddUser(ref strMessage, ref strException, PRODUCTNO, PRODUCTNAME, PRODUCTVERSION, CREATOR, CREATEDATE, dtDPPara); + bool result = false; + + // int i, j; + string strSQLAddField, strSQLAddValue; + Collection MTLCollection = new Collection(); + Collection CollectionSQL = new Collection(); + + + string strSQL = ""; + + IDbConnection cnnTemp = null; + DbDataReader drTemp, drTemp1; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + bool blnAdd = false; ; + + try + { + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + + try + { + + //add by 14166 for 产品已核准 则不允许进行参数收集 + strSQL = " SELECT * FROM TBLPRDPRODUCTBASIS WHERE PRODUCTNO='" + PRODUCTNO + "' And PRODUCTVERSION='" + PRODUCTVERSION + "' "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + //if (Convert.ToInt32(drTemp["ISSUESTATE"]) == 2) + //{ + // clsERP.combineException(ref aryException, null, null, "[%产品编号:" + PRODUCTNO + " ,产品版本:" + PRODUCTVERSION + " 产品已核准,不允许产品Bom信息收集!%]"); + // // goto exitfun; + //} + + } + else + { + //手动增加一个产品主档 + strSQL = "INSERT INTO TBLPRDPRODUCTBASIS (PRODUCTNO,PRODUCTVERSION,PRODUCTNAME,PRODUCTTYPE,ISSUESTATE,\r\n CREATOR,CREATEDATE,DESCRIPTION,CURVERSION, UNITNO, UNITTYPE, SPECNO,CARTONQTY,PALLETQTY,BOXQTY,LOTSTDQTY, CUSTOMERNO , DEVICENO , ECNCONTROL , BATCHECNLOCK , DATASTAMP , UNITID , PANLEID ) VALUES ('"+ PRODUCTNO +"', '"+ PRODUCTVERSION +"', '"+ PRODUCTNO +"', 'null', '0', 'ERP',sysdate, 'ERP新增', '1', '', '', 'N/A', '0', '0', '0', '0','N/A', 'N/A', 'N', '0', '0', '','')"; + CollectionSQL.Add(strSQL); + // clsERP.combineException(ref aryException, null, null, "[%产品编号:" + PRODUCTNO + " ,产品版本:" + PRODUCTVERSION + " 产品不存在,不允许产品Bom信息收集!%]"); + //goto exitfun; + } + drTemp.Close(); + + + + // ----- Exception => Fail ----- + + foreach (Bomlist dr in bomRequest.Bomlist) + { + int NodeType = 0, PUTINPLACETYPE = 0; + string UnitNo = defString, NODEVERSION = defString; + + + strSQL = "delete from TBLPRDBOM where ProductNo='" + PRODUCTNO + "' and PRODUCTVERSION='" + PRODUCTVERSION + "' and NodeNo='" + dr.MaterialNo.ToString() + "' and OPNO='" + dr.OpNo.ToString() + "'"; + CollectionSQL.Add(strSQL); + strSQL = "delete from TBLPRDBOMMATERIALGROUP where ProductNo='" + PRODUCTNO + "' and PRODUCTVERSION='" + PRODUCTVERSION + "' and NodeNo='" + dr.MaterialNo.ToString() + "' and OPNO='" + dr.OpNo.ToString() + "'"; + CollectionSQL.Add(strSQL); + + strSQL = " SELECT * FROM TBLPRDPRODUCTBASIS WHERE PRODUCTNO='" + dr.MaterialNo.ToString() + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + //说明是半成品物料 + NodeType = 1; + PUTINPLACETYPE = 4; + UnitNo = drTemp["UnitNo"].ToString(); + NODEVERSION = "*"; + } + else + { + //再检查是不是物料 + strSQL = " SELECT * FROM TBLMTLMATERIALBASIS WHERE MATERIALNO='" + dr.MaterialNo.ToString() + "'"; + drTemp1 = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp1.Read()) + { + NodeType = 0; + PUTINPLACETYPE = 2; + UnitNo = drTemp1["UnitNo"].ToString(); + NODEVERSION = "N/A"; + } + else + { + throw new Exception("[%NODENO:" + dr.MaterialNo.ToString() + " 既不是半成品也不是物料,信息错误!%]"); + + //goto exitfun; + } + drTemp1.Close(); + } + drTemp.Close(); + strSQL = "INSERT INTO TBLPRDBOM (PRODUCTNO, PRODUCTVERSION, NODENO, NODETYPE, STDQTY, UNITNO, DECREASERATE, OPNO, SPECIFIED, CREATOR, CREATEDATE, NODEVERSION, PUTINPLACETYPE,AB,PositionCode) " + + "VALUES('" + PRODUCTNO + "', '" + PRODUCTVERSION + "', '" + dr.MaterialNo.ToString() + "', '" + NodeType + "', '" + dr.StdQty.ToString() + "', '" + UnitNo + "', '" + dr.DecreaseRate.ToString() + "', '" + dr.OpNo.ToString() + "', '0', 'ERP', sysdate, '" + NODEVERSION + "', '" + PUTINPLACETYPE + "', '" + dr.AB.ToString() + "', '" + dr.PositionCode.ToString() + "')"; + CollectionSQL.Add(strSQL); + + + if (!string.IsNullOrEmpty(dr.SubstituteMaterialNo.ToString()) && NodeType == 0) + { + string[] SUBMTLS = dr.SubstituteMaterialNo.ToString().Split(','); + for (int i = 0; i < SUBMTLS.Length; i++) + { + strSQL = "INSERT INTO TBLPRDBOMMATERIALGROUP (PRODUCTNO, PRODUCTVERSION, NODENO, OPNO, MATERIALNO) VALUES('" + PRODUCTNO + "', '" + PRODUCTVERSION + "', '" + dr.MaterialNo + "','" + dr.OpNo.ToString() + "','" + SUBMTLS[i].ToString() + "') "; + CollectionSQL.Add(strSQL); + + } + + } + } + + + // 呼叫執行SQL指令 + ExecuteSQLNoneQuery_UPD(strDataBaseType, strConnectionString, CollectionSQL); + result = true; + + + } + catch (Exception ex) + { + // trans.Rollback() + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + } + catch (Exception ex) + { + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + + + } + catch (Exception ex) + { + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + CloseConnection(cnnTemp); + } + + + return result; + } + + #endregion + + + #region + public static bool CheckReelQty(ref List aryMessage, ref List aryException, string reelId, string storageCode, ref string mcode, + ref string qty, ref string vendordate, ref string vendorcode, ref string manufacturer, ref string vendorlotno, ref string snscale, ref bool everExisted) + { + bool CheckReelQty = default(bool); + string strSQL = ""; + + IDbConnection cnnTemp = null; + DbDataReader drTemp, drTemp1; + AppSettings objSetting = new AppSettings(); + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + try + { + // //Create connection + cnnTemp = CreateConnection(strConnectionString); + DataTable dtMaterial = new DataTable(); + //供应商生产日期取自制造日期栏,依WMS送入格式回传YYYYMMDD字串 + //供应商编码、生产厂家、供应商批次、09条码四栏同表取数,栏位由WMS进料写入 + strSQL = $"select MATERIALNO,QTY,To_Char(MANUFACTUREDATE,'YYYYMMDD') as VENDORDATE,VENDORCODE,MANUFACTURER,VENDERLOTNO,SNSCALE from TBLINVWIPINVENTORY_RAW where MATERIALLOTNO = '{reelId}'"; + //仓位有传则以仓别+料卷定位,未传则只以料卷号定位 + if (storageCode != "") + { + strSQL += $" and INVENTORYNO = '{storageCode}'"; + } + ExecuteSQLQuery_Adapter(strSQL, dtMaterial, cnnTemp); + if (dtMaterial.Rows.Count > 0) + { + mcode = dtMaterial.Rows[0]["MATERIALNO"].ToString(); + qty = dtMaterial.Rows[0]["QTY"].ToString(); + vendordate = dtMaterial.Rows[0]["VENDORDATE"].ToString(); + //栏位未写入时为NULL,ToString後即空字串,与既有回传空值行为一致 + vendorcode = dtMaterial.Rows[0]["VENDORCODE"].ToString(); + manufacturer = dtMaterial.Rows[0]["MANUFACTURER"].ToString(); + vendorlotno = dtMaterial.Rows[0]["VENDERLOTNO"].ToString(); + snscale = dtMaterial.Rows[0]["SNSCALE"].ToString(); + everExisted = true; + CheckReelQty = true; + goto exitfun; + } + + //线边仓查无现存量时,再查料卷日志判断该料卷是否曾经存在, + //用以区分「已扣光」与「卷号根本不存在」两种情形 + DataTable dtLog = new DataTable(); + strSQL = $"select count(1) as CNT from TBLINVWIPINVENTORY_RAWLOG where MATERIALLOTNO = '{reelId}'"; + ExecuteSQLQuery_Adapter(strSQL, dtLog, cnnTemp); + if (dtLog.Rows.Count > 0 && Convert.ToDecimal(dtLog.Rows[0]["CNT"]) > 0) + { + everExisted = true; + } + + exitfun: + ; + } + catch (Exception ex) + { + string errorMsg = GetExceptionFullMessage(ex); + throw new Exception(errorMsg); + } + finally + { + CloseConnection(cnnTemp); + } + + + return CheckReelQty; + } + + + #endregion + + + #region MES退料 + /// + /// WMS退料:依REELINFO逐笔扣减线边仓料卷数量,数量不够则清空、不报错 + /// + /// 退料单号 + /// 工单号(仅落客製退料日志备查) + /// 供应仓,对应线边仓的INVENTORYNO + /// 收货仓,仅记录不入账 + /// 料卷明细:REELID/MCODE/QTY + public static bool ReelReturn(ref List aryMessage, ref List aryException, + string mvdCode, string moCode, string fromStorage, string toStorage, + string userCode, string mDate, string mTime, DataTable dtReelInfo) + { + bool ReelReturn = default(bool); + string strSQL = default(string); + IDbConnection cnnTemp = null; + + AppSettings objSetting = new AppSettings(); + var CollectionSQL = new Collection(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + //同一料卷可能在REELINFO内出现多笔,须逐笔累加扣减。 + //因所有SQL累积到最后才一次提交,若每笔都回资料库取现存量, + //第二笔会取到未扣减前的数量而少扣,故在内存累计剩余量。 + var dicLeftQty = new Dictionary(); + //以料卷为单位做扣减与快照时,保持 REELINFO 的出现顺序 + var lstKeyOrder = new List(); + var dicMCode = new Dictionary(); + var dicReelId = new Dictionary(); + + try + { + if (dtReelInfo.Rows.Count == 0) + { + throw new Exception("无明细数据!"); + } + + //操作日期与时间为数字栏,未传则存空值 + string strMDate = mDate.Trim() == "" ? "null" : mDate.Trim(); + string strMTime = mTime.Trim() == "" ? "null" : mTime.Trim(); + + for (int i = 0; i <= dtReelInfo.Rows.Count - 1; i++) + { + string strReelId = dtReelInfo.Rows[i]["REELID"].ToString(); + string strMCode = dtReelInfo.Rows[i]["MCODE"].ToString(); + string strKey = fromStorage + "|" + strMCode + "|" + strReelId; + + //请求扣减量 + decimal REQQTY = 0; + if (dtReelInfo.Rows[i]["QTY"].ToString() != "") + { + REQQTY = Convert.ToDecimal(dtReelInfo.Rows[i]["QTY"]); + } + if (REQQTY <= 0) + { + throw new Exception($"{strReelId}扣减数量不能为0或者负数!"); + } + + //现存量:以仓别+物料+料卷三段键定位 + decimal CURQTY = 0; + if (dicLeftQty.ContainsKey(strKey)) + { + CURQTY = dicLeftQty[strKey]; + } + else + { + DataTable dtRaw = new DataTable(); + strSQL = $"select QTY from TBLINVWIPINVENTORY_RAW where INVENTORYNO = '{fromStorage}' and MATERIALNO = '{strMCode}' and MATERIALLOTNO = '{strReelId}'"; + ExecuteSQLQuery_Adapter(strSQL, dtRaw, cnnTemp); + if (dtRaw.Rows.Count == 0) + { + throw new Exception($"{strReelId}在仓位{fromStorage}找不到对应的料卷!"); + } + if (dtRaw.Rows[0]["QTY"].ToString() != "") + { + CURQTY = Convert.ToDecimal(dtRaw.Rows[0]["QTY"]); + } + } + + //数量不够则清空、不用报错:实扣量最多只扣到现存量, + //不套用标准「保留负数」的写法,短扣差额由客製退料日志的请求量与实扣量留证 + decimal REALQTY = REQQTY; + if (REQQTY > CURQTY) + { + REALQTY = CURQTY; + } + decimal LEFTQTY = CURQTY - REALQTY; + dicLeftQty[strKey] = LEFTQTY; + if (!lstKeyOrder.Contains(strKey)) + { + lstKeyOrder.Add(strKey); + dicMCode[strKey] = strMCode; + dicReelId[strKey] = strReelId; + } + + //① 写客製退料日志:逐笔记录请求量与实扣量,供短扣对帐;收货仓仅记录不入账 + strSQL = @"INSERT INTO TBLINVREELRETURNLOG_LQ(MVDCODE, MOCODE, REELID, MCODE, FROMSTORAGE, TOSTORAGE, REQQTY, REALQTY, USERCODE, MDATE, MTIME, EVENTTIME) "; + strSQL += $" VALUES('{mvdCode}','{moCode}','{strReelId}','{strMCode}','{fromStorage}','{toStorage}',{REQQTY},{REALQTY},'{userCode}',{strMDate},{strMTime},To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'))"; + CollectionSQL.Add(strSQL); + } + + //料卷日志与扣减以「料卷」为单位各做一次,不随 REELINFO 逐笔做: + //TBLINVWIPINVENTORY_RAWLOG 的主键是 (INVENTORYNO, MATERIALNO, MATERIALLOTNO, EVENTTIME), + //EVENTTIME 只到秒,同一料卷若在同批内写入多列快照必然撞主键 ORA-00001 + //(规格 2.2 请求样例的 REELINFO 即同一 REELID 连续两笔)。 + //且标准的 RAWLOG 语义本就是「变更后快照」=最终状态一列,故此处只留最终一列。 + foreach (string strKey in lstKeyOrder) + { + string strMCode = dicMCode[strKey]; + string strReelId = dicReelId[strKey]; + decimal LEFTQTY = dicLeftQty[strKey]; + + //② 扣减线边仓现存量(累加扣减后的最终数量) + strSQL = $"UPDATE TBLINVWIPINVENTORY_RAW SET QTY = {LEFTQTY} WHERE INVENTORYNO = '{fromStorage}' AND MATERIALNO = '{strMCode}' AND MATERIALLOTNO = '{strReelId}'"; + CollectionSQL.Add(strSQL); + + //③ 写料卷日志(扣减后整列快照),必须排在删除资料列之前,否则删除后即无从取数 + strSQL = @"INSERT INTO TBLINVWIPINVENTORY_RAWLOG(INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,EVENTTIME,DATECODE) "; + strSQL += " SELECT INVENTORYNO, MATERIALNO, MATERIALLOTNO, UNITNO, QTY, MATERIALTYPE, INPUTDATE,MANUFACTUREDATE,RECEIPTNO,REELID,EXDATE,To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),DATECODE "; + strSQL += $" FROM TBLINVWIPINVENTORY_RAW WHERE INVENTORYNO = '{fromStorage}' AND MATERIALNO = '{strMCode}' AND MATERIALLOTNO = '{strReelId}'"; + CollectionSQL.Add(strSQL); + + //④ 扣光则删除资料列 + if (LEFTQTY <= 0) + { + strSQL = $"DELETE FROM TBLINVWIPINVENTORY_RAW WHERE INVENTORYNO = '{fromStorage}' AND MATERIALNO = '{strMCode}' AND MATERIALLOTNO = '{strReelId}' AND QTY = 0"; + CollectionSQL.Add(strSQL); + } + } + + if (CollectionSQL.Count > 0) + { + ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL); + } + + ReelReturn = true; + + exitfun: + ; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + finally + { + CloseConnection(cnnTemp); + } + return ReelReturn; + + } + #endregion + } +} \ No newline at end of file diff --git a/MESEAI/EAItc/clsMDS.cs b/MESEAI/EAItc/clsMDS.cs new file mode 100644 index 0000000..5eb33d4 --- /dev/null +++ b/MESEAI/EAItc/clsMDS.cs @@ -0,0 +1,25 @@ + +namespace tcEAI_C +{ + + public class clsMDS + { + + public string strDataBaseType; + public string strConnectionString; + private udReverse.clsReverse objReverse = new udReverse.clsReverse(); + + // 2003/03/22,sammi. + // 因TC可能呼叫KC,在整個Function中,必須要使用同一個Reverse物件,如此在產生AddReverseUpdateContent的資料時,ReverseOrder才不會重覆. + // 若KC再往下呼叫UD,則必須將Reverse物件傳遞予UD. + public udReverse.clsReverse ReverseObj + { + get + { + return objReverse; + } + } + + + } +} \ No newline at end of file diff --git a/MESEAI/EAItc/clsOE.cs b/MESEAI/EAItc/clsOE.cs new file mode 100644 index 0000000..0cddf1f --- /dev/null +++ b/MESEAI/EAItc/clsOE.cs @@ -0,0 +1,2987 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Runtime.InteropServices; +using kcENT; +using kcMTL; +using kcPRD; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; +using iMESCore.Settings; +using static iMESCore.Base.iMESComSubroutine; +using static iMESCore.Base.iMESConst; +using static iMESCore.DataBase.iMESSql; +using static iMESCore.Base.iMESComXML; +using iMESCore.DataBase; +using System.Linq; +using System.Collections.ObjectModel; +using kcSYS; +using kcOE; +using kcOP; +using kcSMD; +using System.Xml; +using kcQC; + +namespace tcEAI_C +{ + + public class clsOE + { + + + public clsOE() + { + + + } + + #region MO + + + /// + /// 新增工單 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool addMO(string Orgcode,string OrgMono, string MONo, string MOUnitNo, string ProductNo, decimal MOQty, string FactoryNo, string RONo = null, string ItemNo = null, string CustomerNo = null, + int MOTypeNo = defInteger, int Priority = defInteger, DateTime PlanFinishDate = default(DateTime), string Creator = null, + DateTime CreateDate = default(DateTime), string Description = null, DataTable dtMTL = null, List MOProperty = null, List aryMessage = null, List aryException = null, + List aryAlert = null, DataTable dtMOProperty = null, string ERPMOLineNo = defString, string CustomerLotNo = null, DateTime PlanStartDate = default(DateTime), int wipEntityId = defInteger, string bomVersion = null, string lcPlantype = null, string faiFlag = null) + { + bool addMORet = default(bool); + + bool r = false; + string strSQLTemp, strSQL = default(string), strSQLAddField, strSQLAddValue; + IDbConnection cnnTemp1 = null; + //OleDbCommand cmmTemp; + DbDataReader drTemp2; + DbDataReader drTemp3; + // Dim daTemp As OleDb.OleDbDataAdapter + // Dim drSel() As DataRow + // Dim strDataBaseType, strConnectionString As String 'Connection string + // Dim i As Integer + // Dim dsTemp As DataSet + AppSettings objSetting = new AppSettings(); + var CollectionSQL = new Collection(); + + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp1 = CreateConnection(strConnectionString); + + // ----- Default Value ----- + int MOSource = 0; // 0: RO, 1: RMA, 2: None + int MOState = 0; // 0: Unconfirm, 1: Pending, 2: Confirm, 3: Release(允許開立生產批), 6: 已在客託倉或退貨倉的工單(允許開立生產批), 99:Close + int IssueState = 0; + string BelongToMONo = "N/A"; + string ENGNo = "N/A"; + string ENGVersion = "N/A"; + //string CustomerLotNo = string.Empty; + // Dim OPNo As String = "LOTCREATE" + + // ---- Get Value ----- + string CustomerName = string.Empty; + string ProductVersion = string.Empty; + string ProcessNo = string.Empty; + string ProcessVersion = string.Empty; + + bool isROExist = false; + bool isRODetailExist = false; + + string ItemProperty = defString; // 2016-10-17, Joe, 新增料件屬性,P:採購件,M:自製件,S:外包件 + int OutSourcingFlag = defInteger; // 2016-10-17, Joe, 0:off,1:on + + // Kevin 15/06/09 ,調整產品編號轉大寫,後續的程式處理並未全部都有轉大寫 + ProductNo = ProductNo.ToUpper(); + + // ----- 1. 檢查MO是否存在 ----- + + MONo = MONo.ToUpper(); + + using (var objOE = new clsOEBasis()) + { + if (objOE.GetMOBasis(MONo.ToUpper())["MONo"] is DBNull == false) + clsERP.combineException(ref aryException, mesmsg: "[%MONoExist%]"); + } + + // ----- 2. 檢查MOSource----- + if (string.IsNullOrEmpty(RONo)) + MOSource = 2; // MO來源為其他(暫不考慮RMA) + + // ----- 3. 檢查CustomerNo是否存在 ----- + if (MOSource == 0) + { + if (string.IsNullOrEmpty(CustomerNo)) + { + // 未傳入 + clsERP.combineException(ref aryException, mesmsg: "[%ROWithOutCustomer%]"); + } + else + { + // 有傳入=>檢查Customer主檔 + using (var objENT = new clsCustomerBasis()) + { + var dr = objENT.GetCustomerBasis(CustomerNo.ToUpper()); + if (dr["CustomerNo"] is DBNull == true) + { + // Customer主檔未建立 + // clsERP.combineException(aryException, , , "[%CustomerNoNotExist%]") + + // 5.3 若拋入訂單號碼,則必須拋入客戶編號,系統應檢查tblENTCustomerBasis之中是否存在此客戶,若無則自動新增 + objENT.AddCustomerBasis(CustomerNo.ToUpper(), CustomerNo, CustomerNo, "NULL", "NULL", "NULL", "NULL", "NULL", "NULL"); + objENT.SetCustomerBasisIssueState(CustomerNo.ToUpper(), 2); + } + else + { + CustomerName = dr["CustomerName"].ToString(); + } + } + } + } + + // ----- 4. 檢查Product ----- + using (var objPRD = new clsProduct()) + { + var dr = objPRD.GetProduct(ProductNo.ToUpper()); + if (dr["ProductNo"] is DBNull == true) + clsERP.combineException(ref aryException, mesmsg: "[%ProductNoNotExist%]"); + if (dr["ProductNo"] is DBNull == false && Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["IssueState"], 2, false))) + clsERP.combineException(ref aryException, mesmsg: "[%ProductNoNotApproved%]"); + + // ----- 5. 檢查MOUnitNo ----- + if (dr["ProductNo"] is DBNull == false && dr["UnitNo"].ToString().ToLower() != MOUnitNo.ToLower()) + clsERP.combineException(ref aryException, mesmsg: "[%ProductMOWithDifferentUnitNo%]"); + dr.Delete(); + + try + { + ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper()); + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, mesmsg: "[%GetProductVersionFail%]"); + } + + // 2016-10-17, Joe, 取得ItemProperty + var drItemProperty = objPRD.GetProductProperty(ProductNo, ProductVersion, "ItemProperty"); + if (drItemProperty == null == false && drItemProperty["DefaultValue"] is DBNull == false) + { + ItemProperty = drItemProperty["DefaultValue"].ToString(); + } + // 2016-10-17, Joe, 取得外包控制 + using (var objSYS = new clsSYSParameter()) + { + OutSourcingFlag = Conversions.ToInteger(objSYS.GetParameterValue("OutSourcingFlag")); + } + // 2016-10-17, Joe, 若該產品品號屬性屬於S且外包控管參數為Off時,MES不做工單新增/修改,直接回應OK,但訊息應回傳『MES系統不支持外包工單』 + if (ItemProperty == "S" & OutSourcingFlag == 0) + { + // 2018/06/26 Lena, 修正訊息語系未譯的問題. + clsERP.combineException(ref aryException, mesmsg: "[%ProductNo%]:" + ProductNo + ",[%ProductVersion%]:" + ProductVersion + ",[%IsOutSourcingProduct%], MES [%IsNotSupported%] !"); + if (aryException.Count > 0) + goto exitfun; + } + + // ----- 6. 檢查ProductProcess是否存在 ----- + // 2012/07/26, Aaron, 如果傳入的MOTypeNo找不到就用-1(*)找尋預設值,再找不到彈出錯誤 + dr = objPRD.GetProductProcess(ProductNo.ToUpper(), ProductVersion, MOTypeNo, DefaultProcess: 1); + if (dr["ProductNo"] is DBNull == true) + { + dr = objPRD.GetProductProcess(ProductNo.ToUpper(), ProductVersion, -1, DefaultProcess: 1); + if (dr["ProductNo"] is DBNull == true) + clsERP.combineException(ref aryException, mesmsg: "[%ProductProcessNoNotExist%]"); + } + } + + // ----- 7. 檢查用料清單資料 ----- + var objPRD_M = new kcPRD.clsProduct(); + DataView dvTemp; + var objMTL = new kcMTL.clsMTLBasis(); + var dsBOM = new DataSet(); + DataRow drData; + + System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); // 用以讀取Xml字串 + + // 工單用料表 + var dtMOBom = new DataTable("MOBom"); + dtMOBom.Columns.Add("MONo", Type.GetType("System.String")); + dtMOBom.Columns.Add("MaterialLevel", Type.GetType("System.Int32")); // 0:Material,1:Product + dtMOBom.Columns.Add("MaterialNo", Type.GetType("System.String")); + dtMOBom.Columns.Add("MaterialVersion", Type.GetType("System.String")); + dtMOBom.Columns.Add("StdQty", Type.GetType("System.Double")); + dtMOBom.Columns.Add("DecreaseRate", Type.GetType("System.Double")); + dtMOBom.Columns.Add("UnitNo", Type.GetType("System.String")); + dtMOBom.Columns.Add("OPNo", Type.GetType("System.String")); + dtMOBom.Columns.Add("PutInPlaceType", Type.GetType("System.Int32")); + dtMOBom.Columns.Add("Specified", Type.GetType("System.Int32")); // 0:No,1:Yes + dtMOBom.Columns.Add("MOFlag", Type.GetType("System.Int32")); // 0:Create MO,1:來自半成品庫,不用開立工單 + dtMOBom.Columns.Add("MaterialMONo", Type.GetType("System.String")); // 半成品的工單編號 + dtMOBom.Columns.Add("Description", Type.GetType("System.String")); // Bom Material Description + dtMOBom.Columns.Add("SubstituteMaterialNo", Type.GetType("System.String")); // 替代料,預設值同MaterialNo + dtMOBom.Columns.Add("SubstituteMaterialLevel", Type.GetType("System.Int32")); // 替代料等級,預設值同物料等級(materialLevel) + dtMOBom.Columns.Add("SubstituteStdQty", Type.GetType("System.Decimal")); // 替代料標準數量,預設值=標準數量StdQty + dtMOBom.Columns.Add("RequireQty", Type.GetType("System.Decimal")); // 需求數,預設值=工單數量MoQty * 標準數StdQty + dtMOBom.Columns.Add("AB", Type.GetType("System.String")); // 需求數,預設值=工單數量MoQty * 標準數StdQty + dtMOBom.Columns.Add("PositionCode", Type.GetType("System.String")); // 需求數,預設值=工單數量MoQty * 標準數StdQty + + + // 1.工單的單位可能與用料表(tblOEMOMaterialList)的標準單位(產品的單位)不同---------------------------------------------------- + // 故須以工單數量,單位換算出產品的標準量 + DataRow drTemp; + string strStdUnitNo; + double dblStdQty; + + // 工單開立,產品不一定是CurVersion. + drTemp = objPRD_M.GetProduct(ProductNo, ProductVersion, CurVersion: defInteger); + if (drTemp["ProductNo"] is DBNull) + { + throw new iMESException.MESException("0000-200002", "Get product data of ProductNo:" + ProductNo + ", Version:" + ProductVersion + " fail !"); + } + + strStdUnitNo = Conversions.ToString(drTemp["UnitNo"]); // 標準單位 + if ((strStdUnitNo.ToUpper() ?? "") == (MOUnitNo.ToUpper() ?? "")) // 單位相同 + { + dblStdQty = Conversions.ToDouble(MOQty); + } + else + { + // 將CurQty轉換為產品標準單位之數量 + udUnitTransferFunction.clsUnitTransferFunction objUnit; + var colParameters = new Collection(); + colParameters.Add(ProductNo, "ProductNo"); + colParameters.Add(ProductVersion, "ProductVersion"); + colParameters.Add(ENGNo, "ENGNo"); + colParameters.Add(ENGVersion, "ENGVersion"); + objUnit = new udUnitTransferFunction.clsUnitTransferFunction(); + dblStdQty = Conversions.ToDouble(objUnit.EXETransferQty(MOUnitNo, strStdUnitNo, Conversions.ToDouble(MOQty), colParameters)); + objUnit = null; + } + decimal DecreaseRate = 0m; + + dsBOM = objPRD_M.ShowBOM(ProductNo, ProductVersion); + var loopTo2 = dsBOM.Tables[0].Rows.Count - 1; + for (int i = 0; i <= loopTo2; i++) + { + drData = dtMOBom.NewRow(); + drData["MONo"] = MONo; + drData["MaterialLevel"] = dsBOM.Tables[0].Rows[i]["NodeType"]; + DecreaseRate = Conversions.ToDecimal(dsBOM.Tables[0].Rows[i]["DecreaseRate"]); // 取得耗損率 + + // 2008/06/17,sammi,投料點來自BOM表的設定. + drData["PutInPlaceType"] = dsBOM.Tables[0].Rows[i]["PutInPlaceType"]; + if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dsBOM.Tables[0].Rows[i]["NodeType"], 1, false))) // Product + { + drData["MOFlag"] = 0; + drData["MaterialMONo"] = MONo; + // NodeVersion,取出已轉換的產品版本. + drData["MaterialVersion"] = ProductVersion; + } + else // Material (NodeType = 0) + { + drData["MOFlag"] = 1; + drData["MaterialMONo"] = "N/A"; + drData["MaterialVersion"] = dsBOM.Tables[0].Rows[i]["NodeVersion"]; + } + drData["MaterialNo"] = dsBOM.Tables[0].Rows[i]["NodeNo"]; + drData["SubstituteMaterialNo"] = dsBOM.Tables[0].Rows[i]["NodeNo"]; // 替代料,預設值同MaterialNo + drData["StdQty"] = dsBOM.Tables[0].Rows[i]["StdQty"]; + drData["DecreaseRate"] = dsBOM.Tables[0].Rows[i]["DecreaseRate"]; + drData["UnitNo"] = dsBOM.Tables[0].Rows[i]["UnitNo"]; + drData["OPNo"] = dsBOM.Tables[0].Rows[i]["OPNo"]; + drData["Specified"] = dsBOM.Tables[0].Rows[i]["Specified"]; + drData["Description"] = Strings.Replace(dsBOM.Tables[0].Rows[i]["Description"].ToString(), "'", "''"); + drData["SubstituteMaterialLevel"] = dsBOM.Tables[0].Rows[i]["NodeType"]; // 2012/12/27,Even,替代料等級,預設值為物料等級 + drData["SubstituteStdQty"] = dsBOM.Tables[0].Rows[i]["StdQty"]; // 2012/12/28,Even,替代料標準數,預設值為 標準數 + drData["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dsBOM.Tables[0].Rows[i]["StdQty"]), 1m + DecreaseRate); // 2012/12/27,Even,需求數,預設值為工單數 * 標準數 + drData["AB"] = dsBOM.Tables[0].Rows[i]["AB"].ToString(); + drData["PositionCode"] = dsBOM.Tables[0].Rows[i]["PositionCode"].ToString(); + dtMOBom.Rows.Add(drData); + } + + dsBOM.Dispose(); + // Add MO之用料表 + dvTemp = new DataView(dtMOBom); + dvTemp.RowFilter = Conversions.ToString("MONo='" + MONo + "'"); + + var loopTo8 = dvTemp.Count - 1; + for (int j = 0; j <= loopTo8; j++) + { + DecreaseRate = Conversions.ToDecimal(dvTemp[j]["DecreaseRate"]); + decimal decRequireQty = Conversions.ToDecimal(Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dvTemp[j]["StdQty"]), 1m + DecreaseRate)); + + // '2012/12/27,Even,改變需求數 + dvTemp[j].BeginEdit(); + // dvTemp.Table.Rows(j)("RequireQty") = dtMO.Rows(i)("MOQty") * dvTemp.Table.Rows(j)("StdQty") * (1 + DecreaseRate) + dvTemp[j]["RequireQty"] = decRequireQty; + dvTemp[j].EndEdit(); + + AddMOMaterialList(Conversions.ToString(MONo), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToInteger(dvTemp[j]["MaterialLevel"]), Conversions.ToDouble(dvTemp[j]["StdQty"]), Conversions.ToDouble(dvTemp[j]["DecreaseRate"]), Conversions.ToString(dvTemp[j]["OPNo"]), Conversions.ToInteger(dvTemp[j]["Specified"]), Conversions.ToInteger(dvTemp[j]["PutInPlaceType"]), Conversions.ToString(dvTemp[j]["UnitNo"]), Conversions.ToInteger(dvTemp[j]["MOFlag"]), Conversions.ToString(dvTemp[j]["MaterialMONo"]), dvTemp[j]["Description"].ToString(), CollectionSQL, MaterialVersion: Conversions.ToString(dvTemp[j]["MaterialVersion"]), SubstituteMaterialNo: Conversions.ToString(dvTemp[j]["MaterialNo"]), SubstituteMaterialLevel: Conversions.ToInteger(dvTemp[j]["SubstituteMaterialLevel"]), RequireQty: Conversions.ToDecimal(dvTemp[j]["RequireQty"]), SubstituteStdQty: Conversions.ToDecimal(dvTemp[j]["SubstituteStdQty"]), Creator: Creator, CreateDate: DateTime.Now, AB:Conversions.ToString(dvTemp[j]["AB"]), PositionCode:Conversions.ToString(dvTemp[j]["PositionCode"])); + + // R1203001 不是指定用料及半成品時才處理替代料 By Acer 2012/03/06 + if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dvTemp[j]["Specified"], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(dvTemp[j]["MaterialLevel"], 0, false))) + { + var dsSubstitute = new DataSet(); + if (objPRD_M.ShowBOMMaterialGroup(Conversions.ToString(ProductNo), Conversions.ToString(ProductVersion), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToString(dvTemp[j]["OPNo"])).Tables[0].Rows.Count > 0) + { + // 處理BOM表中指定的替代料 + dsSubstitute = objPRD_M.ShowBOMMaterialGroup(Conversions.ToString(ProductNo), Conversions.ToString(ProductVersion), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToString(dvTemp[j]["OPNo"])); + } + else + { + // 處理物料群組中指定的替代料 + dsSubstitute = objMTL.ShowMaterialSubstitute(Conversions.ToString(dvTemp[j]["MaterialNo"])); + } + + var loopTo9 = dsSubstitute.Tables[0].Rows.Count - 1; + for (int k = 0; k <= loopTo9; k++) + { + // 2012/12/27,Even,處裡替代用料的需求數量,有替代用料,用料清單會除原先清單外再加上替代用料清單 + decimal dblRequireQty = 0m * (1m + DecreaseRate); + + AddMOMaterialList(Conversions.ToString(MONo), Conversions.ToString(dvTemp[j]["MaterialNo"]), Conversions.ToInteger(dvTemp[j]["MaterialLevel"]), Conversions.ToDouble(dvTemp[j]["StdQty"]), Conversions.ToDouble(dvTemp[j]["DecreaseRate"]), Conversions.ToString(dvTemp[j]["OPNo"]), Conversions.ToInteger(dvTemp[j]["Specified"]), Conversions.ToInteger(dvTemp[j]["PutInPlaceType"]), Conversions.ToString(dvTemp[j]["UnitNo"]), Conversions.ToInteger(dvTemp[j]["MOFlag"]), Conversions.ToString(dvTemp[j]["MaterialMONo"]), dvTemp[j]["Description"].ToString(), CollectionSQL, MaterialVersion: Conversions.ToString(dvTemp[j]["MaterialVersion"]), SubstituteMaterialNo: dsSubstitute.Tables[0].Rows[k]["MaterialNo"].ToString(), SubstituteMaterialLevel: Conversions.ToInteger(dvTemp[j]["SubstituteMaterialLevel"]), RequireQty: dblRequireQty, SubstituteStdQty: Conversions.ToDecimal(dvTemp[j]["SubstituteStdQty"]), Creator: Creator, CreateDate: DateTime.Now, AB: Conversions.ToString(dvTemp[j]["AB"]), PositionCode: Conversions.ToString(dvTemp[j]["PositionCode"])); + + } + dsSubstitute = null; + } + + } + #region"注释原收用料清单逻辑 继承 PRDBOM" + + //if (dtMTL.Rows.Count > 0) + //{ + // bool blnWF = false; + // //2023/12/07,Ning,151196: [6.0.7] SDD231107_01-01_WF 工單整合接口調整 + // //取得目前ERP是否為WF + // using (var objSYSPar = new kcSYS.clsSYSParameter()) + // { + // var dsTemp = new DataSet(); + // dsTemp = objSYSPar.ShowERPSetting(ActiveERP: 1); + // if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0) + // { + // if (dsTemp.Tables[0].Rows[0]["ERP_Name"].ToString().ToUpper() == "WORKFLOW") + // { + // blnWF = true; + // } + // } + // } + + // dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String")); + // // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo + + // foreach (DataRow dr in dtMTL.Rows) + // { + // string strMaterialUnit = dr["UnitNo"].ToString(); + // decimal decTemp = 0m; + // try + // { + // if (string.IsNullOrEmpty(dr["MainItem"].ToString())) + // { + // // 未傳入 + // clsERP.combineException(ref aryException, mesmsg: "[%MainItem%]"); + // } + + // //if (string.IsNullOrEmpty(dr["PhantomItem"].ToString())) + // //{ + // // // 未傳入 + // // clsERP.combineException(ref aryException, mesmsg: "[%PhantomItem%]"); + // //} + + // if (string.IsNullOrEmpty(dr["LockRequirement"].ToString())) + // { + // // 未傳入 + // clsERP.combineException(ref aryException, mesmsg: "[%LockRequirement%]"); + // } + + // if (string.IsNullOrEmpty(dr["OperationSeqnum"].ToString())) + // { + // // 未傳入 + // clsERP.combineException(ref aryException, mesmsg: "[%OperationSeqnum%]"); + // } + + // if (blnWF == true) + // { + // if (Conversions.ToInteger(dr["StdQty"]) != Convert.ToDecimal(dr["StdQty"])) //若標準用量有小數, 需以ERP所傳入的該物料的需領用量(RequireQty)/預計產量(MOQty),並以無條件捨去取到小數六位數的值,做為該物料的標準用量 + // { + // decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000; + // decTemp = Math.Floor(decTemp); + // decTemp = decTemp / 1000000; + // dr["StdQty"] = decTemp; + // } + // if (Conversions.ToInteger(dr["SubstituteStdQty"]) != Convert.ToDecimal(dr["SubstituteStdQty"])) //若替代料標準用量有小數同標準用量處理 + // { + // decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000; + // decTemp = Math.Floor(decTemp); + // decTemp = decTemp / 1000000; + // dr["SubstituteStdQty"] = decTemp; + // } + // } + // if (dr["MaterialLevel"].ToString() == "0") + // { + // // 用料清單為物料 + // using (var objMTL = new clsMTLBasis()) + // { + // DataRow drMTL = null; + // bool errorFlag = false; + + // dr["MONo"] = dr["MONo"].ToString().ToUpper(); + + // drMTL = objMTL.GetMaterialBasis(dr["MaterialNo"].ToString().ToUpper()); + // // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion + + // // MaterialNo + // if (drMTL["MaterialNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" + + // dr["MaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsMaterial%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper(); + // } + + // // UnitNo + // if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + // { + // // 當用料清單和物料主檔的單位不同時 + // // 單位轉換 + // using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + // { + // var colParameters = new Collection(); + // colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + // colParameters.Add("*", "ProductVersion"); + + // try + // { + // dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters)); + // dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters)); + + // dr["UnitNo"] = drMTL["UnitNo"].ToString().ToLower(); + // } + // catch (Exception ex) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + // } + // } + // } + // else + // { + // dr["UnitNo"] = dr["UnitNo"].ToString().ToLower(); + // } + + // // MaterialMONo (Default) + // dr["MaterialMONo"] = "N/A"; + + // // MaterialType + // if (dr["MaterialType"] is DBNull == true) + // { + // dr["MaterialType"] = drMTL["MaterialType"]; + // } + // else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drMTL["MaterialType"], false))) + // { + // dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper(); + // } + // else + // { + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // } + + // // CheckLotNo + // if (dr["CheckLotNo"] is DBNull == true) + // { + // dr["CheckLotNo"] = drMTL["CheckLotNo"]; + // } + // else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["CheckLotNo"], drMTL["CheckLotNo"], false))) + // { + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListCheckLotNoDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // } + + // // 2013/02/20,Even,修改替代料檢查 + // if (dr["SubstituteMaterialNo"] is DBNull == true) + // { + // dr["SubstituteMaterialNo"] = dr["MaterialNo"]; + // dr["SubstituteMaterialLevel"] = dr["MaterialLevel"]; + // } + // // 2013/02/25,Even,判斷替代料,替代料可為半成品或是物料 + // else if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料 + // { + // // 查詢替代料是否在物料主檔內,若無,則出現錯誤訊息 + // drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper()); + // if (drMTL["MaterialNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + // dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + // } + // } + // else // 為半成品 (SubstituteMaterialLevel = 1) + // { + // DataRow drPRD = null; + // // 檢查物料是否存在於產品主檔 + // using (var objPRD = new clsProduct()) + // { + // drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper()); + // } + // if (drPRD["ProductNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + // dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + // } + // } + + // if (dr["SubstituteStdQty"] is DBNull == true) + // { + // dr["SubstituteStdQty"] = dr["StdQty"]; + // } + + // // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換 + // decimal decRequireQty = 0m; + // if (dr["RequireQty"] is DBNull == true) + // { + // // ERP未傳入需求數(RequireQty) + // // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + // dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"])); + // } + // else + // { + // decRequireQty = Convert.ToDecimal(dr["RequireQty"]); + // // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + // if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + // { + // // 當用料清單和物料主檔的單位不同時 + // using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + // { + // var colParameters = new Collection(); + // colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + // colParameters.Add("*", "ProductVersion"); + // try + // { + // dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters)); + // } + // catch (Exception ex) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + // } + // } + // } + // else + // { + // dr["RequireQty"] = decRequireQty; + // } + // } + + // // 檢查OPNo(用料作業站)是否存在 ----- + // if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE") + // { + // // 有傳入=>檢查OP主檔 + // using (var objOP = new clsOpBasis()) + // { + // var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper()); + // if (drOP["OPNo"] is DBNull == true) + // { + // // OP主檔未建立 + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialNo%]:" + + // dr["MaterialNo"] + " [%OPNoNotExist%](" + dr["OPNo"] + ")"); + // } + // } + // } + + // } + // } + // else + // { + // // 用料清單為半成品 + // using (var objPRD = new clsProduct()) + // { + // DataRow drPRD = null; + // bool errorFlag = false; + + // dr["MONo"] = dr["MONo"].ToString().ToUpper(); + + // drPRD = objPRD.GetProduct(dr["MaterialNo"].ToString().ToUpper()); + // // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion + + // // MaterialNo + // if (drPRD["ProductNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" + + // dr["MaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsProduct%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper(); + // } + + // // UnitNo + // if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + // { + // // 當用料清單和物料主檔的單位不同時 + // // 單位轉換 + // using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + // { + // var colParameters = new Collection(); + // colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + // colParameters.Add("*", "ProductVersion"); + + // try + // { + + // dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters)); + // dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters)); + + // dr["UnitNo"] = drPRD["UnitNo"].ToString().ToLower(); + // } + // catch (Exception ex) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + // } + // } + // } + // else + // { + // dr["UnitNo"] = dr["UnitNo"].ToString().ToLower(); + // } + + // // MaterialMONo (Default) + // dr["MaterialMONo"] = "N/A"; + + // // MaterialType + // if (dr["MaterialType"] is DBNull == true) + // { + // dr["MaterialType"] = drPRD["ProductType"]; + // } + // else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drPRD["ProductType"], false))) + // { + // dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper(); + // } + // else + // { + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // } + + // // CheckLotNo + // dr["CheckLotNo"] = 1; // 半成品固定為1 + + // // SubstituteMaterialNo + // // ---2013/02/20,Even,替代料是否存在的檢查---- + // if (dr["SubstituteMaterialNo"] is DBNull == true) + // { + // dr["SubstituteMaterialNo"] = dr["MaterialNo"]; + // dr["SubstituteMaterialLevel"] = dr["MaterialLevel"]; + // } + // else + // { + // DataRow drMTL = null; + // // 2013/02/25,Even,判斷替代料,替代料可為半成品或是物料 + // if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料 + // { + // // 查詢替代料是否在物料主檔內,若無,則出現錯誤訊息 + // using (var objMTL = new clsMTLBasis()) + // { + // drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper()); + // } + + // if (drMTL["MaterialNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + // dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + // } + // } + // else // 為半成品 (SubstituteMaterialLevel = 1) + // { + // // 檢查物料是否存在於產品主檔 + // drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper()); + // if (drPRD["ProductNo"] is DBNull == true) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + // dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%]."); + // goto SkipMaterialList; + // } + // else + // { + // dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + // } + // } + // } + + // if (dr["SubstituteStdQty"] is DBNull == true) + // { + // dr["SubstituteStdQty"] = dr["StdQty"]; + // } + + + // // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換 + // decimal decRequireQty = 0m; + // if (dr["RequireQty"] is DBNull == true) + // { + // // ERP未傳入需求數(RequireQty) + // // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + // dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"])); + // } + // else + // { + // decRequireQty = Convert.ToDecimal(dr["RequireQty"]); + // // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + // if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + // { + // // 當用料清單和產品主檔的單位不同時 + // using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + // { + // var colParameters = new Collection(); + // colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + // colParameters.Add("*", "ProductVersion"); + // try + // { + // dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters)); + // } + // catch (Exception ex) + // { + // errorFlag = true; + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + // dr["MaterialNo"]); + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + // } + // } + // } + // else + // { + // dr["RequireQty"] = decRequireQty; + // } + // } + + // // 檢查OPNo(用料作業站)是否存在 ----- + // if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE") + // { + // // 有傳入=>檢查OP主檔 + // using (var objOP = new clsOpBasis()) + // { + // var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper()); + // if (drOP["OPNo"] is DBNull == true) + // { + // // OP主檔未建立 + // clsERP.combineException(ref aryException, mesmsg: "[%MaterialNo%]:" + + // dr["MaterialNo"] + " [%OPNoNotExist%](" + dr["OPNo"] + ")"); + // } + // } + // } + // } + // } + + // SkipMaterialList: + // ; + // } + + // catch (Exception ex) + // { + // clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + // } + // } + //} + #endregion + + // ----- 8. 檢查FactoryNo ----- + // FactoryNo = "N/A" + List argstrMessage = null; + List argstrException = null; + doFactoryNo(FactoryNo, Creator, CreateDate, strMessage: argstrMessage, strException: argstrException); + + // ----- 9. 檢查MO Property --- + if (!(dtMOProperty == null) && dtMOProperty.Rows.Count > 0) + { + foreach (DataRow dr in dtMOProperty.Rows) + { + List argaryMessage = null; + List argaryException = null; + doSYSMOProperty(Convert.ToString(dr["PropertyNo"]), Convert.ToString(dr["DataType"]), aryMessage: argaryMessage, aryException: argaryException); + } + } + + // ----- Exception => Fail ----- + if (aryException.Count > 0) + goto exitfun; + + // ----- Add MO ----- + // Dim objLic As New iMESLicxManager.clsDBCom + // Using cn As New OleDbConnection(objSetting.GetConnectionString) + // Using cmd As New OleDbCommand("", cn) + // cn.Open() + // Using trans As OleDbTransaction = cn.BeginTransaction + // cmd.Transaction = trans + try + { + + if (string.IsNullOrEmpty(RONo) == false) + { + var objOE = new clsOEBasis(); + // 檢查訂單是否已存在 + var dr = objOE.GetROBasis(RONo.ToUpper()); + if (dr["RONo"] is DBNull == false) + isROExist = true; + + // 檢查訂單明細是否已存在 + // 若訂單號碼有傳入,此項目應一併傳入,若未傳入則預設為1 + if (string.IsNullOrEmpty(ItemNo)) + ItemNo = "1"; + dr = objOE.GetRODetail(RONo.ToUpper(), Convert.ToDecimal(ItemNo.ToUpper())); + if (dr["ItemNo"] is DBNull == false) + { + isRODetailExist = true; + } + + // ----- RO ----- + if (isROExist == false) + { + // add ROBasis + strSQL = "insert into tbloerobasis(rono,customerno,creator,createdate,issuestate,rostate) values('" + RONo.ToUpper() + "','" + CustomerNo.ToUpper() + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),2,2)"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "insert into tbloerobasis(rono,customerno,description,creator,createdate,issuestate,lotserial,rostate) values(?,?,?,?,?,?,?,?)" + // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper) + // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper) + // cmd.Parameters.AddWithValue(":Description", DBNull.Value) + // cmd.Parameters.AddWithValue(":Creator", Creator) + // cmd.Parameters.AddWithValue(":CreateDate", CreateDate) + // cmd.Parameters.AddWithValue(":IssueState", 2) + // cmd.Parameters.AddWithValue(":LotSerial", DBNull.Value) + // cmd.Parameters.AddWithValue(":ROState", 2) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + } + + switch (isRODetailExist) + { + case true: + { + // update RODetail + strSQL = "update tbloerodetail set orderqty=orderqty+" + MOQty + ", unreleaseqty=unreleaseqty+" + MOQty; + strSQL += "where RONO='" + RONo.ToUpper() + "' and ItemNo=" + ItemNo.ToUpper(); + break; + } + // Gary Lu 20130307:原本無Where條件,不修正會使得TBLOERODETAIL內其他訂單明細也受到影響 + // cmd.CommandText = _ + // "update tbloerodetail set orderqty=orderqty+?, unreleaseqty=unreleaseqty+?" + // cmd.Parameters.AddWithValue(":OrderQty", MOQty) + // cmd.Parameters.AddWithValue(":UnReleaseQty", MOQty) + case false: + { + // add RODetail + strSQL = "insert into tbloerodetail(rono,itemno,productno,orderqty,unreleaseqty,creator,createdate,rounitno,customerno,customername) " + "values('" + RONo.ToUpper() + "'," + ItemNo + ",'" + ProductNo.ToUpper() + "'," + MOQty + "," + MOQty + ",'" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + MOUnitNo.ToLower() + "','" + CustomerNo.ToUpper() + "','" + ChkSingleQuation(CustomerName) + "')"; + break; + } + // cmd.CommandText = _ + // "insert into tbloerodetail(rono,itemno,productno,orderqty,unreleaseqty,description,creator,createdate,rounitno,customerno,customername) " & _ + // "values(?,?,?,?,?,?,?,?,?,?,?)" + // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper) + // cmd.Parameters.AddWithValue(":ItemNo", ItemNo) + // cmd.Parameters.AddWithValue(":ProductNo", ProductNo.ToUpper) + // cmd.Parameters.AddWithValue(":OrderQty", MOQty) + // cmd.Parameters.AddWithValue(":UnReleaseQty", MOQty) + // cmd.Parameters.AddWithValue(":Description", DBNull.Value) + // cmd.Parameters.AddWithValue(":Creator", Creator) + // cmd.Parameters.AddWithValue(":CreateDate", CreateDate) + // cmd.Parameters.AddWithValue(":ROUnitNo", MOUnitNo.ToLower) + // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper) + // cmd.Parameters.AddWithValue(":CustomerName", CustomerName) + } + CollectionSQL.Add(strSQL); + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + } + + // ----- MO ----- + + // 2019/08/16 Mantis60378: 新增FromERP欄位, 若來自EAI整合(TT、WF、T100),需填入1 + // add MO Basis + strSQLAddField = "insert into tblOEMOBasis(mono,mostate,moqty,productno,productversion,priority,planfinishdate," + "belongtomono,description,creator,createdate,issuestate,unreleaselotqty,mounitno,motypeno,mosource,engno,engversion,customerno,factoryno" + ", FromERP,wipEntityId,bomVersion,lcPlantype,faiFlag"; + strSQLAddValue = "values('" + MONo.ToUpper() + "'," + MOState + "," + MOQty + ",'" + ProductNo.ToUpper() + "','" + ProductVersion.ToUpper() + "'," + Priority + ",To_Date('" + Strings.Format(PlanFinishDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'),'" + BelongToMONo + "','" + Description + "','" + Creator + "',To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')," + IssueState + "," + MOQty + ",'" + MOUnitNo.ToLower() + "'," + MOTypeNo + "," + MOSource + ",'" + ENGNo + "','" + ENGVersion + "','" + CustomerNo.ToUpper() + "','" + FactoryNo + "'," + "1," + wipEntityId + ",'" + bomVersion + "','" + lcPlantype + "','" + faiFlag + "'"; + if (string.IsNullOrEmpty(RONo) == true) + { + strSQLAddField += ",rono"; + strSQLAddValue += ",'N/A'"; + } + else + { + strSQLAddField += ",rono"; + strSQLAddValue += ",'" + RONo.ToUpper() + "'"; + } + if (string.IsNullOrEmpty(Orgcode) == true) + { + strSQLAddField += ",Orgcode"; + strSQLAddValue += ",'N/A'"; + } + else + { + strSQLAddField += ",Orgcode"; + strSQLAddValue += ",'" + Orgcode + "'"; + } + if (string.IsNullOrEmpty(OrgMono) == true) + { + strSQLAddField += ",OrgMono"; + strSQLAddValue += ",'N/A'"; + } + else + { + strSQLAddField += ",OrgMono"; + strSQLAddValue += ",'" + OrgMono + "'"; + } + + if (string.IsNullOrEmpty(ItemNo) == true) + { + strSQLAddField += ",itemno"; + strSQLAddValue += ",-1"; + } + else + { + strSQLAddField += ",itemno"; + strSQLAddValue += "," + ItemNo; + } + if (!string.IsNullOrEmpty(CustomerLotNo)) + { + strSQLAddField += ",customerlotno"; + strSQLAddValue += ",'" + CustomerLotNo + "'"; + } + + // 2018/3/19 Vick 新增欄位 ERPMOLineNo + if (ERPMOLineNo != defString) + { + strSQLAddField += ",ERPMOLineNo"; + strSQLAddValue += ",'" + ERPMOLineNo + "'"; + } + + if (PlanStartDate != default(DateTime)) + { + strSQLAddField += ",PlanStartDate"; + strSQLAddValue += ", To_Date('" + Strings.Format(PlanStartDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')"; + } + + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "insert into tbloemobasis(mono,rono,itemno,mostate,moqty,productno,productversion,priority,planfinishdate,belongtomono,description,creator,createdate," & _ + // "issuestate,unreleaselotqty,mounitno,lotserial,motypeno,mosource,engno,engversion,customerno,incomingkey,customerlotno,factoryno) " & _ + // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) + // If String.IsNullOrEmpty(RONo) = True) + // cmd.Parameters.AddWithValue(":RONo", "N/A") + // Else + // cmd.Parameters.AddWithValue(":RONo", RONo.ToUpper) + // End If + // If String.IsNullOrEmpty(ItemNo) = True) + // cmd.Parameters.AddWithValue(":ItemNo", -1) + // Else + // cmd.Parameters.AddWithValue(":ItemNo", ItemNo) + // End If + // cmd.Parameters.AddWithValue(":MOState", MOState) + // cmd.Parameters.AddWithValue(":MOQty", MOQty) + // cmd.Parameters.AddWithValue(":ProductNo", ProductNo.ToUpper) + // cmd.Parameters.AddWithValue(":ProductVersion", ProductVersion.ToUpper) + // cmd.Parameters.AddWithValue(":Priority", Priority) + // cmd.Parameters.AddWithValue(":PlanFinishDate", PlanFinishDate) + // cmd.Parameters.AddWithValue(":BelongToMONo", BelongToMONo) + // cmd.Parameters.AddWithValue(":Description", Description) + // cmd.Parameters.AddWithValue(":Creator", Creator) + // cmd.Parameters.AddWithValue(":CreateDate", CreateDate) + // cmd.Parameters.AddWithValue(":IssueState", IssueState) + // cmd.Parameters.AddWithValue(":UnReleaseLotQty", MOQty) + // cmd.Parameters.AddWithValue(":MOUnitNo", MOUnitNo.ToLower) + // cmd.Parameters.AddWithValue(":LotSerial", DBNull.Value) + // cmd.Parameters.AddWithValue(":MOTypeNo", MOTypeNo) + // cmd.Parameters.AddWithValue(":MOSource", MOSource) + // cmd.Parameters.AddWithValue(":EngNo", ENGNo) + // cmd.Parameters.AddWithValue(":EngVersion", ENGVersion) + // cmd.Parameters.AddWithValue(":CustomerNo", CustomerNo.ToUpper) + // cmd.Parameters.AddWithValue(":IncomingKey", DBNull.Value) + // If CustomerLotNo = String.Empty) + // cmd.Parameters.AddWithValue(":CustomerLotNo", DBNull.Value) + // Else + // cmd.Parameters.AddWithValue(":CustomerLotNo", CustomerLotNo) + // End If + // cmd.Parameters.AddWithValue(":FactoryNo", FactoryNo) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + // add MO Component + // + + + // add MO Material List + // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +*MaterialMONo, +SubstituteMaterialNo + //if (dtMTL.Rows.Count > 0) + //{ + // if (!dtMTL.Columns.Contains("MaterialMONo")) + // dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String")); + + // foreach (DataRow dr in dtMTL.Rows) + // { + // if (dr["MaterialMONo"] is DBNull || string.IsNullOrEmpty(dr["MaterialMONo"].ToString())) + // dr["MaterialMONo"] = "N/A"; + + // bool blnAddMaterial = true; // 是否將工單用料加入tblOEMOMaterialList, True:是 False:否 + + // // 2019/09/25 Grace 增加檢查, 若有傳入DeliveryMethod且值=4, 這筆工單用料清單, 不加入至tblOEMOMaterialList;否或非4則不做任何處理 + // // 材料型態tagname:DeliveryMethod (Optional參數,非必傳) + // if (!(dr["DeliveryMethod"] is DBNull)) + // { + // if (dr["DeliveryMethod"].ToString() == "4") + // { + // blnAddMaterial = false; + // } + // } + + // if (blnAddMaterial) + // { + // // 2019/01/30 OwenLiu, Mantis: 0054631 工單拋轉時,避免oracle與SQLServer對於空字串('')處理不同 + // // Oracle會將欄位值存成Null, SQLServer會將欄位值成空字串,造成後續功能判斷上的問題 + // string strSQLAddMTLField, strSQLAddMTLValue; + // // 先設定Not Null欄位 + // strSQLAddMTLField = "INSERT INTO tblOEMOMaterialList(MONo,MaterialNo,MaterialLevel,StdQty,UnitNo"; + // strSQLAddMTLValue = " VALUES('" + dr["MONo"].ToString().ToUpper() + "'" + ",'" + dr["MaterialNo"].ToString().ToUpper() + "'," + + // dr["MaterialLevel"] + "," + dr["StdQty"] + ",'" + dr["UnitNo"].ToString().ToLower() + "'"; + + // strSQLAddMTLField += ",DecreaseRate,OPNo,Specified,PutinplaceType,MaterialMONo,MaterialType" + ",CountWay,CheckLotNo,SubstituteMaterialNo,mainItem,phantomItem,lockRequirement,operationSeqnum"; + // strSQLAddMTLValue = strSQLAddMTLValue + "," + + // dr["DecreaseRate"] + ",'" + dr["OPNo"].ToString().ToUpper() + "'," + dr["Specified"] + "," + dr["PutInPlaceType"] + ",'" + dr["MaterialMONo"] + + // "'" + ",'" + dr["MaterialType"].ToString().ToUpper() + "'," + dr["CountWay"] + "," + dr["CheckLotNo"] + ",'" + dr["SubstituteMaterialNo"].ToString().ToUpper() + + // "','" + dr["mainItem"] + "','" + dr["phantomItem"] + "','" + dr["lockRequirement"] + "','" + dr["operationSeqnum"] + "'"; + + // // RequireQty + // if (!dr.IsNull("RequireQty") && !string.IsNullOrEmpty(dr["RequireQty"].ToString())) + // { + // strSQLAddMTLField += ",RequireQty"; + // strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["RequireQty"].ToString(); + // } + // // SubstituteStdQty + // if (!dr.IsNull("SubstituteStdQty") && !string.IsNullOrEmpty(dr["SubstituteStdQty"].ToString())) + // { + // strSQLAddMTLField += ",SubstituteStdQty"; + // strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["SubstituteStdQty"].ToString(); + // } + // // MaterialVersion + // if (!dr.IsNull("MaterialVersion") && !string.IsNullOrEmpty(dr["MaterialVersion"].ToString())) + // { + // strSQLAddMTLField += ",MaterialVersion"; + // strSQLAddMTLValue = strSQLAddMTLValue + ",'" + dr["MaterialVersion"] + "'".ToString(); + // } + // // SubstituteMaterialLevel + // if (!dr.IsNull("SubstituteMaterialLevel") && !string.IsNullOrEmpty(dr["SubstituteMaterialLevel"].ToString())) + // { + // strSQLAddMTLField += ",SubstituteMaterialLevel"; + // strSQLAddMTLValue = strSQLAddMTLValue + "," + dr["SubstituteMaterialLevel"].ToString(); + // } + + // strSQL = strSQLAddMTLField + ")" + strSQLAddMTLValue + ")"; + + // CollectionSQL.Add(strSQL); + // } + + // // cmd.CommandText = _ + // // "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," & _ + // // "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty) " & _ + // // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + // // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper) + // // cmd.Parameters.AddWithValue(":MaterialNo", dr("MaterialNo").ToString.ToUpper) + // // cmd.Parameters.AddWithValue(":MaterialLevel", dr("MaterialLevel")) + // // cmd.Parameters.AddWithValue(":StdQty", dr("StdQty")) + // // cmd.Parameters.AddWithValue(":UnitNo", dr("UnitNo").ToString.ToLower) + // // cmd.Parameters.AddWithValue(":OPNo", dr("OPNo").ToString.ToUpper) + // // cmd.Parameters.AddWithValue(":PutInPlaceType", dr("PutInPlaceType")) + // // cmd.Parameters.AddWithValue(":DecreaseRate", dr("DecreaseRate")) + // // cmd.Parameters.AddWithValue(":Specified", dr("Specified")) + // // cmd.Parameters.AddWithValue(":MaterialType", dr("MaterialType").ToString.ToUpper) + // // cmd.Parameters.AddWithValue(":CountWay", dr("CountWay")) + // // cmd.Parameters.AddWithValue(":CheckLotNo", dr("CheckLotNo")) + // // cmd.Parameters.AddWithValue(":MaterialVersion", dr("MaterialVersion")) + // // cmd.Parameters.AddWithValue(":MaterialMONo", dr("MaterialMONo")) + // // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr("SubstituteMaterialNo").ToString.ToUpper) + // // cmd.Parameters.AddWithValue(":SubstituteMaterialLevel", dr("SubstituteMaterialLevel")) '2012/12/26,Even,新增替代物料階 &數量 + // // cmd.Parameters.AddWithValue(":SubstituteStdQty", dr("SubstituteStdQty")) '2012/12/28,Even,新增替代物標準數 + // // cmd.Parameters.AddWithValue(":RequireQty", dr("RequireQty")) + // // cmd.ExecuteNonQuery() + // // cmd.Parameters.Clear() + // } + //} + + + // add MO Process + // 依產品、產品版本、工單類別找出工單流程 + // 參考kcOE.ShowProductProcess、kcOE.UpdMOProcessbyProduct、MEStc_WellDown.addMO + // 2012/07/26, Aaron, 修正取流程時無法取得多區段的流程 + + // 2018/11/19 OwenLiu, 透過共用Function 統一處理 MOProcess資料 + ExamineMOProcess(MONo, ProductNo, ProductVersion, MOTypeNo, ref CollectionSQL, ref aryException, CustomerLotNo); + + if (aryException.Count > 0) + goto exitfun; + + // add MO Property + if (dtMOProperty.Rows.Count > 0) + { + foreach (DataRow dr in dtMOProperty.Rows) + { + strSQL = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')"; + CollectionSQL.Add(strSQL); + // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":PropertyNo", dr("PropertyNo")) + // cmd.Parameters.AddWithValue(":PropertyValue", dr("PropertyValue")) + // cmd.CommandText = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values(?,?,?)" + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + strSQL = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')"; + CollectionSQL.Add(strSQL); + // cmd.Parameters.AddWithValue(":MONo", dr("MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":PropertyNo", dr("PropertyNo")) + // cmd.Parameters.AddWithValue(":PropertyValue", dr("PropertyValue")) + // cmd.CommandText = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values(?,?,?)" + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + } + } + + + // add MO SEMI Out + // + + + // trans.Commit() + //string argstrDataBaseType = "Null"; + ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL); + r = true; + clsERP.combineMessage(ref aryMessage, mmsg: "[%AddMOSuccess%]"); + } + + catch (Exception ex) + { + // trans.Rollback() + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + + } + // End Using + // End Using + // End Using + + exitfun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + CloseConnection(cnnTemp1); + addMORet = r; + } + + return addMORet; + + } + public static string AddMOMaterialList(string MONo, string MaterialNo, int MaterialLevel, double StdQty, double DecreaseRate, string OPNo, int Specified, int PutInPlaceType, string UnitNo, int MOFlag, string MaterialMONo, string Description = defString, Collection colReturnSQL = null, string AdditionalXml = "", string MaterialVersion = defString, string SubstituteMaterialNo = defString, int SubstituteMaterialLevel = defInteger, decimal RequireQty = defInteger, decimal SubstituteStdQty = defInteger, string Creator = defString, DateTime CreateDate = default(DateTime),string AB=defString,string PositionCode=defString) + { + string AddMOMaterialListRet = default(string); + // 此 Function 將新增一筆資料 + // 傳入值: 各欄位新增值 + // 傳回值: success(成功), fail(失敗) + + DbDataReader drTemp = null; + string MaterialType = "N/A"; + int CountWay = -1; + int CheckLotNo = -1; + IDbConnection cnnTemp = null; + + string strSQL = ""; + string strSQLAddField = ""; + string strSQLAddValue = ""; + + + AppSettings objSetting = new AppSettings(); + + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + + try + { + cnnTemp = CreateConnection(strConnectionString); // //Create connection + + if (MaterialLevel == 0) // Material + { + strSQL = "Select MaterialType,CountWay,CheckLotNo From tblMTLMaterialBasis" + " Where MaterialNo ='" + MaterialNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + MaterialType = Conversions.ToString(drTemp["MaterialType"]); + CountWay = Conversions.ToInteger(drTemp["CountWay"]); + CheckLotNo = Conversions.ToInteger(drTemp["CheckLotNo"]); + } + else + { + throw new iMESException.MESException("0000-200003", "MaterialNo:" + MaterialNo + " is not exist!"); + } + drTemp.Close(); + } + // cmmTemp.Dispose() + + else if (MaterialLevel == 1) // Product + { + strSQL = "Select ProductType From tblPRDProductBasis Where ProductNo ='" + MaterialNo + "'"; + // cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp) + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + MaterialType = Conversions.ToString(drTemp["ProductType"]); + } + else + { + throw new iMESException.MESException("0000-200003", "ProductNo:" + MaterialNo + " is not exist!"); + } + drTemp.Close(); + + CheckLotNo = 1; // 一律要Check Lot + } + + // Combine SQL + strSQLAddField = "Insert into tblOEMOMaterialList (MONo, MaterialNo, OrgMaterialNo, MaterialLevel, StdQty, UnitNo," + "DecreaseRate, OPNo, Specified, PutInPlaceType, MOFlag, MaterialType, CountWay, CheckLotNo "; + strSQLAddValue = " Values ('" + MONo + "', '" + MaterialNo + "','" + MaterialNo + "'," + MaterialLevel + "," + StdQty + ",'" + UnitNo + "'," + DecreaseRate + ",'" + OPNo + "'," + Specified + "," + PutInPlaceType + "," + MOFlag + ",'" + MaterialType + "'," + CountWay + "," + CheckLotNo; + + + if (MOFlag == 0) // Create MO,紀錄半成品的工單編號 + { + strSQLAddField = strSQLAddField + ",MaterialMONo"; + strSQLAddValue = strSQLAddValue + ",'" + MaterialMONo + "'"; + } + else + { + strSQLAddField = strSQLAddField + ",MaterialMONo"; + strSQLAddValue = strSQLAddValue + ",'N/A'"; + } + if (Description != defString) + { + strSQLAddField = strSQLAddField + ",Description"; + strSQLAddValue = strSQLAddValue + ",'" + Description + "'"; + } + if (MaterialVersion != defString) + { + strSQLAddField = strSQLAddField + ",MaterialVersion"; + strSQLAddValue = strSQLAddValue + ",'" + MaterialVersion + "'"; + } + if (SubstituteMaterialNo != defString) + { + strSQLAddField = strSQLAddField + ",SubstituteMaterialNo"; + strSQLAddValue = strSQLAddValue + ",'" + SubstituteMaterialNo + "'"; + } + + // 2012/12/27,Even,新增替代料等級及需求數量 + if (SubstituteMaterialLevel != defInteger) + { + strSQLAddField = strSQLAddField + ",SubstituteMaterialLevel"; + strSQLAddValue = strSQLAddValue + ",'" + SubstituteMaterialLevel + "'"; + } + if (SubstituteStdQty != defInteger) + { + strSQLAddField = strSQLAddField + ",SubstituteStdQty"; + strSQLAddValue = strSQLAddValue + ",'" + SubstituteStdQty + "'"; + } + if (RequireQty != defInteger) + { + strSQLAddField = strSQLAddField + ",RequireQty"; + strSQLAddValue = strSQLAddValue + ",'" + RequireQty + "'"; + } + if (Creator != defString) + { + strSQLAddField = strSQLAddField + ",Creator"; + strSQLAddValue = strSQLAddValue + ",'" + Creator + "'"; + } + if (CreateDate != defDateTime) + { + strSQLAddField = strSQLAddField + ",CreateDate"; + strSQLAddValue = strSQLAddValue + ",To_Date('" + Strings.Format(CreateDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')"; + } + + if (string.IsNullOrEmpty(AdditionalXml)) + { + // 當沒有額外的欄位時,直接給定strSQL + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + } + else + { + // 加上additional的field & value 後傳回 + strSQL = SeparateAddXML_Add(ref strSQLAddField, ref strSQLAddValue, AdditionalXml); + } + + // 呼叫執行SQL指令 + if (colReturnSQL == null) + { + ExecuteSQLNoneQuery(Conversions.ToString(strDataBaseType), strConnectionString, ref strSQL); + } + else + { + // 不執行指令,將指令傳出 + colReturnSQL.Add(strSQL); + } + + // Return success + AddMOMaterialListRet = "success"; + } + + catch (Exception e1) + { + AddMOMaterialListRet = "fail"; + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + } // New Exception("kcOE.AddMOMaterialList: " & e1.Message) + + finally + { + CloseConnection(cnnTemp); + + } + + return AddMOMaterialListRet; + + } + + /// + /// 編輯工單(工單變更) + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool editMO(string MONo, decimal MOQty, string RONo = null, string ItemNo = null, string CustomerNo = null, int MOTypeNo = defInteger, int Priority = defInteger, DateTime PlanFinishDate = default(DateTime), string Creator = null, DateTime CreateDate = default(DateTime), string Description = null, DataTable dtMTL = null, List aryMessage = null, List aryException = null, List aryAlert = null, DataTable dtMOProperty = null, string ERPMOLineNo = defString, bool PropertyFlag = false, string CustomerLotNo = null, DateTime PlanStartDate = default(DateTime), int wipEntityId = defInteger, string bomVersion = null, string lcPlantype = null, string faiFlag = null) // haoqian 221025 + { + bool editMORet = default(bool); + + bool r = false; + var CollectionSQL = new Collection(); + string strSQL = ""; + + try + { + + // ----- Default Value ----- + int MOSource = 0; // 0: RO, 1: RMA, 2: None + int MOState = 0; // 0: Unconfirm, 1: Pending, 2: Confirm, 3: Release(允許開立生產批), 6: 已在客託倉或退貨倉的工單(允許開立生產批), 99:Close + int IssueState = 0; + string BelongToMONo = "N/A"; + string ENGNo = "N/A"; + string ENGVersion = "N/A"; + //string CustomerLotNo = string.Empty; + string FactoryNo = "N/A"; + decimal AdjustQty = 0m; + string OPNo = "LOTCREATE"; + + // ---- Get Value ----- + string CustomerName = string.Empty; + string ProductVersion = string.Empty; + string ProcessNo = string.Empty; + string ProcessVersion = string.Empty; + + bool isROExist = false; + bool isRODetailExist = false; + + string ItemProperty = defString; // 2016-10-17, Joe, 新增料件屬性,P:採購件,M:自製件,S:外包件 + int OutSourcingFlag = defInteger; // 2016-10-17, Joe, 0:off,1:on + string ProductNo = defString; + + var ReleaseQty = default(decimal); + + // ----- 1. 檢查MO是否存在 ----- + MONo = MONo.ToUpper(); + + using (var objOE = new clsOEBasis()) + { + + var drOE = objOE.GetMOBasis(MONo.ToUpper()); + if (drOE["MONo"] is DBNull == true) + clsERP.combineException(ref aryException, mesmsg: "[%MONoNotExist%]"); + // If drOE.Item("IssueState") < 0 Or drOE.Item("IssueState") > 2) clsERP.combineException(aryException, , , "[%MONoIssueStateCanNotEdit%]") + + + if (!(drOE["MOState"] is DBNull)) + { + if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(drOE["MOState"], 99, false))) + clsERP.combineException(ref aryException, mesmsg: "[%MONoClosed%]"); + } + + // 2020/08/11 Grace Mantis 76332 依據規格書說明調整:若訂單號碼有傳入,此項目應一併傳入,若未傳入則預設為1 + if (string.IsNullOrEmpty(ItemNo) == true) + ItemNo = "1"; + + // ----- 2. 檢查訂單資料 ----- + if (string.IsNullOrEmpty(RONo) == false) + { + if (RONo.ToUpper() != drOE["RONo"].ToString()) + clsERP.combineException(ref aryException, mesmsg: "[%RONoCanNotChange%]"); + if (ItemNo != drOE["ItemNo"].ToString()) + clsERP.combineException(ref aryException, mesmsg: "[%ROItemNoCanNotChange%]"); + } + + // ----- 3. 檢查MO剩餘數量 ----- + // If MOQty < drOE.Item("UnReleaseLotQty")) clsERP.combineException(aryException, , , "[%MOQtyLassThenUnReleaseLotQty%]") + + // 要修改的MOQty不可小於已下線數量:MOQtyLessThenReleaseLotQty, 2009/05/05,by yumei + if (!(drOE["MOQty"] is DBNull)) + { + ReleaseQty = Convert.ToDecimal(Operators.SubtractObject(drOE["MOQty"], drOE["UnReleaseLotQty"])); + if (MOQty < ReleaseQty) + clsERP.combineException(ref aryException, mesmsg: "[%MOQtyLessThenReleaseLotQty%]"); + } + + if (!(drOE["IssueState"] is DBNull)) + { + //檢查工單數量的變更是否合理 + if (Conversions.ToInteger(drOE["IssueState"]) == 2) + { + var dsOEMOC = objOE.ShowMOComponent(MONo.ToUpper()); + if (dsOEMOC.Tables[0].Rows.Count > 0) + { + //tblOEMOComponent.InventoryNo多筆相同 + if (!(dsOEMOC.Tables[0].Rows[0]["InventoryNo"] is DBNull)) + { + clsERP.combineException(ref aryException, mesmsg: "[%EditMOQtyIsNotAllowed_InventoryNo%]"); + } + else + { + if (!(drOE["MOQty"] is DBNull)) + { + if (MOQty < Convert.ToDecimal(drOE["MOQty"])) + { + if (dsOEMOC.Tables[0].Rows.Count > MOQty) + { + clsERP.combineException(ref aryException, mesmsg: "[%EditMOQtyIsNotAllowed_WaferSouceType%]"); + } + } + } + } + } + } + } + + ProductNo = drOE["ProductNo"].ToString(); + + } + + if (aryException.Count > 0) + goto exitfun; + + // ----- 3. 檢查MOSource----- + if (string.IsNullOrEmpty(RONo)) + MOSource = 2; // MO來源為其他(暫不考慮RMA) + + // ----- 4. 檢查CustomerNo是否存在 ----- + if (MOSource == 0) + { + if (string.IsNullOrEmpty(CustomerNo)) + { + // 未傳入 + clsERP.combineException(ref aryException, mesmsg: "[%ROWithoutCustomerNo%]"); + } + else + { + // 有傳入=>檢查Customer主檔 + using (var objENT = new clsCustomerBasis()) + { + var dr = objENT.GetCustomerBasis(CustomerNo.ToUpper()); + if (dr["CustomerNo"] is DBNull == true) + { + // Customer主檔未建立 + // clsERP.combineException(aryException, , , "[%CustomerNoNotExist%]") + + // 5.3 若拋入訂單號碼,則必須拋入客戶編號,系統應檢查tblENTCustomerBasis之中是否存在此客戶,若無則自動新增 + objENT.AddCustomerBasis(CustomerNo.ToUpper(), CustomerNo, CustomerNo, "NULL", "NULL", "NULL", "NULL", "NULL", "NULL"); + objENT.SetCustomerBasisIssueState(CustomerNo.ToUpper(), 2); + } + else + { + CustomerName = dr["CustomerName"].ToString(); + } + } + } + } + + // ----- 5. 檢查Product ----- + // Using objPRD As New kcPRD.clsProduct + // Dim dr As DataRow = objPRD.GetProduct(ProductNo.ToUpper) + // If IsDBNull(dr("ProductNo")) = True) clsERP.combineException(aryException, , , "[%ProductNoNotExist%]") + // If IsDBNull(dr("ProductNo")) = False AndAlso dr("IssueState") <> 2) clsERP.combineException(aryException, , , "[%ProductNotApproved%]") + + // '----- 6. 檢查MOUnitNo ----- + // If IsDBNull(dr("ProductNo")) = False AndAlso dr("UnitNo").ToString.ToLower <> MOUnitNo.ToLower) clsERP.combineException(aryException, , , "[%ProductandMOwithdifferentUnitNo%]") + // dr.Delete() + + // Try + // ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper) + // Catch ex As Exception + // clsERP.combineException(aryException, , , "[%GetProductVersionFail%]") + // End Try + // End Using + + using (var objPRD = new clsProduct()) + { + try + { + ProductVersion = objPRD.GetProductCurVersion(ProductNo.ToUpper()); + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, mesmsg: "[%GetProductVersionFail%]"); + } + // 2016-10-17, Joe, 取得ItemProperty + var drItemProperty = objPRD.GetProductProperty(ProductNo, ProductVersion, "ItemProperty"); + if (drItemProperty == null == false && drItemProperty["DefaultValue"] is DBNull == false) + { + ItemProperty = drItemProperty["DefaultValue"].ToString(); + } + } + // 2016-10-17, Joe, 取得外包控制 + using (var objSYS = new clsSYSParameter()) + { + OutSourcingFlag = Conversions.ToInteger(objSYS.GetParameterValue("OutSourcingFlag")); + } + // 2016-10-17, Joe, 若該產品品號屬性屬於S且外包控管參數為Off時,MES不做工單新增/修改,直接回應OK,但訊息應回傳『MES系統不支持外包工單』 + if (ItemProperty == "S" & OutSourcingFlag == 0) + { + clsERP.combineMessage(ref aryMessage, mmsg: "[%ProductNo%]:" + ProductNo + ",[%ProductVersion%]:" + ProductVersion + ",[%Is%] [%OutSourcing%] [%Product%], MES [%IsNotSupported%] !"); + if (aryMessage.Count > 0) + goto exitfun; + } + + // ----- 7. 檢查用料清單資料 ----- + if (dtMTL.Rows.Count > 0) + { + bool blnWF = false; + //2023/12/07,Ning,151196: [6.0.7] SDD231107_01-01_WF 工單整合接口調整 + //取得目前ERP是否為WF + using (var objSYSPar = new kcSYS.clsSYSParameter()) + { + var dsTemp = new DataSet(); + dsTemp = objSYSPar.ShowERPSetting(ActiveERP: 1); + if (dsTemp != null && dsTemp.Tables[0].Rows.Count > 0) + { + if (dsTemp.Tables[0].Rows[0]["ERP_Name"].ToString().ToUpper() == "WORKFLOW") + { + blnWF = true; + } + } + } + + if (!dtMTL.Columns.Contains("MaterialMONo")) + dtMTL.Columns.Add("MaterialMONo", Type.GetType("System.String")); + + // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo + + foreach (DataRow dr in dtMTL.Rows) + { + string strMaterialUnit = dr["UnitNo"].ToString(); + decimal decTemp = 0m; + try + { + if (string.IsNullOrEmpty(dr["MainItem"].ToString())) + { + // 未傳入 + clsERP.combineException(ref aryException, mesmsg: "[%MainItem%]"); + } + + //if (string.IsNullOrEmpty(dr["PhantomItem"].ToString())) + //{ + // // 未傳入 + // clsERP.combineException(ref aryException, mesmsg: "[%PhantomItem%]"); + //} + + if (string.IsNullOrEmpty(dr["LockRequirement"].ToString())) + { + // 未傳入 + clsERP.combineException(ref aryException, mesmsg: "[%LockRequirement%]"); + } + + if (string.IsNullOrEmpty(dr["OperationSeqnum"].ToString())) + { + // 未傳入 + clsERP.combineException(ref aryException, mesmsg: "[%OperationSeqnum%]"); + } + + if (blnWF == true) + { + if (Conversions.ToInteger(dr["StdQty"]) != Convert.ToDecimal(dr["StdQty"])) //若標準用量有小數, 需以ERP所傳入的該物料的需領用量(RequireQty)/預計產量(MOQty),並以無條件捨去取到小數六位數的值,做為該物料的標準用量 + { + decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000; + decTemp = Math.Floor(decTemp); + decTemp = decTemp / 1000000; + dr["StdQty"] = decTemp; + } + if (Conversions.ToInteger(dr["SubstituteStdQty"]) != Convert.ToDecimal(dr["SubstituteStdQty"])) //若替代料標準用量有小數同標準用量處理 + { + decTemp = (Convert.ToDecimal(dr["RequireQty"]) / MOQty) * 1000000; + decTemp = Math.Floor(decTemp); + decTemp = decTemp / 1000000; + dr["SubstituteStdQty"] = decTemp; + } + } + if (dr["MaterialLevel"].ToString() == "0") + { + // 用料清單為物料 + using (var objMTL = new clsMTLBasis()) + { + DataRow drMTL = null; + bool errorFlag = false; + dr["MONo"] = dr["MONo"].ToString().ToUpper(); + + drMTL = objMTL.GetMaterialBasis(dr["MaterialNo"].ToString().ToUpper()); + // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion + + // MaterialNo + if (drMTL["MaterialNo"] is DBNull == true) // 2013/02/19,Even,以物料編號在物料主檔中查詢,查不到表示該項為半成品,因為TIPTOP系統中,物料和產品在同一個table內,使用者可能挑選到產品卻以為是物料 + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" + + dr["MaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsMaterial%]."); + goto SkipMaterialList; + } + else + { + dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper(); + } + + // UnitNo + if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + { + // 當用料清單和物料主檔的單位不同時 + // 單位轉換 + using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + { + var colParameters = new Collection(); + colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + colParameters.Add("*", "ProductVersion"); + + try + { + dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters)); + dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters)); + dr["UnitNo"] = drMTL["UnitNo"].ToString().ToLower(); + } + catch (Exception ex) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + } + } + } + else + { + dr["UnitNo"] = dr["UnitNo"].ToString().ToLower(); + } + + // MaterialMONo (Default) + dr["MaterialMONo"] = "N/A"; + + // MaterialType + if (dr["MaterialType"] is DBNull == true) + { + dr["MaterialType"] = drMTL["MaterialType"]; + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drMTL["MaterialType"], false))) + { + dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper(); + } + else + { + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + } + + // CheckLotNo + if (dr["CheckLotNo"] is DBNull == true) + { + dr["CheckLotNo"] = drMTL["CheckLotNo"]; + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectNotEqual(dr["CheckLotNo"], drMTL["CheckLotNo"], false))) + { + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListCheckLotNoDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + } + + // 2013/02/20,Even,修改替代料檢查 + if (dr["SubstituteMaterialNo"] is DBNull == true) + { + dr["SubstituteMaterialNo"] = dr["MaterialNo"]; + dr["SubstituteMaterialLevel"] = dr["MaterialLevel"]; + } + // 2013/02/25,Even,判斷替代料,替代料可為半成品或是物料 + else if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料 + { + // 查詢替代料是否在物料主檔內,若無,則出現錯誤訊息 + drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper()); + if (drMTL["MaterialNo"] is DBNull == true) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%]."); + goto SkipMaterialList; + } + else + { + dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + } + } + else // 為半成品 (SubstituteMaterialLevel = 1) + { + DataRow drPRD = null; + // 檢查物料是否存在於產品主檔 + using (var objPRD = new clsProduct()) + { + drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper()); + } + if (drPRD["ProductNo"] is DBNull == true) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%]."); + goto SkipMaterialList; + } + else + { + dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + } + } + + if (dr["SubstituteStdQty"] is DBNull == true) + { + dr["SubstituteStdQty"] = dr["StdQty"]; + } + // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換 + decimal decRequireQty = 0m; + if (dr["RequireQty"] is DBNull == true) + { + // ERP未傳入需求數(RequireQty) + // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"])); + } + else + { + decRequireQty = Convert.ToDecimal(dr["RequireQty"]); + // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + if (drMTL["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + { + // 當用料清單和物料主檔的單位不同時 + using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + { + var colParameters = new Collection(); + colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + colParameters.Add("*", "ProductVersion"); + try + { + dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drMTL["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters)); + } + catch (Exception ex) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + } + } + } + else + { + dr["RequireQty"] = decRequireQty; + } + } + + // 檢查OPNo(用料作業站)是否存在 ----- + if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE") + { + // 有傳入=>檢查OP主檔 + using (var objOP = new clsOpBasis()) + { + var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper()); + if (drOP["OPNo"] is DBNull == true) + { + // OP主檔未建立 + clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]"); + } + } + } + } + } + else + { + // 用料清單為半成品 + using (var objPRD = new clsProduct()) + { + DataRow drPRD = null; + bool errorFlag = false; + dr["MONo"] = dr["MONo"].ToString().ToUpper(); + + drPRD = objPRD.GetProduct(dr["MaterialNo"].ToString().ToUpper()); + // (skip) MONo, MaterialLevel, STDQty, DecreaseRate, OPNo, Specified, PutinPlaceType, MOFlag, CountWay, Description, OrgMaterialNo, EX_MTLList1, EX_MTLList2, MaterialVersion + + // MaterialNo + if (drPRD["ProductNo"] is DBNull == true) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%MaterialNo%]:" + + dr["MaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%MaterialLevel%][%IsProduct%]."); + goto SkipMaterialList; + } + else + { + dr["MaterialNo"] = dr["MaterialNo"].ToString().ToUpper(); + } + + // UnitNo + if (drPRD["UnitNo"].ToString().ToLower() != dr["UnitNo"].ToString().ToLower()) + { + // 當用料清單和物料主檔的單位不同時 + // 單位轉換 + using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + { + var colParameters = new Collection(); + colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + colParameters.Add("*", "ProductVersion"); + + try + { + dr["StdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["StdQty"]), colParameters)); + + dr["SubstituteStdQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), Convert.ToDouble(dr["SubstituteStdQty"]), colParameters)); + + dr["UnitNo"] = drPRD["UnitNo"].ToString().ToLower(); + } + catch (Exception ex) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + } + } + } + else + { + dr["UnitNo"] = dr["UnitNo"].ToString().ToLower(); + } + + // MaterialMONo (Default) + dr["MaterialMONo"] = "N/A"; + + // MaterialType + if (dr["MaterialType"] is DBNull == true) + { + dr["MaterialType"] = drPRD["ProductType"]; + } + else if (Convert.ToBoolean(Operators.ConditionalCompareObjectEqual(dr["MaterialType"].ToString().ToUpper(), drPRD["ProductType"], false))) + { + dr["MaterialType"] = dr["MaterialType"].ToString().ToUpper(); + } + else + { + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListMaterialTypeDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + } + + // CheckLotNo + dr["CheckLotNo"] = 1; // 半成品固定為1 + + // SubstituteMaterialNo + // ---2013/02/20,Even,替代料是否存在的檢查---- + if (dr["SubstituteMaterialNo"] is DBNull == true) + { + dr["SubstituteMaterialNo"] = dr["MaterialNo"]; + dr["SubstituteMaterialLevel"] = dr["MaterialLevel"]; + } + else + { + DataRow drMTL = null; + // 2013/02/25,Even,判斷替代料,替代料可為半成品或是物料 + if (dr["SubstituteMaterialLevel"].ToString() == "0") // 為物料 + { + // 查詢替代料是否在物料主檔內,若無,則出現錯誤訊息 + using (var objMTL = new clsMTLBasis()) + { + drMTL = objMTL.GetMaterialBasis(dr["SubstituteMaterialNo"].ToString().ToUpper()); + } + + if (drMTL["MaterialNo"] is DBNull == true) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + dr["SubstituteMaterialNo"] + " [%MaterialNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsMaterial%]."); + goto SkipMaterialList; + } + else + { + dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + } + } + else // 為半成品 (SubstituteMaterialLevel = 1) + { + // 檢查物料是否存在於產品主檔 + drPRD = objPRD.GetProduct(dr["SubstituteMaterialNo"].ToString().ToUpper()); + if (drPRD["ProductNo"] is DBNull == true) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: " [%SubstituteMaterialNo%]:" + + dr["SubstituteMaterialNo"] + " [%ProductNoNotExist%][%InMESSystem%]! [%SubstituteMaterialLevel%][%IsProduct%]."); + goto SkipMaterialList; + } + else + { + dr["SubstituteMaterialNo"] = dr["SubstituteMaterialNo"].ToString().ToUpper(); + } + } + } + + if (dr["SubstituteStdQty"] is DBNull == true) + { + dr["SubstituteStdQty"] = dr["StdQty"]; + } + + // 2019/12/16 OwenLiu, Mantis:0065576 , 工單整合(新增)時用料需求數支援單位轉換 + decimal decRequireQty = 0m; + if (dr["RequireQty"] is DBNull == true) + { + // ERP未傳入需求數(RequireQty) + // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + dr["RequireQty"] = Operators.MultiplyObject(Operators.MultiplyObject(MOQty, dr["StdQty"]), Operators.AddObject(1, dr["DecreaseRate"])); + } + else + { + decRequireQty = Convert.ToDecimal(dr["RequireQty"]); + // 2019/12/23 OwenLiu, Mantis:0065953 修正工單整合 用料清單單位轉換的問題 + if (drPRD["UnitNo"].ToString().ToLower() != strMaterialUnit.ToLower()) + { + // 當用料清單和產品主檔的單位不同時 + using (var objUnit = new udUnitTransferFunction.clsUnitTransferFunction()) + { + var colParameters = new Collection(); + colParameters.Add(dr["MaterialNo"].ToString().ToUpper(), "ProductNo"); + colParameters.Add("*", "ProductVersion"); + try + { + dr["RequireQty"] = Convert.ToDouble(objUnit.EXETransferQty(strMaterialUnit.ToLower(), drPRD["UnitNo"].ToString().ToLower(), (double)decRequireQty, colParameters)); + } + catch (Exception ex) + { + errorFlag = true; + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitNoDifferent%]" + " [%MaterialNo%]:" + + dr["MaterialNo"]); + clsERP.combineException(ref aryException, mesmsg: "[%MaterialListUnitTransferFail%]" + " " + ex.Message); + } + } + } + else + { + dr["RequireQty"] = decRequireQty; + } + } + + // 檢查OPNo(用料作業站)是否存在 ----- + if (dr["OPNo"].ToString().ToUpper() != "LOTCREATE") + { + // 有傳入=>檢查OP主檔 + using (var objOP = new clsOpBasis()) + { + var drOP = objOP.GetOPBasis(dr["OPNo"].ToString().ToUpper()); + if (drOP["OPNo"] is DBNull == true) + { + // OP主檔未建立 + clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]"); + } + } + } + } + } + + SkipMaterialList: + ; + } + + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + } + + } + + // ----- 8. 取得FactoryNo ----- + // FactoryNo = "N/A" + + // ----- 檢查MO Property --- + if (!(dtMOProperty == null) && dtMOProperty.Rows.Count > 0) + { + foreach (DataRow dr in dtMOProperty.Rows) + { + List argaryMessage = null; + List argaryException = null; + doSYSMOProperty(Convert.ToString(dr["PropertyNo"]), Convert.ToString(dr["DataType"]), aryMessage: argaryMessage, aryException: argaryException); + } + } + + // ----- 9. 檢查OPNo(用料作業站)是否存在 ----- + if (dtMTL.Rows.Count > 0) + { + + // dtMTL.Columns.Add("MaterialMONo", System.Type.GetType("System.String")) + + // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo + + foreach (DataRow dr in dtMTL.Rows) + { + try + { + // OPyNo <> "LOTCREATE" + if (dr["OPNo"].ToString() != OPNo.ToString()) + { + // 有傳入=>檢查OP主檔 + using (var objOP = new clsOpBasis()) + { + var drOP = objOP.GetOPBasis(dr["OPNo"].ToString()); + if (drOP["OPNo"] is DBNull == true) + { + // OP主檔未建立 + clsERP.combineException(ref aryException, mesmsg: "[%OPNoNotExist%]"); + } + } + } + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doMaterialListFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + } + } + + + // ----- Exception => Fail ----- + if (aryException.Count > 0) + goto exitfun; + + // ----- Edit MO ----- + AppSettings objSetting = new AppSettings(); + // Using cn As New OleDbConnection(objSetting.GetConnectionString) + // Using cmd As New OleDbCommand("", cn) + // cn.Open() + // Using trans As OleDbTransaction = cn.BeginTransaction + // cmd.Transaction = trans + try + { + // ----- MO ----- + // edit MO Basis + strSQL = "update tbloemobasis set " + "moqty=" + MOQty + ", " + "unreleaselotqty=" + (MOQty - ReleaseQty) + ", " + "priority=" + Priority + ", " + "planfinishdate=To_Date('" + Strings.Format(PlanFinishDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS'), " + "description=N'" + Description + "' "; + + // 2018/3/19 Vick 新增欄位 ERPMOLineNo + if (ERPMOLineNo != defString) + { + strSQL += ",ERPMOLineNo ='" + ERPMOLineNo + "' "; + } + if (PlanStartDate != defDateTime) + { + strSQL += ",PlanStartDate = To_Date('" + Strings.Format(PlanStartDate, "yyyy/MM/dd H:mm:ss") + "','YYYY/MM/DD HH24:MI:SS') "; + } + strSQL += "where mono='" + MONo.ToUpper() + "'"; + + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "update tbloemobasis set " & _ + // "moqty=?, " & _ + // "unreleaselotqty=?, " & _ + // "priority=?, " & _ + // "planfinishdate=?, " & _ + // "description=? " & _ + // "where mono=?" + // cmd.Parameters.AddWithValue(":MOQty", MOQty) + // cmd.Parameters.AddWithValue(":UnReleaseLotQty", MOQty - ReleaseQty) 'UNRELEASELOTQTY + // cmd.Parameters.AddWithValue(":Priority", Priority) + // cmd.Parameters.AddWithValue(":PlanFinishDate", PlanFinishDate) + // cmd.Parameters.AddWithValue(":Description", Description) + // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + // add MO Component + + + // add MO Material List + // dtMTL: MONo, MaterialNo, MaterialLevel, StdQty, UnitNo, OPNo, PutInPlaceType, DecreaseRate, Specified, *MaterialType, CountWay, *CheckLotNo, *MaterialVersion, +MaterialMONo, +*SubstituteMaterialNo + if (dtMTL.Rows.Count > 0) + { + + using (var objOE = new clsOEBasis()) + { + + var dtTemp = objOE.ShowMOMaterialList(MONo.ToUpper()).Tables["MOMaterialList"]; + + strSQL = "delete from tbloemomateriallist where mono='" + MONo.ToUpper() + "'"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "delete from tbloemomateriallist where mono=?" + // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + foreach (DataRow dr in dtMTL.Rows) + { + + bool blnAddMaterial = true; // 是否將工單用料加入tblOEMOMaterialList, True:是 False:否 + + // 2019/09/25 Grace 增加檢查, 若有傳入DeliveryMethod且值=4, 這筆工單用料清單, 不加入至tblOEMOMaterialList;否或非4則不做任何處理 + // 材料型態tagname:DeliveryMethod (Optional參數,非必傳) + if (!(dr["DeliveryMethod"] is DBNull)) + { + if (dr["DeliveryMethod"].ToString() == "4") + { + blnAddMaterial = false; + } + } + + if (blnAddMaterial) + { + strSQL = "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," + + "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty,mainItem,phantomItem,lockRequirement,operationSeqnum) " + + "values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["MaterialNo"].ToString().ToUpper() + "'," + dr["MaterialLevel"] + "," + dr["StdQty"] + ",'" + dr["UnitNo"].ToString().ToLower() + + "','" + dr["OPNo"].ToString().ToUpper() + "'," + dr["PutInPlaceType"] + "," + dr["DecreaseRate"] + "," + dr["Specified"] + ",'" + dr["MaterialType"].ToString().ToUpper() + "'," + dr["CountWay"] + + "," + dr["CheckLotNo"] + ",'" + dr["MaterialVersion"] + "','" + dr["MaterialMONo"] + "','" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'," + dr["SubstituteMaterialLevel"] + "," + dr["SubstituteStdQty"] + "," + dr["RequireQty"] + ",'" + dr["mainItem"] + "','" + dr["phantomItem"] + "','" + dr["lockRequirement"] + "','" + dr["operationSeqnum"] + "')"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "insert into tbloemomateriallist(mono,materialno,materiallevel,stdqty,unitno,opno,putinplacetype," & _ + // "decreaserate,specified,materialtype,countway,checklotno,materialversion,materialmono,substitutematerialno,SubstituteMaterialLevel,SubstituteStdQty,RequireQty) " & _ + // "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" + // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":MaterialNo", dr["MaterialNo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":MaterialLevel", dr["MaterialLevel")) + // cmd.Parameters.AddWithValue(":StdQty", dr["StdQty")) + // cmd.Parameters.AddWithValue(":UnitNo", dr["UnitNo").ToString.ToLower) + // cmd.Parameters.AddWithValue(":OPNo", dr["OPNo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":PutInPlaceType", dr["PutInPlaceType")) + // cmd.Parameters.AddWithValue(":DecreaseRate", dr["DecreaseRate")) + // cmd.Parameters.AddWithValue(":Specified", dr["Specified")) + // cmd.Parameters.AddWithValue(":MaterialType", dr["MaterialType").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":CountWay", dr["CountWay")) + // cmd.Parameters.AddWithValue(":CheckLotNo", dr["CheckLotNo")) + // cmd.Parameters.AddWithValue(":MaterialVersion", dr["MaterialVersion")) + // cmd.Parameters.AddWithValue(":MaterialMONo", dr["MaterialMONo")) + // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr["SubstituteMaterialNo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":SubstituteMaterialLevel", dr["SubstituteMaterialLevel")) '2012/12/26,Even,新增替代物料階 &數量 + // cmd.Parameters.AddWithValue(":SubstituteStdQty", dr["SubstituteStdQty")) '2012/12/28,Even,新增替代物標準數 + // cmd.Parameters.AddWithValue(":RequireQty", dr["RequireQty")) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + } + // 將舊的OrgMaterialQty資料更新到tbloemomateriallist + DataRow[] drTemp = dtTemp.Select("MONo='" + dr["MONo"].ToString().ToUpper() + "'" + " And MaterialNo='" + dr["MaterialNo"].ToString().ToUpper() + "'" + " And OPNo='" + + dr["OPNo"] + "'" + " And SubstituteMaterialNo='" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'"); + + foreach (DataRow drOrgMaterialQty in drTemp) + { + strSQL = "update tbloemomateriallist set orgmaterialqty=" + drOrgMaterialQty["OrgMaterialQty"] + + " where mono='" + dr["MONo"].ToString().ToUpper() + "' and materialno='" + dr["MaterialNo"].ToString().ToUpper() + + "' and opno='" + dr["OPNo"].ToString().ToUpper() + "' and substitutematerialno='" + dr["SubstituteMaterialNo"].ToString().ToUpper() + "'"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = _ + // "update tbloemomateriallist set orgmaterialqty=?" & _ + // " where mono=? and materialno=? and opno=? and substitutematerialno=?" + // cmd.Parameters.AddWithValue(":OrgMaterialQty", drOrgMaterialQty("OrgMaterialQty")) + // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":MaterialNo", dr["MaterialNo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":OPNo", dr["OPNo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":SubstituteMaterialNo", dr["SubstituteMaterialNo").ToString.ToUpper) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + } + + } + } + } + + + // add MO Process + // 依目前規格書之「工單變更」: + // 「4.1 單頭只能修改數量(MOQty)與預定完工日(PlanFinishDate)兩個欄位」, + // 故工單流程暫不做修改 + + + // add MO Property + if (dtMOProperty.Rows.Count > 0) + { + if (PropertyFlag) // haoqian 221025 + { + strSQL = "delete from tbloemoproperty where mono='" + MONo.ToUpper() + "'"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = "delete from tbloemoproperty where mono=?" + // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + strSQL = "delete from tbloemoproperty_recive where mono='" + MONo.ToUpper() + "'"; + CollectionSQL.Add(strSQL); + // cmd.CommandText = "delete from tbloemoproperty_recive where mono=?" + // cmd.Parameters.AddWithValue(":MONo", MONo.ToUpper) + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + + foreach (DataRow dr in dtMOProperty.Rows) + { + strSQL = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')"; + CollectionSQL.Add(strSQL); + // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":PropertyNo", dr["PropertyNo")) + // cmd.Parameters.AddWithValue(":PropertyValue", dr["PropertyValue")) + // cmd.CommandText = "insert into tbloemoproperty(mono,propertyno,propertyvalue) values(?,?,?)" + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + strSQL = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values('" + dr["MONo"].ToString().ToUpper() + "','" + dr["PropertyNo"] + "','" + dr["PropertyValue"] + "')"; + CollectionSQL.Add(strSQL); + // cmd.Parameters.AddWithValue(":MONo", dr["MONo").ToString.ToUpper) + // cmd.Parameters.AddWithValue(":PropertyNo", dr["PropertyNo")) + // cmd.Parameters.AddWithValue(":PropertyValue", dr["PropertyValue")) + // cmd.CommandText = "insert into tbloemoproperty_recive(mono,propertyno,propertyvalue) values(?,?,?)" + // cmd.ExecuteNonQuery() + // cmd.Parameters.Clear() + } + } + else // haoqian 221025 + { + foreach (DataRow dr in dtMOProperty.Rows) + { + strSQL = "update tbloemoproperty set propertyvalue = '" + dr["PropertyValue"] + "' where mono = '" + dr["MONo"].ToString().ToUpper() + "' and propertyno = '" + dr["PropertyNo"] + "'"; + CollectionSQL.Add(strSQL); + + strSQL = "update tbloemoproperty_recive set propertyvalue = '" + dr["PropertyValue"] + "' where mono = '" + dr["MONo"].ToString().ToUpper() + "' and propertyno = '" + dr["PropertyNo"] + "'"; + CollectionSQL.Add(strSQL); + + } + + } + } + + // 78079 + // ----- MOComponent ----- + // edit MO Component + using (var objOE = new clsOEBasis()) + { + using (var objSYS = new clsSYSEng()) + { + // Dim drOE As DataRow = objOE.GetMOBasis(MONo.ToUpper) + var dsOEMOC = objOE.ShowMOComponent(MONo.ToUpper()); + if (dsOEMOC.Tables[0].Rows.Count > 0) + { + if (MOQty > dsOEMOC.Tables[0].Rows.Count) + { + var dsCreateComponentNo = new DataSet(); + dsCreateComponentNo = objSYS.InitComponentNo(true, (int)Math.Round(MOQty - dsOEMOC.Tables[0].Rows.Count), MONo.ToUpper(), FactoryNo, CustomerNo, ProductNo, ProductVersion); + if (!(dsCreateComponentNo.Tables == null) && dsCreateComponentNo.Tables[0].Rows.Count > 0) + { + for (int i = 1, loopTo = dsCreateComponentNo.Tables[0].Rows.Count; i <= loopTo; i++) // MOQty - dsOEMOC.Tables[0].Rows.Count + { + strSQL = "Insert into tblOEMOComponent (MoNo, ComponentNo, GoodQty, UnitNo, ReleaseState)" + + " Values ('" + MONo.ToUpper() + "', '" + dsCreateComponentNo.Tables[0].Rows[i - 1]["ComponentNo"].ToString() + "'," + + dsOEMOC.Tables[0].Rows[0]["GoodQty"] + ",'" + dsOEMOC.Tables[0].Rows[0]["UnitNo"] + "', 0)"; + CollectionSQL.Add(strSQL); + } + } + if (dsCreateComponentNo != null) + dsCreateComponentNo = null; + } + } + if (dsOEMOC != null) + dsOEMOC = null; + } + } + + // add MO SEMI Out + + // trans.Commit() + //string argstrDataBaseType = "Null"; + ExecuteSQLNoneQuery_UPD(objSetting.GetDataBaseType(), objSetting.GetConnectionString(), CollectionSQL); + r = true; + clsERP.combineMessage(ref aryMessage, mmsg: "[%EditMOSuccess%]"); + } + catch (Exception ex) + { + // trans.Rollback() + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + + } + // End Using + // End Using + // End Using + + exitfun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%EditMOFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + editMORet = r; + } + + return editMORet; + + } + + /// + /// 檢查SYS模組裡的工單屬性 + /// + /// + /// + /// + /// + /// + /// + /// + public static object doSYSMOProperty(string PropertyNo, string DataType, int IssueState = 2, List aryMessage = null, List aryException = null) + { + object doSYSMOPropertyRet = default(object); + bool r = false; + try + { + + // ----- 檢查MOProperty是否存在 ----- + using (var objSYS = new clsSYSEng()) + { + + var dr = objSYS.GetMOProperty(PropertyNo); + + // ----- MOProperty已存在 ----- + if (dr["PropertyNo"] is DBNull == false) + { + r = true; + goto exitfun; + } + + // ----- MOProperty不存在=>新增MOProperty ----- + // DataType: 0:Numeric, 1:String, 2:Percent, 3:DateTime, 4:Boolean + int intType = 1; + switch (DataType.ToUpper()) + { + case "NUMERIC": + { + intType = 0; + break; + } + case "STRING": + { + intType = 1; + break; + } + case "PERCENT": + { + intType = 2; + break; + } + case "DATETIME": + { + intType = 3; + break; + } + case "BOOLEAN": + { + intType = 4; + break; + } + + default: + { + intType = 1; // 預設為String + break; + } + } + + try + { + objSYS.AddMOProperty(PropertyNo, PropertyNo, intType, 0); + objSYS.SetMOPropertyIssueState(PropertyNo, IssueState); + clsERP.combineMessage(ref aryMessage, mmsg: "[%AddSYSMOPropertySuccess%]"); + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%AddSYSMOPropertyFail%]"); + goto exitfun; + } + + r = true; + + } + + exitfun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%doSYSMOPropertyFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + doSYSMOPropertyRet = r; + } + + return doSYSMOPropertyRet; + } + /// + /// 檢查工廠編號是否存在;不存在=>新增 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static object doFactoryNo(string FactoryNo, string Creator, DateTime CreateDate, int IssueState = 2, List strMessage = null, List strException = null) + { + object doFactoryNoRet = default(object); + bool r = false; + try + { + + // ----- 檢查工廠編號是否存在 ----- + using (var objSMD = new clsSMDBasis()) + { + + var dr = objSMD.GetFactoryBasis(FactoryNo.ToUpper()); + + // ----- 工廠編號已存在 ----- + if (dr["FactoryNo"] is DBNull == false) + goto exitfun; + + // ----- 工廠編號不存在=>新增工廠編號 ----- + try + { + objSMD.AddFactoryBasis(FactoryNo.ToUpper(), "(from ERP)", Creator: Creator, CreateDate: CreateDate); + objSMD.SetFactoryBasisIssueState(FactoryNo.ToUpper(), IssueState); + clsERP.combineMessage(ref strMessage, mmsg: "[%AddFactoryNoSuccess%]"); + } + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%AddFactoryNoFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + goto exitfun; + } + } + r = true; + exitfun: + ; + } + + + catch (Exception ex) + { + clsERP.combineException(ref strException, sysmsg: ex.Message, mesmsg: "[%doFactoryFail%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + doFactoryNoRet = r; + } + + return doFactoryNoRet; + } + private static bool ExamineMOProcess(string MONo, string ProductNo, string ProductVersion, int MOTypeNo, ref Collection colSQL, ref List aryException, string CustomerLotNo = null) + { + + bool blnExecResult = false; + AppSettings objSetting = new AppSettings(); + IDbConnection cnnTemp = null; + string strSQL = "", strSQLAddField = "", strSQLAddValue = ""; + var CollectionSQL = new Collection(); + string CustomerNo = "", DeviceNo = ""; + + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + DbDataReader drTemp; + + // 1.依據工單類型(MOTypeNo)找出預設的流程編號 + // 先查詢指定的工單類型,找不到再用MOType=*的資料(MOTypeNo =-1) + var dtPRDPSNoList = new DataTable(); + var dtPorductProcess = new DataTable(); + strSQL = "select CustomerNo,DeviceNo from tblPRDProductBasis where ProductNo = '" + ProductNo + "' And ProductVersion = '" + ProductVersion + "'"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + CustomerNo = drTemp["CustomerNo"].ToString(); + DeviceNo = drTemp["DeviceNo"].ToString(); + } + drTemp.Close(); + + strSQL = "SELECT PSNo FROM (" + " SELECT PSNo,Min(PSOrder) AS PSOrder FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " GROUP BY PSNo )A ORDER BY PSOrder"; + //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp)) + //{ + // daTemp.Fill(dtPRDPSNoList); + //} + ExecuteSQLQuery_Adapter(strSQL, dtPRDPSNoList, cnnTemp); + + foreach (DataRow drData in dtPRDPSNoList.Rows) + { + var dtSinglePSNoProcess = new DataTable(); + strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " AND MOTypeNo = " + MOTypeNo + " AND DefaultProcess = 1" + " AND PSNo = '" + + drData["PSNo"] + "' ORDER BY PSOrder"; + //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp)) + //{ + // daTemp.Fill(dtSinglePSNoProcess); + //} + ExecuteSQLQuery_Adapter(strSQL, dtSinglePSNoProcess, cnnTemp); + + if (dtSinglePSNoProcess.Rows.Count.Equals(0)) + { + strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " AND MOTypeNo = -1 AND DefaultProcess = 1" + " AND PSNo = '" + + drData["PSNo"] + "' ORDER BY PSOrder"; + //using (var daTemp = new OleDbDataAdapter(strSQL, cnnTemp)) + //{ + // daTemp.Fill(dtSinglePSNoProcess); + //} + ExecuteSQLQuery_Adapter(strSQL, dtSinglePSNoProcess, cnnTemp); + } + dtPorductProcess.Merge(dtSinglePSNoProcess); + } + + dtPRDPSNoList.Dispose(); + + + if (CustomerNo != "N/A" && DeviceNo != "N/A") + { + string strMOTypeNo = MOTypeNo.ToString(); + DataSet dsECN = new DataSet(); + var dtECN = new DataTable(); + var dtNewPorductProcess = new DataTable(); + DataRow drECN; + + dtECN.Columns.Add("MONo", Type.GetType("System.String")); + dtECN.Columns.Add("CustomerLotNo", Type.GetType("System.String")); + + drECN = dtECN.NewRow(); + drECN["MONo"] = MONo; + drECN["CustomerLotNo"] = CustomerLotNo; + dtECN.Rows.Add(drECN); + + dsECN = ShowECNProcessData(ProductNo, ProductVersion, strMOTypeNo, ref aryException, dtECN); + + if (aryException.Count <= 0) + { + short intProcessOrder = 1; + foreach (DataRow drProcess in dsECN.Tables["tblECNProcessData"].Rows) + { + string strProcessNo = drProcess["ProcessNo"].ToString(); + string strProcessVersion = drProcess["ProcessVersion"].ToString(); + + + strSQL = "SELECT * FROM tblPRDProductProcess" + " WHERE ProductNo = '" + ProductNo + "' AND ProductVersion = '" + ProductVersion + "'" + " And ProcessNo = '" + + strProcessNo + "'" + " AND ProcessVersion = '" + strProcessVersion + "' AND MOTypeNo = " + MOTypeNo + ""; + ExecuteSQLQuery_Adapter(strSQL, dtNewPorductProcess, cnnTemp); + } + foreach (DataRow drNewProcess in dtNewPorductProcess.Rows) + { + + // 以指定流程版本新增工單流程 + strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" + + drNewProcess["ProcessNo"].ToString() + "'" + " AND A.ProcessVersion = '" + drNewProcess["ProcessVersion"].ToString() + "'" + " AND B.NodeId = (" + " SELECT Min(B.ToNodeId)" + + " FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" + + drNewProcess["ProcessNo"].ToString() + "'" + " AND A.ProcessVersion = '" + drNewProcess["ProcessVersion"].ToString() + "'" + " And B.FromNodeNo = 'START' GROUP BY A.ProcessNo)"; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + // 應該只有一筆資料,每一個流程也只需要新增一筆資料 + // 2019/01/23 OwenLiu, 修正工單流程存入ProcessVersion 為 * 的問題 + strSQLAddField = "INSERT INTO tblOEMOProcess (MONo,PSNo,PSOrder,ProcessOrder,ProcessNo,ProcessVersion"; + strSQLAddValue = " VALUES ('" + MONo + "','" + + drNewProcess["PSNo"] + "'," + drNewProcess["PSOrder"] + "," + intProcessOrder.ToString() + ",'" + drNewProcess["ProcessNo"].ToString() + "'" + ",'" + drTemp["ProcessVersion"].ToString() + + "'"; + + strSQLAddField += ",OPNo,NodeId,HaveComponent,HaveLevel"; + strSQLAddValue = strSQLAddValue + ",'" + + drTemp["NodeNo"] + "','" + drTemp["NodeId"] + "'" + "," + drNewProcess["HaveComponent"] + "," + drNewProcess["HaveLevel"]; + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + CollectionSQL.Add(strSQL); + intProcessOrder = (short)(intProcessOrder + 1); + } + drTemp.Close(); + } + } + } + else + { + short intProcessOrder = 1; + foreach (DataRow drProcess in dtPorductProcess.Rows) + { + string strProcessNo = drProcess["ProcessNo"].ToString(); + string strProcessVersion = drProcess["ProcessVersion"].ToString(); + if (strProcessVersion == "*") + { + // 以目前最新流程新增工單流程 + strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" + + drProcess["ProcessNo"] + "' AND A.CurVersion = 1" + " AND B.NodeId = (" + " SELECT Min(B.ToNodeId)" + " FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + + " WHERE A.ProcessNo = '" + drProcess["ProcessNo"] + "' AND A.CurVersion = 1" + " AND B.FromNodeNo = 'START' GROUP BY A.ProcessNo)"; + } + else + { + // 以指定流程版本新增工單流程 + strSQL = "SELECT B.ProcessNo, B.ProcessVersion, B.NodeNo, B.NodeId" + " FROM tblPRSProcessBasis A join tblPRSNodeBasis B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" + + drProcess["ProcessNo"] + "'" + " AND A.ProcessVersion = '" + strProcessVersion + "'" + " AND B.NodeId = (" + " SELECT Min(B.ToNodeId)" + + " FROM tblPRSProcessBasis A join tblPRSNodeRelation B ON A.ProcessNo = B.ProcessNo AND A.ProcessVersion = B.ProcessVersion" + " WHERE A.ProcessNo = '" + + drProcess["ProcessNo"] + "'" + " AND A.ProcessVersion = '" + strProcessVersion + "'" + " And B.FromNodeNo = 'START' GROUP BY A.ProcessNo)"; + } + + //using (var cmdProcess = new OleDbCommand(strSQL, cnnTemp)) + //{ + //var drTemp = cmdProcess.ExecuteReader(); + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + // 應該只有一筆資料,每一個流程也只需要新增一筆資料 + // 2019/01/23 OwenLiu, 修正工單流程存入ProcessVersion 為 * 的問題 + strSQLAddField = "INSERT INTO tblOEMOProcess (MONo,PSNo,PSOrder,ProcessOrder,ProcessNo,ProcessVersion"; + strSQLAddValue = " VALUES ('" + MONo + "','" + + drProcess["PSNo"] + "'," + drProcess["PSOrder"] + "," + intProcessOrder.ToString() + ",'" + strProcessNo + "'" + ",'" + drTemp["ProcessVersion"].ToString() + + "'"; + + strSQLAddField += ",OPNo,NodeId,HaveComponent,HaveLevel"; + strSQLAddValue = strSQLAddValue + ",'" + + drTemp["NodeNo"] + "','" + drTemp["NodeId"] + "'" + "," + drProcess["HaveComponent"] + "," + drProcess["HaveLevel"]; + strSQL = strSQLAddField + ")" + strSQLAddValue + ")"; + CollectionSQL.Add(strSQL); + intProcessOrder = (short)(intProcessOrder + 1); + } + drTemp.Close(); + //} + } + } + + + + + // 將收集到的SQL語句加以回傳,由呼叫端統一執行 + if (colSQL != null) + { + for (int i = 1, loopTo = CollectionSQL.Count; i <= loopTo; i++) + colSQL.Add(CollectionSQL[i]); + } + + blnExecResult = true; + } + catch (Exception ex) + { + clsERP.combineException(ref aryException, sysmsg: ex.Message, mesmsg: "[%ExamineMOProcess%]", stack: iMESCore.Base.iMESComXML.CInput(ex.StackTrace)); + } + finally + { + CloseConnection(cnnTemp); + } + + return default(bool); + + } + private static DataSet ShowECNProcessData(string ProductNo, string ProductVersion, string MOTypeNo, ref List aryException, DataTable dtECN) + { + DataSet ShowECNProcessDataRet = default(DataSet); + + // dtECN 傳入LotNo,OrgLotNo,CustomerLotNo,MONo 的資料只會有一筆 + + var CollectionSQL = new Collection(); + var CreateDate = DateTime.Now; + string strSQLAddField, strSQLAddValue; + string strSQL = ""; + var drTemp = default(DbDataReader); + DbDataReader drSEN; + DbDataReader drTECN; + DbDataReader drECN; + var dtProcess = new DataTable(); + string tblECNProcessData; + tblECNProcessData = "tblECNProcessData"; + dtProcess.TableName = tblECNProcessData; + dtProcess.Columns.Add("ECNNO", Type.GetType("System.String")); + dtProcess.Columns.Add("PROCESSNO", Type.GetType("System.String")); + dtProcess.Columns.Add("PROCESSVERSION", Type.GetType("System.String")); + dtProcess.Columns.Add("ECNTYPE", Type.GetType("System.String")); + + AppSettings objSetting = new AppSettings(); + bool blnAllProcess = false; // 用於判斷ECN是否有多條流程 + var cnnTemp = default(IDbConnection); + + try + { + string strDataBaseType = objSetting.GetDataBaseType(); + string strConnectionString = objSetting.GetConnectionString(strDataBaseType); + cnnTemp = CreateConnection(strConnectionString); + + DataSet dsTemp; + DataRow[] drSel; + + cnnTemp = CreateConnection(strConnectionString); + + // 檢查SEN + strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='SEN' and ECNState=2 ORDER BY SENType Desc "; + dsTemp = new DataSet(); + ExecuteSQLQuery_Adapter(strSQL, dsTemp, "TBLPRDECNPROCESS", cnnTemp); + + drSel = dsTemp.Tables["TBLPRDECNPROCESS"].Select(); + if (drSel.Length > 0) + { + foreach (DataRow r in drSel) + { + strSQL = "Select * from TBLPRDSENLOTDETAIL where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "'"; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTemp.Read()) // 比對有無相符的資料 + { + switch (drTemp["SENTYPE"].ToString()) + { + case "1": //客戶批號 + { + dtECN.DefaultView.RowFilter = "CustomerLotNo like '" + drTemp["LOTNO"].ToString() + "'"; + if (dtECN.DefaultView.Count == 1) + { + // 以ECNNO跟工單類型尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' "; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drSEN.Read()) + { + dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN"); + blnAllProcess = true; + } + + // 若目前工單類型找不到資料以*尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='-1' "; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drSEN.Read()) + { + dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN"); + blnAllProcess = true; + } + + + goto GoTonext; + } + + break; + } + case "0": //工單編號 + { + dtECN.DefaultView.RowFilter = "MONo like '" + drTemp["LOTNO"].ToString() + "'"; + if (dtECN.DefaultView.Count == 1) + { + // 以ECNNO跟工單類型尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' "; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drSEN.Read()) + { + dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN"); + blnAllProcess = true; + } + + // 若目前工單類型找不到資料以*尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + r["ECNNO"].ToString() + "' and MOTypeNo='-1' "; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drSEN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drSEN.Read()) + { + dtProcess.Rows.Add(r["ECNNO"].ToString(), drSEN["PROCESSNO"].ToString(), drSEN["PROCESSVERSION"], "SEN"); + blnAllProcess = true; + } + + goto GoTonext; + } + + break; + } + + } + } + drTemp.Close(); + ////cmmTemp.Dispose(); + } + } + + if (dsTemp != null) + { + dsTemp.Dispose(); + } + + // 2020/03/17 Eric + if (blnAllProcess == true) + { + goto GoTonext; + } + + // 檢查TECN + strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='TECN' and ECNState=2 " + "And StartTime <= To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS') And EndTime > To_Date('" + Strings.Format(DateTime.Now, "yyyy/MM/dd HH:mm:ss") + "','YYYY/MM/DD HH24:MI:SS')"; + // 2020/02/04 OwenLiu, 修正SQLServer 查詢問題 + strSQL = SQLCommandTuning(strDataBaseType, ref strSQL); + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + // 以ECNNO跟工單類型尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' "; + drTECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTECN.Read()) + { + dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drTECN["PROCESSNO"].ToString(), drTECN["PROCESSVERSION"], "TECN"); + blnAllProcess = true; + } + + // 若目前工單類型找不到資料以*尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='-1' "; + ////cmmTemp = new IDbCommand(strSQL, cnnTemp); // Select data + drTECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drTECN.Read()) + { + dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drTECN["PROCESSNO"].ToString(), drTECN["PROCESSVERSION"], "TECN"); + blnAllProcess = true; + } + + // 若有ECNNO卻無流程編號及版本回拋錯誤 + goto GoTonext; + } + drTemp.Close(); + + // 2020/03/17 Eric + if (blnAllProcess == true) + { + goto GoTonext; + } + + // 檢查ECN + strSQL = "Select * from TBLPRDECNPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNType='ECN' and ECNState=2 "; + drTemp = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + if (drTemp.Read()) + { + // 以ECNNO跟工單類型尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='" + MOTypeNo + "' "; + drECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drECN.Read()) + dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drECN["PROCESSNO"].ToString(), drECN["PROCESSVERSION"], "ECN"); + + // 若目前工單類型找不到資料以*尋找 + strSQL = "Select * from TBLPRDMOPROCESS where ProductNo='" + ProductNo + "' and productversion='" + ProductVersion + "' and ECNNO='" + drTemp["ECNNO"].ToString() + "' and MOTypeNo='-1' "; + drECN = ExecuteSQLQuery_Reader(strSQL, cnnTemp); + while (drECN.Read()) + dtProcess.Rows.Add(drTemp["ECNNO"].ToString(), drECN["PROCESSNO"].ToString(), drECN["PROCESSVERSION"], "ECN"); + + // 若有ECNNO卻無流程編號及版本回拋錯誤 + goto GoTonext; + } + + GoTonext: + ; + + drTemp.Close(); + + if (dtProcess.Rows.Count <= 0) { clsERP.combineException(ref aryException, mesmsg: "[%ProductNo%]:" + ProductNo + "[%CouldNotFindTheCorrespondingProcessData%]"); } //拋出找不到對應流程資料的錯誤,不允許新增工單 + + if (dsTemp != null) + { + dsTemp.Dispose(); + } + dsTemp.Tables.Add(dtProcess); + ShowECNProcessDataRet = dsTemp; + //LoadECNProcessDataRet = iMESCore.Base.iMESComXML.CombineXMLReturnValue("loadecnprocessdata", tblECNProcessData, "DataSet", iMESCore.Base.iMESComXML.FormatXMLSchema(dsTemp.GetXmlSchema()), dsTemp.GetXml(), ""); + } + + catch (Exception e1) + { + + // 發生錯誤時丟回本身的Function Name及系統錯誤訊息 + throw; + + } + finally + { + if (cnnTemp != null) + { + CloseConnection(cnnTemp); + } + } + return ShowECNProcessDataRet; + + } + #endregion + } +} diff --git a/MESEAI/EAItc/clsSPC.cs b/MESEAI/EAItc/clsSPC.cs new file mode 100644 index 0000000..b79d1ff --- /dev/null +++ b/MESEAI/EAItc/clsSPC.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using Microsoft.VisualBasic; + +namespace tcEAI_C +{ + + public class clsSPC + { + public static string strDataBaseType; + public static string strConnectionString; + + private string Filepath_E = @"D:\Log\EAI_TC\"; // 指定Log + + public void SaveLog(string msg) + { + if (!Directory.Exists(Filepath_E)) + { + Directory.CreateDirectory(Filepath_E); + } + //{ + // var withBlock = My.MyProject.Application.Log.DefaultFileLogWriter; + // // If CInt(Format(Now, "mm")) >= 20 And CInt(Format(Now, "mm")) < 40 Then + // // .BaseFileName = "Log" & "_20" 'Log檔的檔名 + // // ElseIf CInt(Format(Now, "mm")) >= 40 Then + // // .BaseFileName = "Log" & "_40" 'Log檔的檔名 + // // Else + // withBlock.BaseFileName = "Log"; // & Format(Now, "mm") 'Log檔的檔名 + // // End If + // withBlock.CustomLocation = Filepath_E; // 自訂Log檔的存放路徑 + // withBlock.AutoFlush = true; // Log檔寫完後自動清除緩衝 + // withBlock.LogFileCreationSchedule = Microsoft.VisualBasic.Logging.LogFileCreationScheduleOption.Daily; // 設定一天產生一個Log檔 + // withBlock.MaxFileSize = long.MaxValue; // 預設容量5M 改為 最大容量 + //} + + //My.MyProject.Application.Log.WriteEntry(string.Format("{0} {1}", Strings.Format(DateTime.Now, "yy/MM/dd HH:mm:ss ffff,"), msg)); + } + + public void combineException(ref List strException, string code = null, string sysmsg = null, string mesmsg = null, string stack = null) + { + bool result = false; + try + { + var al = new ArrayList(); + al.Add(code); + al.Add(sysmsg); + al.Add(mesmsg); + al.Add(stack); + strException.Add(al); + result = true; + } + catch (Exception ex) + { + result = false; + } + } + + + } +} \ No newline at end of file diff --git a/MESEAI/EAItc/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs b/MESEAI/EAItc/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs new file mode 100644 index 0000000..edc4647 --- /dev/null +++ b/MESEAI/EAItc/obj/Debug/.NETFramework,Version=v4.6.2.AssemblyAttributes.cs @@ -0,0 +1,4 @@ +// +using System; +using System.Reflection; +[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] diff --git a/MESEAI/EAItc/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/MESEAI/EAItc/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache new file mode 100644 index 0000000..6575b1b Binary files /dev/null and b/MESEAI/EAItc/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache differ diff --git a/MESEAI/EAItc/obj/Debug/EAItc_C.csproj.AssemblyReference.cache b/MESEAI/EAItc/obj/Debug/EAItc_C.csproj.AssemblyReference.cache new file mode 100644 index 0000000..e9bf8d1 Binary files /dev/null and b/MESEAI/EAItc/obj/Debug/EAItc_C.csproj.AssemblyReference.cache differ diff --git a/MESEAI/MESEAI.sln b/MESEAI/MESEAI.sln new file mode 100644 index 0000000..6b35361 --- /dev/null +++ b/MESEAI/MESEAI.sln @@ -0,0 +1,194 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.35325.158 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EAIws_C", "EAICws\EAICws\EAIws_C.csproj", "{74B7676A-6420-0784-301F-696024D2A8D7}" + ProjectSection(ProjectDependencies) = postProject + {443394E0-F618-0D60-04C0-E207199604A2} = {443394E0-F618-0D60-04C0-E207199604A2} + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EAItc_C", "EAItc\EAItc_C.csproj", "{443394E0-F618-0D60-04C0-E207199604A2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iMESCIOC", "..\iMESCIOC\iMESCIOC.csproj", "{3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + C++Buile|Any CPU = C++Buile|Any CPU + C++Buile|Mixed Platforms = C++Buile|Mixed Platforms + C++Buile|x64 = C++Buile|x64 + C++Buile|x86 = C++Buile|x86 + Debug|Any CPU = Debug|Any CPU + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Quick|Any CPU = Quick|Any CPU + Quick|Mixed Platforms = Quick|Mixed Platforms + Quick|x64 = Quick|x64 + Quick|x86 = Quick|x86 + Release|Any CPU = Release|Any CPU + Release|Mixed Platforms = Release|Mixed Platforms + Release|x64 = Release|x64 + Release|x86 = Release|x86 + StorageBuild|Any CPU = StorageBuild|Any CPU + StorageBuild|Mixed Platforms = StorageBuild|Mixed Platforms + StorageBuild|x64 = StorageBuild|x64 + StorageBuild|x86 = StorageBuild|x86 + UnitTest|Any CPU = UnitTest|Any CPU + UnitTest|Mixed Platforms = UnitTest|Mixed Platforms + UnitTest|x64 = UnitTest|x64 + UnitTest|x86 = UnitTest|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|Any CPU.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|Any CPU.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|Mixed Platforms.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|Mixed Platforms.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|x64.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|x64.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|x86.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.C++Buile|x86.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|x64.ActiveCfg = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|x64.Build.0 = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|x86.ActiveCfg = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Debug|x86.Build.0 = Debug|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|Any CPU.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|Any CPU.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|Mixed Platforms.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|Mixed Platforms.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|x64.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|x64.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|x86.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Quick|x86.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|Any CPU.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|x64.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|x64.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|x86.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.Release|x86.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|Any CPU.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|Any CPU.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|Mixed Platforms.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|Mixed Platforms.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|x64.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|x64.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|x86.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.StorageBuild|x86.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|Any CPU.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|Any CPU.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|Mixed Platforms.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|x64.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|x64.Build.0 = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|x86.ActiveCfg = Release|Any CPU + {74B7676A-6420-0784-301F-696024D2A8D7}.UnitTest|x86.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|Any CPU.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|Any CPU.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|Mixed Platforms.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|Mixed Platforms.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|x64.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|x64.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|x86.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.C++Buile|x86.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|x64.ActiveCfg = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|x64.Build.0 = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|x86.ActiveCfg = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Debug|x86.Build.0 = Debug|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|Any CPU.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|Any CPU.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|Mixed Platforms.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|Mixed Platforms.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|x64.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|x64.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|x86.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Quick|x86.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|Any CPU.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|x64.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|x64.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|x86.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.Release|x86.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|Any CPU.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|Any CPU.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|Mixed Platforms.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|Mixed Platforms.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|x64.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|x64.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|x86.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.StorageBuild|x86.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|Any CPU.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|Any CPU.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|Mixed Platforms.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|Mixed Platforms.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|x64.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|x64.Build.0 = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|x86.ActiveCfg = Release|Any CPU + {443394E0-F618-0D60-04C0-E207199604A2}.UnitTest|x86.Build.0 = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|Any CPU.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|Any CPU.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|Mixed Platforms.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|x64.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|x64.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|x86.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.C++Buile|x86.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|x64.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|x64.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|x86.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Debug|x86.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|Any CPU.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|Any CPU.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|Mixed Platforms.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|x64.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|x64.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|x86.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Quick|x86.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|Any CPU.Build.0 = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|x64.ActiveCfg = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|x64.Build.0 = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|x86.ActiveCfg = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.Release|x86.Build.0 = Release|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|Any CPU.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|Any CPU.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|Mixed Platforms.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|x64.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|x64.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|x86.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.StorageBuild|x86.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|Any CPU.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|Any CPU.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|Mixed Platforms.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|x64.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|x64.Build.0 = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|x86.ActiveCfg = Debug|Any CPU + {3A1F68B3-EBE4-4A86-9334-F66EC3DCE0AD}.UnitTest|x86.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8C4647D6-0300-48B8-9394-09E4BF0D878A} + EndGlobalSection +EndGlobal diff --git a/MESEAI/packages/BouncyCastle.1.8.9/.signature.p7s b/MESEAI/packages/BouncyCastle.1.8.9/.signature.p7s new file mode 100644 index 0000000..611fac3 Binary files /dev/null and b/MESEAI/packages/BouncyCastle.1.8.9/.signature.p7s differ diff --git a/MESEAI/packages/BouncyCastle.1.8.9/BouncyCastle.1.8.9.nupkg b/MESEAI/packages/BouncyCastle.1.8.9/BouncyCastle.1.8.9.nupkg new file mode 100644 index 0000000..1ce7158 Binary files /dev/null and b/MESEAI/packages/BouncyCastle.1.8.9/BouncyCastle.1.8.9.nupkg differ diff --git a/MESEAI/packages/BouncyCastle.1.8.9/README.md b/MESEAI/packages/BouncyCastle.1.8.9/README.md new file mode 100644 index 0000000..270d9cc --- /dev/null +++ b/MESEAI/packages/BouncyCastle.1.8.9/README.md @@ -0,0 +1,30 @@ +# The Bouncy Castle Crypto Package For C Sharp + +The Bouncy Castle Crypto package is a C\# implementation of cryptographic algorithms and protocols, it was developed by the Legion of the Bouncy Castle, a registered Australian Charity, with a little help! The Legion, and the latest goings on with this package, can be found at [http://www.bouncycastle.org](http://www.bouncycastle.org). In addition to providing basic cryptography algorithms, the package also provides support for CMS, TSP, X.509 certificate generation and a variety of other standards such as OpenPGP. + +The Legion also gratefully acknowledges the contributions made to this package by others (see [here](http://www.bouncycastle.org/csharp/contributors.html) for the current list). If you would like to contribute to our efforts please feel free to get in touch with us or visit our [donations page](https://www.bouncycastle.org/donate), sponsor some specific work, or purchase a support contract through [Crypto Workshop](http://www.cryptoworkshop.com). + +Except where otherwise stated, this software is distributed under a license based on the MIT X Consortium license. To view the license, [see here](http://www.bouncycastle.org/licence.html). The OpenPGP library also includes a modified BZIP2 library which is licensed under the [Apache Software License, Version 2.0](http://www.apache.org/licenses/). + +**Note**: this source tree is not the FIPS version of the APIs - if you are interested in our FIPS version please contact us directly at [office@bouncycastle.org](mailto:office@bouncycastle.org). + +## Mailing Lists + +For those who are interested, there are 2 mailing lists for participation in this project. To subscribe use the links below and include the word subscribe in the message body. (To unsubscribe, replace **subscribe** with **unsubscribe** in the message body) + +* [announce-crypto-csharp-request@bouncycastle.org](mailto:announce-crypto-csharp-request@bouncycastle.org) + This mailing list is for new release announcements only, general subscribers cannot post to it. +* [dev-crypto-csharp-request@bouncycastle.org](mailto:dev-crypto-csharp-request@bouncycastle.org) + This mailing list is for discussion of development of the package. This includes bugs, comments, requests for enhancements, questions about use or operation. + +**NOTE:**You need to be subscribed to send mail to the above mailing list. + +## Feedback + +If you want to provide feedback directly to the members of **The Legion** then please use [feedback-crypto@bouncycastle.org](mailto:feedback-crypto@bouncycastle.org), if you want to help this project survive please consider [donating](https://www.bouncycastle.org/donate). + +For bug reporting/requests you can report issues here on github, via feedback-crypto if required, and we also have a [Jira issue tracker](http://www.bouncycastle.org/jira). We will accept pull requests based on this repository as well. + +## Finally + +Enjoy!