2022年8月10日 星期三

V120902 - 自動設定子畫面 - Grid的高度 , - 判斷元件是否已顯示在畫面(.el)

目的: 視窗大小調整時, 設定 Grid的度度

處理說明 :  1>Grid的高度 = Form.高度 - 過濾Panel.高度  - 按鈕Panel.高度;
                     2>若 Grid 已 Create, 但是尚未顯示在畫面,則無法 getHeight() 及 getWidth()
                          判斷元件是否已顯示在畫面 ,     typeof Ext.getCmp("grid_M").el
                          --> if  (typeof Ext.getCmp("grid_M").el != undefined)      
                                        Ext.getCmp("grid_M").getHeight();



 // [缺勤記錄維護]鈕  - 子畫面欄位

     var mySub2 = [
            {
                type: 'panel', bodyStyle: "background-color:transparent;", border: 0, layout: { type: 'vbox', align: 'stretch' }, padding: "5",
                items: [
                    {
                        xtype: 'panel',
                        id: 'sub2_panel1',
                        //title: 'sub2_panel1',
                        layout: { type: 'hbox', align: 'stretch' },
                        flex: 0,
                        border: 1,
                        items: [
                            {
                                xtype: 'panel',
                                id: 'sub2_panel11',
                                layout: { type: 'vbox', align: 'stretch' },
                                flex: 15,
                                border: 0,
                                items: [{
                                 xtype: "fieldcontainer", fieldLabel: "日期", labelWidth: 60, layout: "hbox", flex: 2,
 items: [{ xtype: "tmdatefield", id: "sub2_DT", name: "sub2_DT", width: 100, padding: "0 4 0 0", },]
                                }, // end of s_日期
                      
                                ]
                            }, //end of sub2_panel11 , flex:20
                      
                            }, //end of sub2_panel12 , flex:20
                            {
                                //xtype: 'toolbar',
                                xtype: 'panel',
                                id: 'sub2_panel13',
                                layout: { type: 'vbox', align: 'right' },
                                flex: 5,
                                border: 0,
                                items: [
                                    {
                                        xtype: 'button',
                                        id: 'sub2_btn_Show',
                                        flex: 2,
                                        border: 1,
                                        text: '資料顯示',  //sub2
                                        iconCls: 'icon-search',
                                        handler: function () {
                                            var np = {};
                                            np["sub2_DT"] = Ext.getCmp("sub2_DT").getValue();
                                            np["sub2_DEP"] = Ext.getCmp("sub2_DEP").getValue();
                                            np["sub2_LDMAN"] = Ext.getCmp("sub2_LDMAN").getValue();
                                            //console.log('np:', np);
             Ext.getCmp('sub2_Grid').store.getProxy().url = '../api/V120902API/getsub2Data';
              Ext.getCmp('sub2_Grid').store.getProxy().extraParams = np; //分頁OK,篩選條件OK
                                            Ext.getCmp('sub2_Grid').reloadGirdData();                                            
Ext.getCmp('mySubForm').getHeight());
Ext.getCmp('sub2_panel1').getHeight());
Ext.getCmp('sub2_panel2').getHeight());
Ext.getCmp('sub2_Grid').getHeight());
Ext.getCmp('sub2_Grid').getHeight());
                                        }
                                    },  // end of 顯示資料
                                    {
                                        xtype: 'button',
                                        id: 'sub2_btn_clear',
                                        flex: 2,
                                        border: 1,
                                        text: '清除條件',
                                        iconCls: 'icon-clear',
                                        handler: function () {
                                            var f = Query.getForm();
                                            f.reset();
                                        }
                                    },  // end of 清除條件                                   
                                ]  // end of items of [顯示資料][清除條件]
                            }   // end of panel13
                        ]
                    },  //end of panel1                    
                    {
                        xtype: 'panel',
                        id: 'sub2_panel2',
                        //title: 'sub2_panel2',
                        layout: { type: 'vbox', align: 'stretch' },
                        //flex: 60,
                        border: 1,
                        items: [sub2_Grid]
                    },
                ] // end of   layout: "vbox", padding: "5", items: [
            }  //end of  my_Sub2 , items[{
        ]      //end of  my_Sub2 , items[
        var win = getMyWindow("缺勤記錄維護", mySub2, mySub2_Btns);

        win.width = 700;
        win.height = 400;
        win.on('resize', function (me, width, height, eOpts) {
            //console.log("win.resize height=",height);
            var Tmp_okpanel_Height = Ext.getCmp('mySub2_OkBtn').getHeight() + 20;            
            var Tmp_rHeight = Ext.getCmp('mySubForm').getHeight() - Ext.getCmp('sub2_panel1').getHeight() - Tmp_okpanel_Height;            
            Ext.getCmp('sub2_panel2').setHeight(Tmp_rHeight);
            //console.log("win.resize Tmp_rHeight=", Tmp_rHeight);            
        });
        win.show();

2022年8月9日 星期二

V120402 - 新增/修改/刪除.Disabled 及 新增按鈕 - Detail畫面處理

 目的: 在畫面[新增]/[修改]/[刪除]按鈕Disabled , 並新增其他 [按鈕]

處理說明: 1>將在畫面[新增]/[修改]/[刪除]按鈕Disabled
                  2>Detail畫面新增[按鈕]
                  3>開啟 Detail 資料


1>將在畫面[新增]/[修改]/[刪除]按鈕Disabled 

//新增 , 查詢畫面, 無新增/修改/刪除/..
    Ext.getCmp('btn_add').setDisabled(false);   //[新增]鈕設為 Disabled
    Ext.getCmp('btn_add').setVisible(false);      //[新增]鈕設為 隱藏
    Ext.getCmp('btn_edit').setVisible(false);
    Ext.getCmp('btn_del').setVisible(false);


