From a1cdfaa4d246cbbb1853a8020b045271e9c59dc0 Mon Sep 17 00:00:00 2001
From: Sai <Sai@hotmail.com>
Date: Tue, 18 Jun 2024 01:59:57 +0800
Subject: [PATCH] =?UTF-8?q?1.=20=E8=AA=BF=E6=95=B4PTD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../Controllers/PTDController.cs              |  28 ++--
 AMESCoreStudio.Web/Views/PTD/PTD006.cshtml    |  30 ++--
 .../Controllers/AMES/WipInfosController.cs    | 145 +++++++++++++++++-
 3 files changed, 171 insertions(+), 32 deletions(-)

diff --git a/AMESCoreStudio.Web/Controllers/PTDController.cs b/AMESCoreStudio.Web/Controllers/PTDController.cs
index 4cd70402..2a95cea0 100644
--- a/AMESCoreStudio.Web/Controllers/PTDController.cs
+++ b/AMESCoreStudio.Web/Controllers/PTDController.cs
@@ -455,20 +455,20 @@ namespace AMESCoreStudio.Web.Controllers
                 return "請輸入 Location";
             }
 
-            var recordType = await _ptdApi.GetRecordTypeInfoById(model.RecordType);
-            if (recordType.Any())
-            {
-                var recordInfoItem = recordType.FirstOrDefault();
-                if (model.RecordNumber.Length != int.Parse((string)recordInfoItem.length))
-                    return "RecordNumber長度與設定的長度不符,請在確認";
-
-                if (!model.RecordNumber.StartsWith((string)recordInfoItem.prefixCode))
-                    return "RecordNumber單據號碼開頭與設定開頭不符,請在確認";
-            }
-            else
-            {
-                return "請維護RecordNumber單投說明表";
-            }
+            //var recordType = await _ptdApi.GetRecordTypeInfoById(model.RecordType);
+            //if (recordType.Any())
+            //{
+            //    var recordInfoItem = recordType.FirstOrDefault();
+            //    if (model.RecordNumber.Length != int.Parse((string)recordInfoItem.length))
+            //        return "RecordNumber長度與設定的長度不符,請在確認";
+
+            //    if (!model.RecordNumber.StartsWith((string)recordInfoItem.prefixCode))
+            //        return "RecordNumber單據號碼開頭與設定開頭不符,請在確認";
+            //}
+            //else
+            //{
+            //    return "請維護RecordNumber單投說明表";
+            //}
 
             // ProductId
             if (string.IsNullOrWhiteSpace(model.ProductId))
diff --git a/AMESCoreStudio.Web/Views/PTD/PTD006.cshtml b/AMESCoreStudio.Web/Views/PTD/PTD006.cshtml
index 64d3fafe..db42a331 100644
--- a/AMESCoreStudio.Web/Views/PTD/PTD006.cshtml
+++ b/AMESCoreStudio.Web/Views/PTD/PTD006.cshtml
@@ -229,14 +229,16 @@
                     page: {
                         curr: 1
                     },
-                    success: function () {
+                    done: function (res, curr, count) {
                         // 表格更新成功後計算資料筆數
-                        calculateRowCount(table.cache['query']);
+                        calculateRowCount(res.data);
+                        var lineNo = document.getElementById('lineNo');
+                        lineNo.focus();
                     }
                 });
-                calculateRowCount(table.cache['query']);
-                var lineNo = document.getElementById('lineNo');
-                lineNo.focus();
+                //calculateRowCount(table.cache['query']);
+                //var lineNo = document.getElementById('lineNo');
+                //lineNo.focus();
             }
         });
         $('#lineNo').on('keypress', function (event) {
@@ -254,12 +256,11 @@
                     page: {
                         curr: 1
                     },
-                    success: function () {
-                        // 表格更新成功後計算資料筆數
+                    done: function (res, curr, count) {
                         calculateRowCount(table.cache['query']);
                     }
                 });
-                calculateRowCount(table.cache['query']);
+
                 // 发送 AJAX 请求到 Controller
                 $.ajax({
                     url: '@Url.Action("GetZDNDetailJson", "PTD")',
@@ -382,10 +383,13 @@
                             },
                             page: {
                                 curr: 1
-                            }
+                            },
+                             done: function(res, curr, count) {
+                                 // 表格更新成功後計算資料筆數
+                                 calculateRowCount(res.data);
+                                 layer.msg('備貨成功!', { icon: 1 });
+                             }
                         });