2>Detail畫面新增[按鈕]
//按鈕 : [借閱登記] [歸還登記][續借登記][查詢借閱記錄][報表]
    var BtnAry = [
        {
            xtype: 'button', text: '借閱登記', id: 'LendBtn',
            listeners: {
                click: function () {
                    //RollPrnBtn_click();
                }
            }
        },
        {
            xtype: 'button', text: '歸還登記', id: 'BackBtn',
            listeners: {
                click: function () {
                    //console.log(" 1 inside 缺勤記錄維護: ");
                    //RollEditBtn_click();
                }
            }
        },
        {
            xtype: 'button', text: '續借登記', id: 'ContBtn',
            listeners: {
                click: function () {
                    //console.log(" 1 inside 缺勤記錄維護: ");
                    //RollEditBtn_click();
                }
            }
        },
        {
            xtype: 'button', text: '查詢借閱記錄', id: 'LookBtn',
            listeners: {
                click: function () {
                    //console.log(" 1 inside 缺勤記錄維護: ");
                    //RollEditBtn_click();
                }
            }
        },
        {
            xtype: 'button', text: '報表', id: 'RtnBtn',
            listeners: {
                click: function () {
                    //console.log(" 1 inside 缺勤記錄維護: ");
                    //RollEditBtn_click();
                }
            }
        },

    ];

    //於單檔下方新增 Button
    Ext.getCmp('grid_D').insertBtn(BtnAry);

3>開啟 Detail 資料
 public dynamic getGridData_D()
        {
            var c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            OracleCommand cmd = new OracleCommand();
            string TMNO = nvc["TMNO"];
            string csSQL = " AND TMNO = :TMNO ";
            cmd.CommandText = csSQL;
            cmd.Parameters.Add(":TMNO", TMNO);
            setDBTable("AMM_TMDWGD");
            DataSet ds = getGridDataPage(cmd);

            return ds;
        }

2022年8月8日 星期一

Ext.Ajax.request - 傳送檔案至 Browser - mask 資料處理中,請稍候 , Cookie

1>目的: 透過 Form.submit 方式,於後端處理後,將結果檔案傳送至前端
2>處理說明: 


1>*.js  - [確認匯入]鈕, 將匯入結果,存於 xls最後一欄後,傳至前端 , 錯誤訊息以 Cookie 傳回

 //[確認匯入]鈕 , 處理
    function mySubForm_2_btnokClick() {
        //取得 [檔案上傳].檔名
        var btn_FileIn_Obj = Ext.getCmp('sub_FName');
        var Tmp_Str = "";
        var np = {
            FName: Ext.getDom(btn_FileIn_Obj.inputId).value
        };
        console.log("FName: ", np.FName);
        //submit會將fileUploadForm裡面input name送到後端
        //Ext.getCmp('btn_FileIn').getForm().submit({
        Ext.getCmp('mySubForm_2_btnok').up("form").submit({
            //standardSubmit: false,    //default:false
            url: '../api/V120103API/uploadFileToDB',
            method: 'POST',
            async: false,

            headers: { 'Content-type': 'multipart/form-data' },
            params: np,
            standardsubmit=true    //才可將檔案送至前端
        } ) //end of submit;
          //顯示匯入結果
        var mask = new Ext.LoadMask(Ext.getBody(), {
            msg: '資料處理中,請稍候...'
        });
        mask.show();//使用 mask 需手動呼叫show() 方法下
        var timer = setInterval(function () {
            var cookie_token = Ext.util.Cookies.get("Rtn_Msg");
            if (cookie_token != null) {
                clearInterval(timer);
                timer = null;
                mask.hide();
                //console.log(" show result !!");
                var r = r_cookies("Rtn_Msg");
                mysuccessalert(r);

                Ext.getCmp('mySubForm_2_btnok').up("window").close();
                Ext.getCmp('mySubForm_2_btnok').up("window").destroy();
                //mysuccessalert('檔案匯出完成');
            }
        }, 1000);       
        
    };  // end of mySubForm_2_btnokClick() {


2>*.cs  - 透過 Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" +          
                HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");  
             --> 傳送檔案至 Browser   

//[匯入] 鈕 , 匯入 XLS 檔案 void
        [HttpPost]
        public void uploadFileToDB()
        {

            HttpContext c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            //匯入檔案名稱(含 *.xlsx)
            string FName = nvc["FName"];
            string FName0 =Path.GetFileNameWithoutExtension(FName) ;  //不含 extension
            string Tmp_FName = FName;
            Workbook wk = null;

            HttpRequest Request = HttpContext.Current.Request;
            var response = this.Request.CreateResponse();
            string file_Name = FName;
            string FILEDT = DateTime.Now.ToString("yyyy-MM-dd");
            string Tmp_RtnMsg = "";
            string Tmp_Sql = "", Tmp_Str = "";
            int Tmp_CNT = 0;

            MemoryStream stream = new MemoryStream();
            HttpCookie MyCookie = new HttpCookie("Rtn_Msg");
            foreach (string cur_FName in Request.Files)
            {
                string fileType = Request.Files[cur_FName].ContentType;
                Stream file_Strm = Request.Files[cur_FName].InputStream;
                file_Name = Path.GetFileName(Request.Files[cur_FName].FileName);                
                int fileSize = Request.Files[cur_FName].ContentLength;
                byte[] fileRcrd = new byte[fileSize];
                //更新資料庫欄位值                
                int Tmp_curpos = 0;                
                bool Tmp_isOK = true;
                try
                {

                    wk = new Workbook();
                    wk.LoadFromStream(file_Strm);
                    Worksheet sheet1 = wk.Worksheets[0];//獲取第一個工作表
                                                        //共 10 欄
//string[] outFieldArray = { "計畫代碼", "父件件號", "件號", "件號中文名稱", "每機用量", 
                                             "BOM量", "計量單位", "工廠", "類別","備註" };
                                                        //int RowsCount = sheet1.Rows.Count();
                    int RowsCount = sheet1.LastRow;
                    string Tmp_CLS,Tmp_ITM,  Tmp_DITM, Tmp_NM, Tmp_REPN, Tmp_RESN, Tmp_INPN, Tmp_INSN, Tmp_RMK;
                    string Tmp_PLNC, Tmp_REWK, Tmp_INSC, Tmp_STLCT, Tmp_NOTE, Tmp_FACWC;
                    string Tmp_RESULT;

                    //STEP1 檢核  XLS 欄位名稱資料是否正確                                            
                    //類別 排序項次 名稱 拆移件號 拆移序號 安裝件號 安裝序號 備考
                    // 拆移PlanningCard 修理REWORK 安裝InstallationCard 儲位 備註 拆移工廠
                    Tmp_RtnMsg = "匯入檔案欄位名稱必需如下:<br>";
                    Tmp_CLS = sheet1.Range[myfunc.GetExcelPos(0, 0)].Value;
                    if (Tmp_CLS != "類別")
                        Tmp_RtnMsg = Tmp_RtnMsg + "第1欄位名稱必需為[類別],";
                    Tmp_DITM = sheet1.Range[myfunc.GetExcelPos(1, 0)].Value;
                    if (Tmp_DITM != "排序項次")
                        Tmp_RtnMsg = Tmp_RtnMsg + "第2欄位名稱必需為[排序項次],";
                    //新增[結果說明]欄位
                    Tmp_RESULT = "結果說明";
                    sheet1.Range[myfunc.GetExcelPos(14, 0)].Value=Tmp_RESULT;

                    //xls 欄位名稱有問題                                                    
                    if ((Tmp_CLS != "類別") || (Tmp_DITM != "排序項次") || (Tmp_NM != "名稱") || (Tmp_REPN != "拆移件號") || (Tmp_RESN != "拆移序號") ||
                          (Tmp_INPN != "安裝件號") || (Tmp_INSN != "安裝序號") || (!Tmp_RMK.Contains("備考")) ||
                          (Tmp_PLNC != "拆移PlanningCard") || (Tmp_REWK != "修理REWORK") || (Tmp_INSC != "安裝InstallationCard") || 
                          (Tmp_STLCT != "儲位") || (Tmp_NOTE != "備註") || (Tmp_FACWC != "拆移工廠")
                          )
                    {
                        Tmp_RtnMsg = Tmp_RtnMsg
                                                 +"敬請檢核";
                        //Tmp_Rtn_JSON = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
                        MyCookie.Value=  HttpUtility.UrlEncode(Tmp_RtnMsg);
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return ;
                    };

                    int Tmp_index;
                    Tmp_isOK = true;
                    //STEP2 檢核資料
                    for (int i = 0; i < RowsCount; i++)
                    {
                        Tmp_curpos = i + 1;
                     
                    //若資料不正確,則不寫入資料庫,只傳回檔案
                    if (Tmp_isOK == false)
                    {
                        Tmp_Str = "匯入檔案欄位值需修正!!<br>"
                                    + "請檢核如下檔案名稱(" + Tmp_FName + ")<br>";
                                    
                        MyCookie.Value = HttpUtility.UrlEncode(Tmp_Str);
                        // 若匯入資料有問題, 則不寫入資料庫 , 傳回結果檔案(*_結果.xlsx)
                        Tmp_FName = FName0 + "_結果.xlsx";
                        wk.SaveToStream(stream, FileFormat.Version2007);
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return;
                    }

V120103 - Ext.Ajax.reqest : AJAX Sample - getUrlStr(Tmp_url, np, "加入資料");

1>*.js
   //檢核是否 CLS+DITM 已存在 AMM_FRO3F16STD
/檢核欄位值是否正確
    Ext.getCmp('btn_save').checkFormValue = function () {

        var np = {};
        np["CLS"] = Tmp_CLS;
        np["DITM"] = Tmp_DITM;
        var isOk = true;
        Ext.Ajax.request({
            method: "POST",
            url: '../../api/V120103API/CHECK_CLS_DITM',
            params: np,
            async: false,
            success: function (response, opts) {
                console.log("0 response.responseText=", response.responseText);
                var Tmp_Obj = Ext.decode(response.responseText);

                console.log("1  Tmp_Obj=", Tmp_Obj);
                if (Tmp_Obj["success"] == false) {
                    var Tmp_Rtn_Msg = "類別(" + Tmp_CLS + ")排序項次(" + Tmp_DITM + ")已存在拆挪管制標準檔(AMM_FRO3F16STD)<br>"
                        + "請檢核<br>"
                        + Tmp_Obj["Rtn_Msg"];
                    mywarnalert(Tmp_Rtn_Msg);
                    isOk = false;
                }
            },  //end of success                
            failure: function (response, opts) {
                var Tmp_Obj = Ext.decode(response.responseText);
                var Tmp_Rtn_Msg = "類別(" + Tmp_CLS + ")排序項次(" + Tmp_DITM + ")已存在拆挪管制標準檔(AMM_FRO3F16STD)<br>"
                    + "請檢核<br>"
                    + Tmp_Obj["Rtn_Msg"];
                mywarnalert(Tmp_Rtn_Msg);
                isOk = false;
            }
        })  //end of Ext.Ajax.Request        
        if (isOk == true) {
            mysuccessalert("包裝完成確認成功!!");
            //資料更新完成, 重新顯示資料
            Ext.getCmp("btn_Show").fireHandler();
        }

    } // end of  checkFormValue 

2>*.cs
using TLSWEB_AMM.Service;
using TLSWEB_AMM.Models;

//檢查 CLS_DITM 是否重複(AMM_FRO3F16STD)
        [HttpPost]          
        public HttpResponseMessage CHECK_CLS_DITM()
        {
            var c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            string Tmp_CLS = nvc["CLS"];
            string Tmp_DITM = nvc["DITM"];            
            OracleConnection conn = new OracleConnection(DBService.ConnectionString(DBLINK));//
            OracleCommand cmd = new OracleCommand();
            OracleDataReader reader;
            var response = this.Request.CreateResponse();

            conn.Open();
            conn.ClientInfo = User.Identity.Name;
            conn.ModuleName = BaseSYS + "_" + BaseMODID;
            conn.ActionName = ActionName;
            cmd.Connection = conn;
            string Tmp_Sql = "";
            string Tmp_Str = "";
            string Tmp_RtnMsg;
            int Tmp_CNT = 0;
            try
            {
                Tmp_Sql = " SELECT    COUNT(*) AS CNT"
                               + "  FROM      AMM_FRO3F16STD "
                                + "  WHERE   CLS= " + myfunc.AA(Tmp_CLS)
                                + "   AND        DITM=" + myfunc.AA(Tmp_DITM);
                cmd.CommandText = Tmp_Sql;
                reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    Tmp_CNT = int.Parse(reader["CNT"].ToString());
                    if (Tmp_CNT > 0)
                    {
                        Tmp_RtnMsg = "類別(" + Tmp_CLS + ")排序項次(" + Tmp_DITM + ")已存在<br>"
                                                +" 不可重複!!<br>"
                                                + "請檢核<br>";
                        //將傳回值加入  JSON String
                        Tmp_Str = "{success: false,Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + ","                                                                 
                                        + " }";                     
                    }
                    else
                    {
                        Tmp_RtnMsg = "類別(" + Tmp_CLS + ")排序項次(" + Tmp_DITM + ")未重複!!<br>";                                         
                        //將傳回值加入  JSON String
                        Tmp_Str = "{success: true,Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + ","
                                        + " }";                        
                    }
                    response.Content = new StringContent(Tmp_Str);    // 回應內容
                    return response;
                }                // if reader.Read()                
            }  // end of try
            catch (Exception e)
            {
                var Tmp_ErrMsg = myfunc.Get1ORA(e.Message);
                Tmp_RtnMsg = "取得[類別][排序項次]的資料失敗 (CHECK_CLS_DITM) !!  <br> "
                                         + Tmp_ErrMsg;
                response.Content = new StringContent("{'success': false , failure: true , 'Rtn_Msg':'" + Tmp_RtnMsg + "' }");    // 回應內容
                return response;
            }
            finally
            {
                conn.Close();
            }
            return response;
        }  // end function CHECK_CLS_DITM() 


3>V120402C.cs  UPDATE 資料
// 更新 - UDPATE_AMM_TMDWGD  - 更新[借閱記錄(AMM_TMDWGD)].BRDAY
        [HttpPost]
        public HttpResponseMessage UPDATE_AMM_TMDWGD()
        {
            //取得參數值
            var c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;

            string Tmp_TMNO = nvc["TMNO"];
            string Tmp_RtnMsg = "";

            string n = funId + "_UPDATE_AMM_TMDWGD";
            OracleConnection conn = new OracleConnection(DBService.ConnectionString(DBLINK));
            OracleCommand cmd = new OracleCommand();
            var response = Request.CreateResponse();
            try
            {
                conn.Open();
                conn.ClientInfo = User.Identity.Name;
                conn.ModuleName = BaseSYS + "_" + BaseMODID;
                conn.ActionName = ActionName;
                cmd.BindByName = true;
                cmd.Connection = conn;
                string Tmp_Sql;
                Tmp_Sql = "  UPDATE  AMM_TMDWGD   "
                               + "  SET  BRDAY=nvl(BRDAY,0)+10 "
                               + "   WHERE   TMNO=" + myfunc.AA(Tmp_TMNO)
                               + "   AND       (TMNO,ITM)  IN  ( SELECT    TMNO,MAX(ITM)  "
                                                                                   +" FROM     AMM_TMDWGD  "
                                                                                   +"  WHERE  TMNO=" + myfunc.AA(Tmp_TMNO)
                                                                                   + " group by  TMNO) ";
                cmd.CommandText = Tmp_Sql;
                cmd.ExecuteNonQuery();
                response.StatusCode = HttpStatusCode.OK;
                Tmp_RtnMsg = "條碼編號(" + Tmp_TMNO + ")<br>"
                                         + "[續借登記]成功 !!  <br>";
                response.Content = new StringContent("{'success': true,'Rtn_Msg':'" + Tmp_RtnMsg + "'}");    // 回應內容

                return response;
                //excuteSQLTran
            }  //try
            catch (Exception e)
            {
                string Tmp_msg;
                Tmp_msg = myfunc.Get1ORA(e.Message);
                Tmp_RtnMsg = "借閱登記失敗 !!  <br>"
                                         + Tmp_msg;
                response.Content = new StringContent("{'success': false,'Rtn_Msg':'" + Tmp_RtnMsg + "'}");    // 回應內容
                return response;
            }
            finally
            {
                conn.Close();
            }
        }


3>V120202D -getUrlStr - 傳回ds  -
{ //加入資料
xtype: "button", text: "加入資料", width: 120, border: 2, margin: { left: 10, },
hidden: true,
id: "sub_btn_Add",
handler: function () {
console.log("insider handler of sub_btn_Add");
var Tmp_APNO = Ext.getCmp("sub_APNO").getValue();
var Tmp_Str = "";
if (checkisnull(Tmp_APNO)) {
Tmp_Str = "請先輸入[申請單號] !!"
mywarnalert(Tmp_Str);
return;
}
var np = {};
np["sub_APNO"] = Tmp_APNO;
var Tmp_url = "../../api/V120202DAPI/get_sub_data1";

//取得挑選資料的 dt2JSON 字串 
//getUrlStr : 必需傳回字串( dt.JSON字串) , 非 ds
var rtn_Str = getUrlStr(Tmp_url, np, "加入資料");

console.log("rtn_Str:", rtn_Str);

if (checkRtnOK(rtn_Str)) {
var Tmp_recs = Ext.decode(rtn_Str);
var Tmp_rec;
for (i = 0; i < Tmp_recs.length; i++) {
Tmp_rec = Tmp_recs[0];
console.log("Tmp_rec:", Tmp_rec);
if (Ext.getCmp("sub_Grid").store.find("APNO", Tmp_rec["APNO"]) == -1) {
console.log("add store Tmp_rec:", Tmp_rec);
Ext.getCmp("sub_Grid").store.add(Tmp_rec);
Ext.getCmp("sub_APNO").setValue("");
}
} //end of for
console.log("store :", Ext.getCmp("sub_Grid").store);
} // end of if (checkRtnOK(rtn_Str)) {
} // end of handler
}, // end of 加入資料

//開啟畫面
var win1 = getMyWindow("領料登記", sub_V120202D_Flds, sub_V120202D_Btns, "D");
    win1.x = 100;
    win1.setWidth(500);
    win1.setHeight(400);
    var np = {};
    //np["sub_APNO"] = Ext.getCmp("sub_APNO").getValue();
    var Tmp_url = "../../api/V120202DAPI/get_sub_data";  //
    Ext.getCmp("sub_Grid").store.getProxy().url = Tmp_url;
    Ext.getCmp("sub_Grid").store.getProxy().extraParams = np; //分頁OK,篩選條件OK    
    Ext.getCmp("sub_Grid").store.load();
    win1.show();

登入使用者, 登入部門 , 1>c# User.Identity.Name 2>js loginInfo.depId - Login - EMPLYID

 1>*.cs  c#   -->  login 使用者id  , User.Identity.Name

using TLSWEB_AMM.Models;

//記錄系統所有登入使用者的 id  : User.Identity.Name

//舊寫法 : LoginUserModel.LoginUserId 

string Tmp_Sql = "  SELECT DEPID "
                           + " FROM HR_EMPLYM "
                           + " WHERE EMPLYID='" +  User.Identity.Name+ "')";
string n = funId + "_EMPID";
DataSet ds = setupPickDs(n, Tmp_Sql, new string[] { "AMM_UPHDAY" });



2>*. js   tlsbase.js --> loginInfo.depId != '856'  ,    loginInfo.id

       Ext.Loader.loadScript({    url: '../Scripts/tlsbase.js'  });

        np["ASPNO"] = "ASP" + DatetoStr(now, "Ymd");
        var Tmp_cur_DT = DatetoStr(now, "Y/m/d");  //呼叫 myfunc.js DatetoStr();
        
        var Tmp_MKER = loginInfo.id;
        var Tmp_MKNM = loginInfo.name;
        var Tmp_MKDT = DatetoStr(now, "Y/m/d");  
        Ext.getCmp("MKER").setValue(Tmp_MKER);
        Ext.getCmp("MKDT").setValue(Tmp_MKDT);

ps: loginInfo Object:
                id = stringArray[0],
                name = stringArray[1],
                usgid = usGid,
                email = stringArray[2],
                depId = stringArray[3],
                depName = stringArray[4],
                depMgr = stringArray[5],

if (loginInfo.depId != '856') 
   var Tmp_Sql = " SELECT  DEP ,LDMAN    "
                          + "  FROM   AMM_FACDEP  "
                          + " WHERE  EMPLYID=" + AA(loginInfo.id)
                          + "  AND       rownum=1 ";
        var Tmp_Str = SqlValue(Tmp_Sql);

2022年8月5日 星期五

V120103 – 匯入 – 匯入結果以 Cookie 傳回 - HttpCookie 用法說明

目的: 如何匯入檔案 且  傳回匯入結果

處理說明 : 1>如何匯入檔案
                   2>如何傳回匯入結果 



0>[挑選檔案]元件 & 匯入子畫面 
//[匯入]子畫面
var J_formFields_Sub_In = [
{
xtype: 'filefield',
id: 'sub_FName',
name: 'sub_FName',
fieldLabel: '檔案名稱',
labelWidth: 60,
msgTarget: 'side',
allowBlank: false,
flex: 1,
anchor: '100%',
buttonText: '選擇檔案',
listeners: {
'change': function (fb, v) {
var fileName = getFileName(v.replace(/C:\\fakepath\\/g, ''));
Ext.getDom(fb.inputId).value = fileName;
//Ext.getDom(fb.inputId).value = v;
}
}
},
];

  //[匯入]按鈕處理
    function xlsInBtn_click() {
        console.log(" 2 inside  xlsInBtn_click() ");
        var mySubForm = Ext.create('Ext.form.FormPanel', {
            autoScroll: true,
            fieldDefaults: {
                labelAlign: 'right',
            },
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            id: "mySubForm_2",
            form_id: "mySubForm_2",
            items: J_formFields_Sub_In,
            buttons: [
                {
                    text: "確定匯入", id: "mySubForm_2_btnok", handler: function () {
                        mySubForm_2_btnokClick();
                        //this.up("window").close();
                        //this.up("window").destroy();
                        //Ext.getCmp('btn_Show').fireHandler();                
                    }
                },
                {
                    text: "取消", id: "mySubForm_2_btncancel", handler: function () {
                        var Tmp_win = this.up("window");
                        if (Tmp_win == undefined) {
                            Ext.Msg.alert("關閉時未取到Window Object");
                        }
                        this.up("window").close();
                        this.up("window").destroy();
                    }
                }
            ]
        }
        );
        var win = getEditWindow_my("匯入", mySubForm, 1);
        win.width = 600;
        win.height = 100;
        win.show();
    };


1>匯入檔案: *.js
    //[確認匯入]鈕 , 處理
    function mySubForm_2_btnokClick() {
        //取得 [檔案上傳].檔名
        var btn_FileIn_Obj = Ext.getCmp('sub_FName');
        var Tmp_Str = "";
        var np = {
            FName: Ext.getDom(btn_FileIn_Obj.inputId).value
        };
        console.log("FName: ", np.FName);
        //submit會將fileUploadForm裡面input name送到後端    
        Ext.getCmp('mySubForm_2_btnok').up("form").submit({
            //standardSubmit: false,    //default:false
            url: '../api/V120103API/uploadFileToDB',
            method: 'POST',
            async: false,
            headers: { 'Content-type': 'multipart/form-data' },
            params: np,
})


2>*.cs
//[匯入] 鈕 , 匯入 XLS 檔案
        [HttpPost]
        //public HttpResponseMessage uploadFileToDB()
        public void uploadFileToDB()
        {

            HttpContext c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            //匯入檔案名稱(含 *.xlsx)
            string FName = nvc["FName"];
            string FName0 =Path.GetFileNameWithoutExtension(FName) ;  //不含 extension
            string Tmp_FName = FName;
            Workbook wk = null;

            HttpRequest Request = HttpContext.Current.Request;
            var response = this.Request.CreateResponse();
            string file_Name = FName;
            string FILEDT = DateTime.Now.ToString("yyyy-MM-dd");
            string Tmp_RtnMsg = "";
            string Tmp_Rtn_JSON = "";   //Tmp_Rtn_JSON = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
            string Tmp_Sql = "", Tmp_Str = "";
            int Tmp_CNT = 0;
            MemoryStream stream = new MemoryStream();
            HttpCookie MyCookie = new HttpCookie("Rtn_Msg");
            foreach (string cur_FName in Request.Files)
            {
                string fileType = Request.Files[cur_FName].ContentType;
                Stream file_Strm = Request.Files[cur_FName].InputStream;
                file_Name = Path.GetFileName(Request.Files[cur_FName].FileName);                
                int fileSize = Request.Files[cur_FName].ContentLength;
                byte[] fileRcrd = new byte[fileSize];
                //更新資料庫欄位值                
                int Tmp_curpos = 0;                
                bool Tmp_isOK = true;
                try
                {

                    wk = new Workbook();
                    wk.LoadFromStream(file_Strm);
                    Worksheet sheet1 = wk.Worksheets[0];//獲取第一個工作表
                                                        //共 10 欄
                                                        //string[] outFieldArray = { "計畫代碼", "父件件號", "件號", "件號中文名稱", "每機用量", "BOM量", "計量單位", "工廠", "類別","備註" };
                                                        //int RowsCount = sheet1.Rows.Count();
                    int RowsCount = sheet1.LastRow;
                    string Tmp_CLS,Tmp_ITM,  Tmp_DITM, Tmp_NM, Tmp_REPN, Tmp_RESN, Tmp_INPN, Tmp_INSN, Tmp_RMK;
                    string Tmp_PLNC, Tmp_REWK, Tmp_INSC, Tmp_STLCT, Tmp_NOTE, Tmp_FACWC;
                    string Tmp_RESULT;                    

                    //STEP1 檢核  XLS 欄位名稱資料是否正確                                            
                    //類別 排序項次 名稱 拆移件號 拆移序號 安裝件號 安裝序號 備考
                    // 拆移PlanningCard 修理REWORK 安裝InstallationCard 儲位 備註 拆移工廠
                    Tmp_CLS = sheet1.Range[myfunc.GetExcelPos(0, 0)].Value;                    
                    Tmp_DITM = sheet1.Range[myfunc.GetExcelPos(1, 0)].Value;
                    Tmp_NM = sheet1.Range[myfunc.GetExcelPos(2, 0)].Value;
                    Tmp_REPN = sheet1.Range[myfunc.GetExcelPos(3, 0)].Value;
                    Tmp_RESN = sheet1.Range[myfunc.GetExcelPos(4, 0)].Value;
                    Tmp_INPN = sheet1.Range[myfunc.GetExcelPos(5, 0)].Value;
                    Tmp_INSN = sheet1.Range[myfunc.GetExcelPos(6, 0)].Value;
                    Tmp_RMK = sheet1.Range[myfunc.GetExcelPos(7, 0)].Value;
                    // string Tmp_PLNC, Tmp_REWK, Tmp_INSC, Tmp_STLCT, Tmp_NOTE, Tmp_FACWC;
                    Tmp_PLNC = sheet1.Range[myfunc.GetExcelPos(8, 0)].Value;
                    Tmp_REWK = sheet1.Range[myfunc.GetExcelPos(9, 0)].Value;
                    Tmp_INSC = sheet1.Range[myfunc.GetExcelPos(10, 0)].Value;
                    Tmp_STLCT = sheet1.Range[myfunc.GetExcelPos(11, 0)].Value;
                    Tmp_NOTE = sheet1.Range[myfunc.GetExcelPos(12, 0)].Value;
                    Tmp_FACWC = sheet1.Range[myfunc.GetExcelPos(13, 0)].Value;
                    //新增[結果說明]欄位
                    Tmp_RESULT = "結果說明";
                    sheet1.Range[myfunc.GetExcelPos(14, 0)].Value=Tmp_RESULT;

                    //xls 欄位名稱有問題                    
                    //類別 排序項次 名稱 拆移件號 拆移序號 安裝件號 安裝序號 備考
                    // 拆移PlanningCard 修理REWORK 安裝InstallationCard 儲位 備註 拆移工廠
                    Tmp_RtnMsg = "匯入檔案欄位名稱必需如下:<br>";                     
                    if ((Tmp_CLS != "類別") || (Tmp_DITM != "排序項次") || (Tmp_NM != "名稱") || (Tmp_REPN != "拆移件號") || (Tmp_RESN != "拆移序號") ||
                          (Tmp_INPN != "安裝件號") || (Tmp_INSN != "安裝序號") || (!Tmp_RMK.Contains("備考")) ||
                          (Tmp_PLNC != "拆移PlanningCard") || (Tmp_REWK != "修理REWORK") || (Tmp_INSC != "安裝InstallationCard") || 
                          (Tmp_STLCT != "儲位") || (Tmp_NOTE != "備註") || (Tmp_FACWC != "拆移工場")
                          )
                    {
                        Tmp_RtnMsg = "匯入檔案欄位名稱必需如下:<br>"
                                                 +"'類別','排序項次','名稱','拆移件號','拆移序號',<br>"
                                                 +"'安裝件號','安裝序號','備考','拆移PlanningCard','修理REWORK',<br>"
                                                 +"'安裝InstallationCard','儲位','備註','拆移工場'<br>"
                                                 +"敬請檢核";
                        //Tmp_Rtn_JSON = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
                        //response.Content = new StringContent(Tmp_Str);    // 回應內容
                        //return response;
                        //Tmp_Str = "已匯出完成!!  (" + Tmp_Cnt.ToString() + "筆) <br>"
                        //   + "檔案名稱(" + Tmp_FName + ")";
                        // 傳回結果字串      
                        MyCookie.Value=  HttpUtility.UrlEncode(Tmp_RtnMsg);
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return ;
                    };

                    int Tmp_index;
                    Tmp_isOK = true;
                    //STEP2 檢核資料
                    for (int i = 0; i < RowsCount; i++)
                    {
                        Tmp_curpos = i + 1;
                        //if (Tmp_curpos == 290)
                        //{
                        //    Tmp_Str = " 第 290筆資料";
                        //};          
                        Tmp_RESULT = "";
                        Tmp_CLS = sheet1.Range[myfunc.GetExcelPos(0, i + 1)].Value;
                        if (myfunc.checkisnull(Tmp_CLS))
                        { break; }
                        Tmp_DITM = sheet1.Range[myfunc.GetExcelPos(1, i + 1)].Value;
                        Tmp_REPN = sheet1.Range[myfunc.GetExcelPos(3, i + 1)].Value;
                        Tmp_RMK = sheet1.Range[myfunc.GetExcelPos(7, i + 1)].Value;
                        if (Tmp_DITM.Length == 0)
                        { Tmp_RESULT = Tmp_RESULT + "排序項次不可空白,"; Tmp_isOK = false; }
                        if (Tmp_REPN.Length == 0)
                        { Tmp_RESULT = Tmp_RESULT + "拆移件號不可空白,"; Tmp_isOK = false; }
                    if ((Tmp_RMK!= "A") && (Tmp_RMK != "B") && (Tmp_RMK != "C") && (Tmp_RMK != "D") && (Tmp_RMK != "E") && (Tmp_RMK != "F"))
                        { Tmp_RESULT = Tmp_RESULT + "備考欄位值必需在 A~F 之間"; Tmp_isOK = false; }                        
                        if (Tmp_RESULT.Length > 0)
                            sheet1.Range[myfunc.GetExcelPos(14, i + 1)].Value = Tmp_RESULT;                            
                        else
                            sheet1.Range[myfunc.GetExcelPos(14, i + 1)].Value = "check ok";
                    }  // for i=0.. 檢查資料                    
                    
                    

                    //若資料不正確,則不寫入資料庫,只傳回檔案
                    if (Tmp_isOK == false)
                    {
                        Tmp_Str = "匯入檔案欄位值需修正!!<br>"
                                    + "請檢核如下檔案名稱(" + Tmp_FName + ")<br>";
                                    
                        MyCookie.Value = HttpUtility.UrlEncode(Tmp_Str);
                        // 若匯入資料有問題, 則不寫入資料庫 , 傳回結果檔案(*_結果.xlsx)
                        Tmp_FName = FName0 + "_結果.xlsx";
                        wk.SaveToStream(stream, FileFormat.Version2007);
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return;
                    }

                    //STEP3 寫入資料庫

                    for (int i = 0; i < RowsCount; i++)
                    {
                        Tmp_curpos = i + 1;
                        //if (Tmp_curpos == 290)
                        //{
                        //    Tmp_Str = " 第 290筆資料";
                        //};                        
                        Tmp_CLS = sheet1.Range[myfunc.GetExcelPos(0, i + 1)].Value;
                        if (myfunc.checkisnull(Tmp_CLS))
                        { break; }
                        Tmp_DITM = sheet1.Range[myfunc.GetExcelPos(1, i + 1)].Value;
                        Tmp_NM = sheet1.Range[myfunc.GetExcelPos(2, i + 1)].Value;
                        Tmp_REPN = sheet1.Range[myfunc.GetExcelPos(3, i + 1)].Value;
                        Tmp_RESN = sheet1.Range[myfunc.GetExcelPos(4, i + 1)].Value;
                        Tmp_INPN = sheet1.Range[myfunc.GetExcelPos(5, i + 1)].Value;                        
                        Tmp_INSN = sheet1.Range[myfunc.GetExcelPos(6, i + 1)].Value;
                        //"'類別','排序項次','名稱','拆移件號','拆移序號','安裝件號','安裝序號','備考','拆移PlanningCard','修理REWORK','安裝InstallationCard','儲位','備註','拆移工廠'<br>"
                        Tmp_RMK = sheet1.Range[myfunc.GetExcelPos(7, i + 1)].Value;
                        Tmp_PLNC = sheet1.Range[myfunc.GetExcelPos(8, i + 1)].Value;
                        Tmp_REWK = sheet1.Range[myfunc.GetExcelPos(9, i+1)].Value;
                        Tmp_INSC = sheet1.Range[myfunc.GetExcelPos(10, i + 1)].Value;
                        Tmp_STLCT = sheet1.Range[myfunc.GetExcelPos(11, i + 1)].Value;
                        Tmp_NOTE = sheet1.Range[myfunc.GetExcelPos(12, i + 1)].Value;
                        Tmp_FACWC = sheet1.Range[myfunc.GetExcelPos(13, i + 1)].Value;

                        Tmp_Sql = " SELECT COUNT(*) "
                                        +"  FROM   AMM_FRO3F16STD "
                                       + "  WHERE  CLS=" + myfunc.AA(Tmp_CLS)
                                       +"  AND        DITM=" + myfunc.AA(Tmp_DITM);
                        Tmp_CNT=int.Parse(myfunc.SqlValue(Tmp_Sql).ToString());
                        if (Tmp_CNT==0)
                        {        
                            Tmp_ITM = GET_MAX_ITM(Tmp_CLS).ToString();
                            Tmp_Sql = " INSERT  INTO  AMM_FRO3F16STD "
                                        + "  (CLS,ITM,DITM,NM,REPN,RESN,INPN,INSN,RMK,PLNC,REWK,INSC,STLCT,NOTE,FACWC) "
                                        + "  VALUES "
                                        + "("
                                        + myfunc.AA(Tmp_CLS) + ","
                                        + myfunc.AA(Tmp_ITM) + ","
                                        + myfunc.AA(Tmp_DITM) + ","
                                        + myfunc.AA(Tmp_NM) + ","
                                        + myfunc.AA(Tmp_REPN) + ","
                                        + myfunc.AA(Tmp_RESN) + ","
                                        + myfunc.AA(Tmp_INPN) + ","
                                        + myfunc.AA(Tmp_INSN) + ","
                                        + myfunc.AA(Tmp_RMK) + ","
                                        + myfunc.AA(Tmp_PLNC) + ","
                                        + myfunc.AA(Tmp_REWK) + ","
                                        + myfunc.AA(Tmp_INSC) + ","
                                        + myfunc.AA(Tmp_STLCT) + ","
                                        + myfunc.AA(Tmp_NOTE) + ","
                                        + myfunc.AA(Tmp_FACWC) 
                                        + ") ";
                            myfunc.SqlExec(Tmp_Sql);
                            sheet1.Range[myfunc.GetExcelPos(14, i + 1)].Value = "新增 OK!!";
                        }
                        else
                        {
                            Tmp_Sql = " UPDATE  AMM_FRO3F16STD "
                                        + "  SET    NM="+ myfunc.AA(Tmp_NM) + ","
                                                  + "   REPN=" + myfunc.AA(Tmp_REPN) + ","
                                                  + "   RESN=" + myfunc.AA(Tmp_RESN) + ","
                                                  + "   INPN=" + myfunc.AA(Tmp_INPN) + ","
                                                  + "   INSN=" + myfunc.AA(Tmp_INSN) + ","
                                                  + "   RMK=" + myfunc.AA(Tmp_RMK) + ","
                                                  + "   PLNC=" + myfunc.AA(Tmp_PLNC) + ","
                                                  + "   REWK=" + myfunc.AA(Tmp_REWK) + ","
                                                  + "   INSC=" + myfunc.AA(Tmp_INSC) + ","
                                                  + "   STLCT=" + myfunc.AA(Tmp_STLCT) + ","
                                                  + "   NOTE=" + myfunc.AA(Tmp_NOTE) + ","
                                                  + "   FACWC=" + myfunc.AA(Tmp_FACWC)                                         
                                        + "  WHERE  CLS=" + myfunc.AA(Tmp_CLS)
                                        + "  AND       DITM=" + myfunc.AA(Tmp_DITM);
                            myfunc.SqlExec(Tmp_Sql);
                            sheet1.Range[myfunc.GetExcelPos(14, i + 1)].Value = "更新 OK!!";
                        }                        
                    };  //end of for i= , 寫入資料庫
                    Tmp_Str = "匯入成功!!";
                    MyCookie.Value = HttpUtility.UrlEncode(Tmp_Str);                    
                    Tmp_FName = FName0 + "_結果.xlsx";
                    wk.SaveToStream(stream, FileFormat.Version2007);
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                    HttpContext.Current.Response.Cookies.Add(MyCookie);
                    HttpContext.Current.Response.End();                    
                    //Tmp_Str = "{success: true,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
                    //response.Content = new StringContent(Tmp_Str);    // 回應內容
                    //return response;
                }// try
                catch (Exception e)
                {                                                                                          //失敗
                    Tmp_Str = "批次匯入失敗!!<br>"
                                             + "第" + Tmp_curpos.ToString() + "筆資料<br>"                                             
                                             + e.Message + "<br>"
                                             +Tmp_Sql+"<br>";
                    MyCookie.Value = HttpUtility.UrlEncode(Tmp_Str);
                    HttpContext.Current.Response.Cookies.Add(MyCookie);
                    HttpContext.Current.Response.End();
                    //+ Tmp_Sql ;
                    //Tmp_Str = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) +",Tmp_Sql:"+ myfunc.AA(Tmp_Sql) +"}";
                    //Tmp_Str = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
                    //response.Content = new StringContent(Tmp_Str);    // 回應內容                    
                    //return response;
                }
            }  //end of foreach (string cur_FName in Request.Files)            
            return;
        }  //  end of  uploadFileToDB()