-                        calculateRowCount(table.cache['query']);
-                        layer.msg('備貨成功!', { icon: 1 });
                     }
                     else {
                         hg.msg('加入失敗:' + res.msg);
@@ -472,8 +476,10 @@
         }
 
         function calculateRowCount(table) {
+            const rowCount = document.getElementById('rowCount');
             var RowCount = table.length;
-            $("#rowCount").html("應出貨數量: 0 pcs,目前刷入數量: " + RowCount + " pcs");
+            rowCount.innerHTML = `應出貨數量: 0 pcs,目前刷入數量: ${RowCount} pcs`;
+            console.log(RowCount);
         }
 
         function addRow(tableId, rowData) {
diff --git a/AMESCoreStudio.WebApi/Controllers/AMES/WipInfosController.cs b/AMESCoreStudio.WebApi/Controllers/AMES/WipInfosController.cs
index f47c12d1..0202aa2b 100644
--- a/AMESCoreStudio.WebApi/Controllers/AMES/WipInfosController.cs
+++ b/AMESCoreStudio.WebApi/Controllers/AMES/WipInfosController.cs
@@ -16,6 +16,9 @@ using System.IO;
 using System.Collections.ObjectModel;
 using AMESCoreStudio.WebApi.Controllers.BLL;
 using System.Text;
+using System.Data.SqlClient;
+using Microsoft.Extensions.Configuration;
+using Dapper;
 
 namespace AMESCoreStudio.WebApi.Controllers.AMES
 {
@@ -29,6 +32,7 @@ namespace AMESCoreStudio.WebApi.Controllers.AMES
         private readonly AMESContext _context;
         private readonly ESUNContext _esun_context;
         private readonly IConfiguration _config;
+        private readonly string _PTDContext;
 
         /// <summary>
         /// 
@@ -38,6 +42,7 @@ namespace AMESCoreStudio.WebApi.Controllers.AMES
         {
             _config = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json").Build();
             _context = context;
+            _PTDContext = _config.GetConnectionString("PTDContext");
         }
 
         /// <summary>
@@ -3040,13 +3045,13 @@ and b.item_no = '{0}' and a.barcode_no = '{1}'", kp_no, barcode_no);
             htmlTable.AppendLine("</thead>");
             htmlTable.AppendLine("<tbody>");
             //Mail Body Html
-            foreach (SNDataModel SNData in data.TableData)
+            foreach (var SNData in data.TableData)
             {
                 htmlTable.AppendLine("<tr>");
-                htmlTable.AppendLine($"<td>{SNData.DnNo}</td>");
-                htmlTable.AppendLine($"<td>{SNData.LineNo}</td>");
-                htmlTable.AppendLine($"<td>{SNData.Material}</td>");
-                htmlTable.AppendLine($"<td>{SNData.Sn}</td>");
+                htmlTable.AppendLine($"<td>{SNData.dnNo}</td>");
+                htmlTable.AppendLine($"<td>{SNData.lineNo}</td>");
+                htmlTable.AppendLine($"<td>{SNData.material}</td>");
+                htmlTable.AppendLine($"<td>{SNData.sn}</td>");
                 htmlTable.AppendLine("</tr>");
             }
             //Mail Body Html
@@ -3201,7 +3206,7 @@ and b.item_no = '{0}' and a.barcode_no = '{1}'", kp_no, barcode_no);
 
                             // Commit the transaction
                             transaction.Commit();
-                            await SendMail(strRecordType, Data);
+                            //await SendMail(strRecordType, Data);
                         }
                         catch (Exception ex)
                         {
@@ -4693,6 +4698,134 @@ and b.item_no = '{0}' and a.barcode_no = '{1}'", kp_no, barcode_no);
         [Route("[action]")]
         [HttpPost]
         public async Task<ResultModel<dynamic>> PostPTD007Commit(PTD007CommitDataModel Data)
+        {
+            ResultModel<dynamic> result = new ResultModel<dynamic>();
+            List<string> SNList = new List<string>();
+            Collection<string> colSQL = new Collection<string>();
+
+            try
+            {
+                // RecordDate 加入目前時間
+                Data.RecordDate += $" {DateTime.Now:HH:mm:ss}";
+
+                string strSQL = "";
+                string strRecordType = Data.RecordType;
+                string strRbu = Data.Rbu;
+                string strWorkCenter = Data.WorkCenter;
+                string strRecordDate = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(Data.RecordDate)).ToString("yyyy-MM-dd HH:mm:ss");
+                string strCreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
+                using (IDbConnection ptdConnection = new SqlConnection(_PTDContext))
+                {
+                    if (ptdConnection.State != ConnectionState.Open)
+                    {
+                        ptdConnection.Open();
+                    }
+                    foreach (PTD007TableDataModel SNData in Data.TableData)
+                    {
+                        //ZWHPickListDetail查SN資訊
+                        strSQL = $@"Select * FROM [SFIS_PTD].[dbo].[ZWHPickListDetail] 
+                            where RecordNumber='{SNData.dnno}' and RCLineNO='{SNData.dnLineNO}'";
+
+                        var q = await ptdConnection.QueryAsync<dynamic>(strSQL);
+
+                        foreach (var row in q)
+                        {
+                            string strLatest;
+                            //確認此出貨序號是否有ZHistoryKeyDefine
+                            strSQL = $@"select Seed FROM [SFIS_PTD].[dbo].[ZHistoryKeyDefine] where serialnumber ='{row.ShipmentSN}'";
+
+                            var q1 = await ptdConnection.QueryAsync<dynamic>(strSQL);
+
+                            if (q1.Any())
+                            {
+                                int seed = Convert.ToInt32(q1.FirstOrDefault().Seed);
+                                int nIdx = seed + 1;
+                                strLatest = row.ShipmentSN + nIdx.ToString().PadLeft(4, '0');//組成HistoryID
+                                                                                                           //HistoryKeyDefine
+                                strSQL = @$"UPDATE [SFIS_PTD].[dbo].[ZHistoryKeyDefine]
+                                                SET [Seed] = {nIdx} where [SerialNumber]='{row.ShipmentSN}'";
+                                colSQL.Add(strSQL);
+                                //ZSNInfo
+                                strSQL = @$"Update [SFIS_PTD].[dbo].[ZSNInfo] SET LatestHistoryID='{strLatest}',RecordTypeID='{strRecordType}', 
+                                                                         CurrentProductID='{row.ProductID}'
+                                                    where SerialNumber='{row.ShipmentSN}'";
+                                colSQL.Add(strSQL);
+                            }
+                            else
+                            {
+                                strLatest = row.ShipmentSN + 1.ToString().PadLeft(4, '0');//組成HistoryID
+                                                                                                        //ZHistoryKeyDefine
+                                strSQL = @$"INSERT INTO [SFIS_PTD].[dbo].[ZHistoryKeyDefine] ([SerialNumber],[Seed])
+                                            VALUES ('{row.ShipmentSN}',1)";
+                                colSQL.Add(strSQL);
+                                //ZSNInfo
+                                strSQL = @$"INSERT INTO [SFIS_PTD].[dbo].[ZSNInfo] ([SerialNumber],[CurrentProductID],[OriginalProductID],
+                                                        [LocationID],[LatestHistoryID],[RecordTypeID],
+                                                        [OwnerPlantID],[OwnerCompanyID],[CreatePlantID],[CreateCompanyID],
+                                                        [ModifyDate]) VALUES 
+                                                        ('{row.ShipmentSN}','{row.ProductID}','{row.ProductID}',
+                                                        '9000','{strLatest}','{strRecordType}',
+                                                        '{strWorkCenter}','{strRbu}','{strWorkCenter}','{strRbu}',
+                                                        '{strCreateDate}')";
+                                colSQL.Add(strSQL);
+                            }
+                            //ZProductTrans
+                            strSQL = $@"INSERT INTO [SFIS_PTD].[dbo].[ZProductTrans] 
+                                                    ([HistoryID],[SerialNumber],[RecordTypeID],[RecordNumber],[RCLineNO],[RecordDate],
+                                                     [ProductID],[IsChangeID],[LocationID],[EmplID],[IsDelete],
+                                                     [OwnerPlantID],[OwnerCompanyID],[CreatePlantID],[CreateCompanyID],
+                                                     [CreatorID],[CreateDate],[ModifierID],[ModifyDate],
+                                                     [chkflag],[IsBranchCoReceived],[MOID]) VALUES 
+                                                    ('{strLatest}','{row.ShipmentSN}','{strRecordType}','{SNData.dnno}','{SNData.dnLineNO}','{strRecordDate}',
+                                                     '{SNData.productID}',0,'9000','{SNData.soldCustomerID.ToString()}',0,
+                                                     '{strWorkCenter}','{strRbu}','{strWorkCenter}','{strRbu}',
+                                                     'WH00','{strCreateDate}','WH00','{strCreateDate}',0,0,'')";
+                            colSQL.Add(strSQL);
+
+                        }
+                        strSQL = $@"Update [SFIS_PTD].[dbo].[ZWHPickListDetail] set TaskStatus ='Recorded' 
+                                    where RecordNumber='{SNData.dnno}' and RCLineNO='{SNData.dnLineNO}'";
+                        colSQL.Add(strSQL);
+                    }
+
+                    using (var transaction = ptdConnection.BeginTransaction())
+                    {
+                        try
+                        {
+                            foreach (string query in colSQL)
+                            {
+                                await ptdConnection.ExecuteAsync(query,transaction: transaction);
+                            }
+
+                            // Commit the transaction
+                            transaction.Commit();
+                            //await SendMail(strRecordType, Data);
+                        }
+                        catch (Exception ex)
+                        {
+                            // Rollback the transaction in case of an exception
+                            transaction.Rollback();
+                            throw ex; // Rethrow the exception after rollback
+                        }
+                    }
+                }
+
+
+                result.Success = true;
+                result.Msg = "OK";
+            }
+            catch (Exception ex)
+            {
+                result.Success = false;
+                result.Msg = ex.Message;
+            }
+            return result;
+
+        }
+
+        [Route("[action]")]
+        [HttpPost]
+        public async Task<ResultModel<dynamic>> PostPTD007CommitOld(PTD007CommitDataModel Data)
         {
             ResultModel<dynamic> result = new ResultModel<dynamic>();
             List<string> SNList = new List<string>();