Esempio n. 1
0
        /// <summary>
        /// 覆核
        /// </summary>
        /// <param name="RegisterNo"></param>
        /// <param name="ViewModel"></param>
        /// <param name="SearchData"></param>
        /// <returns></returns>
        public MSGReturnModel <List <SpecifiedTimeTreasuryApprSearchDetailViewModel> > ApproveData(List <string> RegisterNo, List <SpecifiedTimeTreasuryApprSearchDetailViewModel> ViewModel, SpecifiedTimeTreasuryApprSearchViewModel SearchData)
        {
            var result = new MSGReturnModel <List <SpecifiedTimeTreasuryApprSearchDetailViewModel> >();

            result.RETURN_FLAG = false;
            result.DESCRIPTION = Ref.MessageType.not_Find_Any.GetDescription();

            if (!ViewModel.Any())
            {
                return(result);
            }

            DateTime dt      = DateTime.Now;
            string   logStrC = string.Empty; //combin Log

            List <TREA_OPEN_REC> TORs = new List <TREA_OPEN_REC>();

            using (TreasuryDBEntities db = new TreasuryDBEntities())
            {
                var _TREA_ITEM = db.TREA_ITEM.Where(x => x.ITEM_OP_TYPE == "3").Select(x => x.ITEM_ID).ToList();

                foreach (var item in ViewModel.Where(x => RegisterNo.Contains(x.vTREA_REGISTER_ID)))
                {
                    var _TREA_OPEN_REC = db.TREA_OPEN_REC.FirstOrDefault(x => x.TREA_REGISTER_ID == item.vTREA_REGISTER_ID);
                    if (_TREA_OPEN_REC == null) //找不到該單號
                    {
                        result.DESCRIPTION = Ref.MessageType.not_Find_Any.GetDescription(null, $"單號:{item.vTREA_REGISTER_ID}");
                        return(result);
                    }
                    if (_TREA_OPEN_REC.LAST_UPDATE_DT > item.vLAST_UPDATE_DT) //資料已備更新
                    {
                        result.DESCRIPTION = Ref.MessageType.already_Change.GetDescription(null, $"單號:{item.vTREA_REGISTER_ID}");
                        return(result);
                    }
                    TORs.Add(_TREA_OPEN_REC);
                    var    applyStatus = ((int)Ref.ApplyStatus._2).ToString(); // 狀態: 覆核完成
                    string logStrB     = string.Empty;                         //修改前 Log
                    string logStrA     = string.Empty;                         //修改後 Log

                    logStrB += _TREA_OPEN_REC.modelToString(logStrB);

                    _TREA_OPEN_REC.APPR_STATUS     = applyStatus;
                    _TREA_OPEN_REC.LAST_UPDATE_UID = SearchData.vCreateUid;
                    _TREA_OPEN_REC.LAST_UPDATE_DT  = dt;
                    _TREA_OPEN_REC.APPR_UID        = SearchData.vCreateUid;
                    _TREA_OPEN_REC.APPR_DT         = dt;

                    logStrA += _TREA_OPEN_REC.modelToString(logStrA);

                    //#region 申請單紀錄檔
                    ////取得流水號
                    //List<string> workList = _TREA_OPEN_REC.OPEN_TREA_REASON.Split(';').ToList();
                    //foreach (var workItem in workList)
                    //{
                    //    if (!_TREA_ITEM.Contains(workItem))
                    //    {
                    //        SysSeqDao sysSeqDao = new SysSeqDao();
                    //        string qPreCode = DateUtil.getCurChtDateTime().Split(' ')[0];
                    //        var cId = sysSeqDao.qrySeqNo("G6", qPreCode).ToString().PadLeft(3, '0');

                    //        var _TREA_APLY_REC = db.TREA_APLY_REC
                    //            .Add(new TREA_APLY_REC()
                    //            {
                    //                APLY_NO = $@"G6{qPreCode}{cId}", ////申請單號 G6+系統日期YYYMMDD(民國年)+3碼流水號
                    //                APLY_FROM = "S",
                    //                TREA_REGISTER_ID = item.vTREA_REGISTER_ID,
                    //                ITEM_ID = workItem,
                    //                APLY_STATUS = "C01",
                    //                EXPECTED_ACCESS_DATE = _TREA_OPEN_REC.OPEN_TREA_DATE,
                    //                APLY_UNIT = _TREA_OPEN_REC.CREATE_UNIT,
                    //                APLY_UID = _TREA_OPEN_REC.CREATE_UID,
                    //                APLY_DT = _TREA_OPEN_REC.CREATE_DT,
                    //                APLY_APPR_UID = SearchData.vCreateUid,
                    //                APLY_APPR_DT = dt,
                    //                CREATE_UID = SearchData.vCreateUid,
                    //                CREATE_DT = dt,
                    //                LAST_UPDATE_UID = SearchData.vCreateUid,
                    //                LAST_UPDATE_DT = dt,
                    //                CREATE_UNIT = SearchData.vCreateUnit
                    //            });
                    //        logStrA += _TREA_APLY_REC.modelToString(logStrA);
                    //    }
                    //}
                    //#endregion

                    #region 申請單暫存檔
                    //取得流水號
                    List <string> workList = _TREA_OPEN_REC.OPEN_TREA_REASON.Split(';').ToList();
                    if (workList.Count != 0)
                    {
                        var data = (from n in db.TREA_APLY_TEMP select n);
                        db.TREA_APLY_TEMP.RemoveRange(data);
                    }
                    foreach (var workItem in workList)
                    {
                        if (!_TREA_ITEM.Contains(workItem))
                        {
                            var _TREA_APLY_TEMP = db.TREA_APLY_TEMP
                                                  .Add(new TREA_APLY_TEMP()
                            {
                                ITEM_ID = workItem,
                            });
                        }
                    }
                    #endregion

                    logStrC += string.Format("修改前{0}^^修改後{1}", logStrB, logStrA);
                }
                var validateMessage = db.GetValidationErrors().getValidateString();
                if (validateMessage.Any())
                {
                    result.DESCRIPTION = validateMessage;
                }
                else
                {
                    try
                    {
                        db.SaveChanges();

                        #region 寄信
                        //List<Tuple<string, string>> _mailTo = new List<Tuple<string, string>>() { new Tuple<string, string>("*****@*****.**", "測試帳號-glsisys") };
                        List <Tuple <string, string> > _mailTo = new List <Tuple <string, string> >();
                        List <Tuple <string, string> > _ccTo   = new List <Tuple <string, string> >();
                        var emps            = GetEmps();
                        var _MAIL_CONTENT   = db.MAIL_CONTENT.AsNoTracking().FirstOrDefault(x => x.MAIL_CONTENT_ID == "01" && x.IS_DISABLED == "N");
                        var _MAIL_RECEIVE   = db.MAIL_RECEIVE.AsNoTracking();
                        var _CODE_ROLE_FUNC = db.CODE_ROLE_FUNC.AsNoTracking();
                        var _CODE_USER_ROLE = db.CODE_USER_ROLE.AsEnumerable();
                        var _CODE_USER      = db.CODE_USER.AsNoTracking();
                        foreach (var TOR in TORs)
                        {
                            if (_MAIL_CONTENT != null)
                            {
                                string _content = _MAIL_CONTENT.MAIL_CONTENT1;
                                _content = _content.Replace("@_TREA_OPEN_TIME_", TOR.OPEN_TREA_TIME);
                                _content = _content.Replace("@_EXEC_TIME_E_", TOR.EXEC_TIME_E);
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine(_content);
                                //                            sb.AppendLine(
                                //        $@"您好,
                                //通知今日金庫開關庫時間為:{TOR.OPEN_TREA_TIME},請準時至金庫門口集合。
                                //為配合金庫大門之啟閉,請有權人在:{TOR.EXEC_TIME_E} 前進入「金庫進出管理系統」完成入庫確認作業,謝謝。
                                //");
                                var           _FuncId     = _MAIL_RECEIVE.Where(x => x.MAIL_CONTENT_ID == _MAIL_CONTENT.MAIL_CONTENT_ID).Select(x => x.FUNC_ID);
                                var           _RoleId     = _CODE_ROLE_FUNC.Where(x => _FuncId.Contains(x.FUNC_ID)).Select(x => x.ROLE_ID);
                                var           _UserId     = _CODE_USER_ROLE.Where(x => _RoleId.Contains(x.ROLE_ID)).Select(x => x.USER_ID).Distinct();
                                List <string> _userIdList = new List <string>();

                                _userIdList.AddRange(_CODE_USER.Where(x => _UserId.Contains(x.USER_ID) && x.IS_MAIL == "Y").Select(x => x.USER_ID).ToList());
                                if (_userIdList.Any())
                                {
                                    //人名 EMAIl
                                    var _EMP = emps.Where(x => _userIdList.Contains(x.USR_ID)).ToList();
                                    if (_EMP.Any())
                                    {
                                        _EMP.ForEach(x => {
                                            _mailTo.Add(new Tuple <string, string>(x.EMAIL, x.EMP_NAME));
                                        });
                                    }
                                }

                                try
                                {
                                    var sms = new SendMail.SendMailSelf();
                                    sms.smtpPort    = 25;
                                    sms.smtpServer  = Properties.Settings.Default["smtpServer"]?.ToString();
                                    sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString();
                                    sms.mailPwd     = Properties.Settings.Default["mailPwd"]?.ToString();
                                    sms.Mail_Send(
                                        new Tuple <string, string>(sms.mailAccount, "金庫管理系統"),
                                        _mailTo,
                                        _ccTo,
                                        _MAIL_CONTENT?.MAIL_SUBJECT ?? "入庫人員確認作業通知",
                                        sb.ToString()
                                        );
                                }
                                catch (Exception ex)
                                {
                                    result.DESCRIPTION = $"Email 發送失敗請人工通知。";
                                }
                            }
                        }
                        #endregion

                        #region LOG
                        //新增LOG
                        Log log = new Log();
                        log.CFUNCTION = "覆核-指定開庫覆核作業";
                        log.CACTION   = "U";
                        log.CCONTENT  = logStrC;
                        LogDao.Insert(log, SearchData.vCreateUid);
                        #endregion

                        result.RETURN_FLAG = true;
                        result.DESCRIPTION = $"申請單號 : {string.Join(",", RegisterNo)} 覆核成功";
                        result.Datas       = GetApprSearchData(SearchData);
                    }
                    catch (Exception ex)
                    {
                        result.DESCRIPTION = ex.exceptionMessage();
                    }
                }
            }
            return(result);
        }
Esempio n. 2
0
        public void Routine(TreasuryDBEntities db, string dateTime, DateTime _dtn, string MAIL_TIME_ID)
        {
            var       _split     = dateTime.Split(':');
            var       hh         = _split[0];
            var       mm         = _split.Length > 1 ? _split[1] : string.Empty;
            var       dt         = new DateTime(_dtn.Year, _dtn.Month, _dtn.Day, Convert.ToInt32(hh), Convert.ToInt32(mm), 0);
            SysSeqDao sysSeqDao  = new SysSeqDao();
            String    qPreCode   = DateUtil.getCurChtDateTime().Split(' ')[0];
            var       _Mail_Time = db.MAIL_TIME.ToList()
                                   .FirstOrDefault(x =>
                                                   x.MAIL_TIME_ID == MAIL_TIME_ID &&
                                                   x.SEND_TIME != null &&
                                                   x.SEND_TIME == dateTime &&
                                                   x.IS_DISABLED != "Y" &&
                                                   x.SCHEDULER_UPDATE_DT == _dtn);

            if (_Mail_Time != null)
            {
                string errorMsg = string.Empty;

                var MailTId      = sysSeqDao.qrySeqNo("MailT", qPreCode).ToString().PadLeft(3, '0');
                var _JOB_ITEM_ID = $@"{qPreCode}W{MailTId}";
                try
                {
                    #region 新增排程工作紀錄檔
                    Extension.NlogSet($"新增排程工作紀錄檔");
                    db.SYS_JOB_REC.Add(new SYS_JOB_REC()
                    {
                        JOB_ITEM_ID = _JOB_ITEM_ID,
                        JOB_ID      = _Mail_Time.MAIL_TIME_ID,
                        CREATE_TIME = dt,
                        STATUS      = "2",
                        START_TIME  = _dtn,
                    });

                    var test = db.GetValidationErrors().getValidateString();
                    if (!test.IsNullOrWhiteSpace())
                    {
                        Extension.NlogSet($"{test}");
                    }
                    db.SaveChanges();
                    #endregion

                    #region 新增 開庫紀錄檔
                    Extension.NlogSet($"新增開庫紀錄檔");
                    db.TREA_OPEN_REC.RemoveRange(
                        db.TREA_OPEN_REC.Where(x =>
                                               x.OPEN_TREA_TYPE == "1" &&
                                               x.OPEN_TYPE == "Y" &&
                                               x.REGI_STATUS == "C02"));

                    var _TORId = sysSeqDao.qrySeqNo("W", qPreCode).ToString().PadLeft(2, '0');
                    var _TOR   = new TREA_OPEN_REC()
                    {
                        TREA_REGISTER_ID = $"W{qPreCode}{_TORId}",    //開庫工作單號(金庫登記簿單號)
                        OPEN_TREA_TYPE   = "1",                       //開庫類型
                        OPEN_TREA_REASON = "例行性開庫",                   //開庫原因
                        OPEN_TREA_TIME   = _Mail_Time.TREA_OPEN_TIME, //開庫時間
                        EXEC_TIME_B      = _Mail_Time.EXEC_TIME_B,    //系統區間(起)
                        EXEC_TIME_E      = _Mail_Time.EXEC_TIME_E,    //系統區間(迄)
                        OPEN_TREA_DATE   = _dtn,
                        APPR_STATUS      = "2",
                        REGI_STATUS      = "C02",
                        CREATE_DT        = _dtn,
                        OPEN_TYPE        = "Y" //Y為例行性
                    };
                    db.TREA_OPEN_REC.Add(_TOR);

                    #endregion

                    #region 取得例行出入庫作業項目

                    #region 自【金庫存取作業設定檔】查詢例行出入庫作業項目
                    Extension.NlogSet($"自【金庫存取作業設定檔】查詢例行出入庫作業項目");
                    var _Trea_Item = db.TREA_ITEM.AsNoTracking()
                                     .Where(x =>
                                            x.DAILY_FLAG == "Y" &&
                                            x.IS_DISABLED == "N").ToList();
                    #endregion

                    #region 清空【申請單紀錄暫存檔】
                    Extension.NlogSet($" 清空【申請單紀錄暫存檔】");
                    db.TREA_APLY_TEMP.RemoveRange(db.TREA_APLY_TEMP);
                    #endregion

                    var _MAIL_CONTENT = db.MAIL_CONTENT.AsNoTracking()
                                        .First(x => x.MAIL_CONTENT_ID == _Mail_Time.MAIL_CONTENT_ID);
                    var           _MAIL_RECEIVE   = db.MAIL_RECEIVE.AsNoTracking();
                    var           _CODE_ROLE_FUNC = db.CODE_ROLE_FUNC.AsNoTracking();
                    var           _CODE_USER_ROLE = db.CODE_USER_ROLE.AsEnumerable();
                    var           _CODE_USER      = db.CODE_USER.AsNoTracking();
                    List <string> _userIdList     = new List <string>();
                    var           emps            = GetEmps();
                    //List<Tuple<string, string>> _mailTo = new List<Tuple<string, string>>() { new Tuple<string, string>("*****@*****.**", "測試帳號-glsisys") };
                    List <Tuple <string, string> > _mailTo = new List <Tuple <string, string> >();
                    List <Tuple <string, string> > _ccTo   = new List <Tuple <string, string> >();

                    var _FuncId = _MAIL_RECEIVE.Where(x => x.MAIL_CONTENT_ID == _MAIL_CONTENT.MAIL_CONTENT_ID).Select(x => x.FUNC_ID);
                    var _RoleId = _CODE_ROLE_FUNC.Where(x => _FuncId.Contains(x.FUNC_ID)).Select(x => x.ROLE_ID);
                    var _UserId = _CODE_USER_ROLE.Where(x => _RoleId.Contains(x.ROLE_ID)).Select(x => x.USER_ID).Distinct();
                    _userIdList.AddRange(_CODE_USER.Where(x => _UserId.Contains(x.USER_ID) && x.IS_MAIL == "Y").Select(x => x.USER_ID));

                    if (_userIdList.Any())
                    {
                        //人名 EMAIl
                        var _EMP = emps.Where(x => _userIdList.Contains(x.USR_ID)).ToList();
                        if (_EMP.Any())
                        {
                            _EMP.ForEach(x => {
                                _mailTo.Add(new Tuple <string, string>(x.EMAIL, x.EMP_NAME));
                            });
                        }
                    }

                    var str = _MAIL_CONTENT.MAIL_CONTENT1;

                    str = str.Replace("@_TREA_OPEN_TIME_", _Mail_Time.TREA_OPEN_TIME);
                    str = str.Replace("@_EXEC_TIME_E_", _Mail_Time.EXEC_TIME_E);

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(str);
//                    sb.AppendLine(
//$@"您好,
//通知今日金庫開關庫時間為:{_Mail_Time.TREA_OPEN_TIME},請準時至金庫門口集合。
//為配合金庫大門之啟閉,請有權人在:{_Mail_Time.EXEC_TIME_E} 前進入「金庫進出管理系統」完成入庫確認作業,謝謝。
//");
                    int num = 1;

                    #region 將例行作業項目寫入【申請單紀錄暫存檔】
                    Extension.NlogSet($" 將例行作業項目寫入【申請單紀錄暫存檔】");
                    _Trea_Item.ForEach(x =>
                    {
                        db.TREA_APLY_TEMP.Add(new TREA_APLY_TEMP()
                        {
                            ITEM_ID = x.ITEM_ID
                        });
                        //sb.AppendLine($"{num}. {x.ITEM_DESC}");
                        num += 1;
                    });
                    #endregion

                    #endregion

                    #region 寄送mail給保管人
                    Extension.NlogSet($" 寄送mail給保管人");
                    try
                    {
                        var sms = new SendMail.SendMailSelf();
                        sms.smtpPort    = 25;
                        sms.smtpServer  = Properties.Settings.Default["smtpServer"]?.ToString();
                        sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString();
                        sms.mailPwd     = Properties.Settings.Default["mailPwd"]?.ToString();
                        Extension.NlogSet($" 寄送mail內容 : {sb.ToString()}");
                        sms.Mail_Send(
                            new Tuple <string, string>(sms.mailAccount, "金庫管理系統"),
                            _mailTo,
                            _ccTo,
                            _MAIL_CONTENT?.MAIL_SUBJECT ?? "金庫每日例行開庫通知",
                            sb.ToString()
                            );
                    }
                    catch (Exception ex)
                    {
                        Extension.NlogSet($" 寄送mail給保管人 錯誤 : {ex.exceptionMessage()}");
                    }


                    #endregion
                    test = db.GetValidationErrors().getValidateString();
                    if (!test.IsNullOrWhiteSpace())
                    {
                        Extension.NlogSet($"{test}");
                    }
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    errorMsg = ex.exceptionMessage();
                    Extension.NlogSet($"錯誤 : {errorMsg}");
                }
                #region 異動【排程工作紀錄檔】資料(工作結束)
                var _SJR = db.SYS_JOB_REC
                           .FirstOrDefault(x => x.JOB_ITEM_ID == _JOB_ITEM_ID);
                if (_SJR != null)
                {
                    if (!errorMsg.IsNullOrWhiteSpace())
                    {
                        _SJR.STATUS = "4"; //執行失敗
                        _SJR.MEMO   = errorMsg;
                    }
                    else
                    {
                        _SJR.STATUS = "3"; //執行成功
                        _SJR.MEMO   = null;
                    }
                    _SJR.END_TIME = DateTime.Now;
                    var test = db.GetValidationErrors().getValidateString();
                    if (!test.IsNullOrWhiteSpace())
                    {
                        Extension.NlogSet($"{test}");
                    }
                    db.SaveChanges();
                }
                #endregion
            }
            //db.MAIL_TIME
        }
Esempio n. 3
0
        public void RemindClose(TreasuryDBEntities db, string dateTime, DateTime _dtn, int?_INTERVAL_MIN)
        {
            //bool result = true;
            var       _split    = dateTime.Split(':');
            var       hh        = _split[0];
            var       mm        = _split.Length > 1 ? _split[1] : string.Empty;
            var       dt        = new DateTime(_dtn.Year, _dtn.Month, _dtn.Day, Convert.ToInt32(hh), Convert.ToInt32(mm), 0);
            SysSeqDao sysSeqDao = new SysSeqDao();
            String    qPreCode  = DateUtil.getCurChtDateTime().Split(' ')[0];

            //var _TREA_OPEN_REC = db.TREA_OPEN_REC.AsNoTracking()
            //    .Where(x => x.REGI_STATUS.Trim()[0] == 'D' && x.LAST_UPDATE_DT < _dtn.AddMinutes(Convert.ToDouble(-_INTERVAL_MIN)));


            var _TREA_OPEN_REC = db.TREA_OPEN_REC.AsNoTracking().AsEnumerable()
                                 .FirstOrDefault(x => x.REGI_STATUS != "E01" && x.APPR_STATUS != "4" && x.LAST_UPDATE_DT < _dtn.AddMinutes(Convert.ToDouble(-_INTERVAL_MIN)));

            if (_TREA_OPEN_REC != null)
            {
                //result = false;

                var _TREA_APLY_REC = db.TREA_APLY_REC.AsNoTracking().FirstOrDefault(x => x.TREA_REGISTER_ID == _TREA_OPEN_REC.TREA_REGISTER_ID);

                var _Mail_Time = db.MAIL_TIME.AsNoTracking().FirstOrDefault(x => x.MAIL_TIME_ID == "3" && x.IS_DISABLED == "N");
                if (_Mail_Time != null)
                {
                    var    _MAIL_CONTENT = db.MAIL_CONTENT.AsNoTracking().FirstOrDefault(x => x.MAIL_CONTENT_ID == _Mail_Time.MAIL_CONTENT_ID && x.IS_DISABLED == "N");
                    string errorMsg      = string.Empty;

                    Extension.NlogSet($"MAIL_TIME 有找到未完成關庫覆核的金庫登記簿");
                    Extension.NlogSet($"DateTime : {_dtn}");

                    var MailTId      = sysSeqDao.qrySeqNo("MailT", qPreCode).ToString().PadLeft(3, '0');
                    var _JOB_ITEM_ID = $@"{qPreCode}W{MailTId}";

                    try
                    {
                        #region 新增排程工作紀錄檔
                        Extension.NlogSet($"新增排程工作紀錄檔");
                        db.SYS_JOB_REC.Add(new SYS_JOB_REC()
                        {
                            JOB_ITEM_ID = _JOB_ITEM_ID,
                            JOB_ID      = _Mail_Time.MAIL_TIME_ID,
                            CREATE_TIME = dt,
                            STATUS      = "2",
                            START_TIME  = _dtn,
                        });
                        var test = db.GetValidationErrors().getValidateString();
                        if (!test.IsNullOrWhiteSpace())
                        {
                            Extension.NlogSet($"{test}");
                        }
                        db.SaveChanges();
                        #endregion

                        //List<Tuple<string, string>> _mailTo = new List<Tuple<string, string>>() { new Tuple<string, string>("*****@*****.**", "測試帳號-glsisys") };
                        List <Tuple <string, string> > _mailTo = new List <Tuple <string, string> >();
                        List <Tuple <string, string> > _ccTo   = new List <Tuple <string, string> >();
                        var           _MAIL_RECEIVE            = db.MAIL_RECEIVE.AsNoTracking();
                        var           _CODE_ROLE_FUNC          = db.CODE_ROLE_FUNC.AsNoTracking();
                        var           _CODE_USER_ROLE          = db.CODE_USER_ROLE.AsEnumerable();
                        var           _CODE_USER  = db.CODE_USER.AsNoTracking();
                        List <string> _userIdList = new List <string>();
                        var           emps        = GetEmps();

                        var _FuncId = _MAIL_RECEIVE.Where(x => x.MAIL_CONTENT_ID == _MAIL_CONTENT.MAIL_CONTENT_ID).Select(x => x.FUNC_ID);
                        var _RoleId = _CODE_ROLE_FUNC.Where(x => _FuncId.Contains(x.FUNC_ID)).Select(x => x.ROLE_ID);
                        var _UserId = _CODE_USER_ROLE.Where(x => _RoleId.Contains(x.ROLE_ID)).Select(x => x.USER_ID).Distinct();
                        _userIdList.AddRange(_CODE_USER.Where(x => _UserId.Contains(x.USER_ID) && x.IS_MAIL == "Y").Select(x => x.USER_ID).ToList());
                        if (_userIdList.Any())
                        {
                            //人名 EMAIl
                            var _EMP = emps.Where(x => _userIdList.Contains(x.USR_ID)).ToList();
                            if (_EMP.Any())
                            {
                                _EMP.ForEach(x => {
                                    _mailTo.Add(new Tuple <string, string>(x.EMAIL, x.EMP_NAME));
                                });
                            }
                        }


                        StringBuilder sb = new StringBuilder();

                        string str = _MAIL_CONTENT.MAIL_CONTENT1;
                        str = str.Replace("@_TREA_REGISTER_ID_", _TREA_OPEN_REC.TREA_REGISTER_ID);
                        var status = string.Empty;

                        switch (_TREA_OPEN_REC.REGI_STATUS)
                        {
                        case "C02":
                            if (_TREA_OPEN_REC.APPR_STATUS == "3")
                            {
                                status = "【指定開庫申請作業】";
                            }
                            else if (_TREA_OPEN_REC.APPR_STATUS == "1")
                            {
                                status = "【指定開庫覆核作業】";
                            }
                            else if (_TREA_OPEN_REC.APPR_STATUS == "2")
                            {
                                if (_TREA_APLY_REC == null)
                                {
                                    status = "【入庫人員確認作業】";
                                }
                                else
                                {
                                    status = "【金庫登記簿執行作業(開庫前)】";
                                }
                            }
                            break;

                        case "D01":
                            status = "【金庫登記簿執行作業(開庫後)】";
                            break;

                        case "D02":
                        case "D04":
                            status = "【金庫登記簿覆核作業】";
                            break;
                        }

                        str = str.Replace("@_STATUS_", status);
                        sb.AppendLine(str);

                        #region 寄送mail給相關人員
                        Extension.NlogSet($" 寄送mail給相關人員");
                        try
                        {
                            var sms = new SendMail.SendMailSelf();
                            sms.smtpPort    = 25;
                            sms.smtpServer  = Properties.Settings.Default["smtpServer"]?.ToString();
                            sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString();
                            sms.mailPwd     = Properties.Settings.Default["mailPwd"]?.ToString();
                            Extension.NlogSet($" 寄送mail內容 : {sb.ToString()}");
                            sms.Mail_Send(
                                new Tuple <string, string>(sms.mailAccount, "金庫管理系統"),
                                _mailTo,
                                _ccTo,
                                _MAIL_CONTENT?.MAIL_SUBJECT ?? "金庫登記簿開庫流程尚完成通知",
                                sb.ToString()
                                );
                        }
                        catch (Exception ex)
                        {
                            Extension.NlogSet($" 寄送mail給相關人員 錯誤 : {ex.exceptionMessage()}");
                        }
                        test = db.GetValidationErrors().getValidateString();
                        if (!test.IsNullOrWhiteSpace())
                        {
                            Extension.NlogSet($"{test}");
                        }
                        db.SaveChanges();
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        errorMsg = ex.exceptionMessage();
                        Extension.NlogSet($"錯誤 : {errorMsg}");
                    }

                    #region 異動【排程工作紀錄檔】資料(工作結束)
                    var _SJR = db.SYS_JOB_REC
                               .FirstOrDefault(x => x.JOB_ITEM_ID == _JOB_ITEM_ID);
                    if (_SJR != null)
                    {
                        if (!errorMsg.IsNullOrWhiteSpace())
                        {
                            _SJR.STATUS = "4"; //執行失敗
                            _SJR.MEMO   = errorMsg;
                        }
                        else
                        {
                            _SJR.STATUS = "3"; //執行成功
                            _SJR.MEMO   = null;
                        }
                        _SJR.END_TIME = DateTime.Now;
                        var test = db.GetValidationErrors().getValidateString();
                        if (!test.IsNullOrWhiteSpace())
                        {
                            Extension.NlogSet($"{test}");
                        }
                        db.SaveChanges();
                    }
                    #endregion
                }
            }
            //return result;
        }
Esempio n. 4
0
        public JsonResult SendReport(
            reportModel data,
            List <reportParm> parms,
            List <reportParm> extensionParms = null
            )
        {
            MSGReturnModel <string> result = new MSGReturnModel <string>();

            result.RETURN_FLAG = false;

            Treasury.WebUtility.FileRelated.createFile(Server.MapPath("~/Temp/"));
            try
            {
                var fileLocation = Server.MapPath("~/Temp/");

                string title = "報表名稱";
                if (data.className.IsNullOrWhiteSpace())
                {
                    result.DESCRIPTION = "寄送報表錯誤請聯絡IT人員";
                    //result.DESCRIPTION = MessageType.parameter_Error.GetDescription(null, "無呼叫的className");
                    return(Json(result));
                }
                if (!data.title.IsNullOrWhiteSpace())
                {
                    title = data.title;
                }
                object       obj     = Activator.CreateInstance(Assembly.Load("Treasury.Web").GetType($"Treasury.Web.Report.Data.{data.className}"));
                MethodInfo[] methods = obj.GetType().GetMethods();
                MethodInfo   mi      = methods.FirstOrDefault(x => x.Name == "GetData");
                if (mi == null)
                {
                    //檢查是否有實作資料獲取
                    result.DESCRIPTION = "寄送報表錯誤請聯絡IT人員";
                    return(Json(result));
                }
                DataSet           ds    = (DataSet)mi.Invoke(obj, new object[] { parms });
                List <reportParm> eparm = (List <reportParm>)(obj.GetType().GetProperty("extensionParms").GetValue(obj));

                var lr = new LocalReport();
                lr.ReportPath = Server.MapPath($"~/Report/Rdlc/{data.className}.rdlc");
                lr.DataSources.Clear();
                List <ReportParameter> _parm = new List <ReportParameter>();
                _parm.Add(new ReportParameter("Title", title));
                if (extensionParms != null)
                {
                    _parm.AddRange(extensionParms.Select(x => new ReportParameter(x.key, x.value)));
                }
                if (eparm.Any())
                {
                    _parm.AddRange(eparm.Select(x => new ReportParameter(x.key, x.value)));
                }
                if (_parm.Any())
                {
                    lr.SetParameters(_parm);
                }

                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    lr.DataSources.Add(new ReportDataSource("DataSet" + (i + 1).ToString(), ds.Tables[i]));
                }

                string _DisplayName = title;
                if (_DisplayName != null)
                {
                    _DisplayName = _DisplayName.Replace("(", "-").Replace(")", "");
                    var _name = _parm.FirstOrDefault(x => x.Name == "vJobProject");
                    if (_name != null)
                    {
                        _DisplayName = $"{_DisplayName}_{_name.Values[0]}";
                    }
                }
                lr.DisplayName = _DisplayName;
                lr.Refresh();

                string mimeType, encoding, extension;

                Warning[] warnings;
                string[]  streams;
                var       renderedBytes = lr.Render
                                          (
                    "PDF",
                    null,
                    out mimeType,
                    out encoding,
                    out extension,
                    out streams,
                    out warnings
                                          );

                var saveAs = string.Format("{0}.pdf", Path.Combine(fileLocation, _DisplayName));

                var idx = 0;
                while (Directory.Exists(saveAs))
                {
                    idx++;
                    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(fileLocation, _DisplayName), idx);
                }

                //using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
                //{
                //    stream.Write(renderedBytes, 0, renderedBytes.Length);
                //    stream.Close();
                //}

                lr.Dispose();


                #region 寄信
                //存許項目
                string vitemIdName = extensionParms.FirstOrDefault(x => x.key == "vJobProject")?.value;
                //庫存日期
                string aplyDt = parms.FirstOrDefault(x => x.key == "APLY_DT_From")?.value;

                MAIL_TIME    MT = new MAIL_TIME();
                MAIL_CONTENT MC = new MAIL_CONTENT();

                //List<Tuple<string, string>> _mailTo = new List<Tuple<string, string>>() { new Tuple<string, string>("*****@*****.**", "測試帳號-glsisys") };
                List <Tuple <string, string> > _mailTo = new List <Tuple <string, string> >();
                List <Tuple <string, string> > _ccTo   = new List <Tuple <string, string> >();
                using (TreasuryDBEntities db = new TreasuryDBEntities())
                {
                    //季追蹤庫存表 抓5
                    MT = db.MAIL_TIME.AsNoTracking().FirstOrDefault(x => x.MAIL_TIME_ID == "5" && x.IS_DISABLED != "Y");
                    var _MAIL_CONTENT_ID = MT?.MAIL_CONTENT_ID;
                    MC = db.MAIL_CONTENT.AsNoTracking().FirstOrDefault(x => x.MAIL_CONTENT_ID == _MAIL_CONTENT_ID && x.IS_DISABLED != "Y");
                    var _MAIL_RECEIVE   = db.MAIL_RECEIVE.AsNoTracking();
                    var _CODE_ROLE_FUNC = db.CODE_ROLE_FUNC.AsNoTracking();
                    var _CODE_USER_ROLE = db.CODE_USER_ROLE.AsEnumerable();
                    var _CODE_USER      = db.CODE_USER.AsNoTracking();

                    var emps = comm.GetEmps();
                    using (DB_INTRAEntities dbINTRA = new DB_INTRAEntities())
                    {
                        //存許項目
                        string vitemId = parms.FirstOrDefault(x => x.key == "vJobProject")?.value;             //Bianco 20190326 原參數 vjobProject
                        //權責部門
                        string vdept = parms.FirstOrDefault(x => x.key == "vdept")?.value;                     //Bianco 20190326 原參數 CHARGE_DEPT_ID
                        //權責科別
                        string vsect = parms.FirstOrDefault(x => x.key == "vsect")?.value;                     //Bianco 20190326 原參數 CHARGE_SECT_ID

                        var _VW_OA_DEPT = dbINTRA.VW_OA_DEPT.AsNoTracking();
                        var _V_EMPLY2   = dbINTRA.V_EMPLY2.AsNoTracking();

                        var _ITEM_CHARGE_UNIT = db.ITEM_CHARGE_UNIT.AsNoTracking()
                                                .Where(x => x.ITEM_ID == vitemId, vitemId != null)
                                                .Where(x => x.CHARGE_DEPT == vdept, vdept != "All")
                                                .Where(x => x.CHARGE_SECT == vsect, vsect != "All")
                                                .Where(x => x.IS_DISABLED == "N")
                                                .AsEnumerable()
                                                .Select(x => new ITEM_CHARGE_UNIT()
                        {
                            CHARGE_DEPT      = x.CHARGE_DEPT,
                            CHARGE_SECT      = x.CHARGE_SECT,
                            CHARGE_UID       = x.CHARGE_UID,
                            IS_MAIL_SECT_MGR = x.IS_MAIL_SECT_MGR,
                            IS_MAIL_DEPT_MGR = x.IS_MAIL_DEPT_MGR
                        }).ToList();
                        _ITEM_CHARGE_UNIT.ForEach(x => {
                            //經辦

                            var _CHARGE_NAME = _V_EMPLY2.FirstOrDefault(y => y.USR_ID == x.CHARGE_UID);
                            if (_CHARGE_NAME != null && !_mailTo.Any(y => y.Item1 == _CHARGE_NAME.EMAIL))
                            {
                                _mailTo.Add(new Tuple <string, string>(_CHARGE_NAME.EMAIL, _CHARGE_NAME.EMP_NAME));
                            }

                            if (x.IS_MAIL_SECT_MGR == "Y")
                            {
                                //科主管員編
                                var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.DPT_HEAD;

                                //人名 EMAIl
                                var _EMP_NAME = _V_EMPLY2.FirstOrDefault(y => y.EMP_NO == _VW_OA_DEPT_DPT_HEAD);
                                if (_EMP_NAME != null && !_mailTo.Any(y => y.Item1 == _EMP_NAME.EMAIL))
                                {
                                    _mailTo.Add(new Tuple <string, string>(_EMP_NAME.EMAIL, _EMP_NAME.EMP_NAME));
                                }
                            }
                            if (x.IS_MAIL_DEPT_MGR == "Y")
                            {
                                //部主管員編
                                //var _UP_DPT_CD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.UP_DPT_CD;
                                //var _UP_DPT_CD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_SECT)?.UP_DPT_CD;
                                //var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == _UP_DPT_CD)?.DPT_HEAD;
                                var _VW_OA_DEPT_DPT_HEAD = _VW_OA_DEPT.FirstOrDefault(y => y.DPT_CD == x.CHARGE_DEPT)?.DPT_HEAD;
                                //人名 EMAIl
                                var _EMP_NAME = _V_EMPLY2.FirstOrDefault(y => y.EMP_NO == _VW_OA_DEPT_DPT_HEAD);
                                if (_EMP_NAME != null && !_ccTo.Any(y => y.Item1 == _EMP_NAME.EMAIL) && !_mailTo.Any(y => y.Item1 == _EMP_NAME.EMAIL))
                                {
                                    _ccTo.Add(new Tuple <string, string>(_EMP_NAME.EMAIL, _EMP_NAME.EMP_NAME));
                                }
                            }
                        });
                        if (MC != null)
                        {
                            var           _FuncId     = _MAIL_RECEIVE.Where(x => x.MAIL_CONTENT_ID == MC.MAIL_CONTENT_ID).Select(x => x.FUNC_ID);
                            var           _RoleId     = _CODE_ROLE_FUNC.Where(x => _FuncId.Contains(x.FUNC_ID)).Select(x => x.ROLE_ID);
                            var           _UserId     = _CODE_USER_ROLE.Where(x => _RoleId.Contains(x.ROLE_ID)).Select(x => x.USER_ID).Distinct();
                            List <string> _userIdList = new List <string>();

                            _userIdList.AddRange(_CODE_USER.Where(x => _UserId.Contains(x.USER_ID) && x.IS_MAIL == "Y").Select(x => x.USER_ID).ToList());
                            if (_userIdList.Any())
                            {
                                //人名 EMAIl
                                var _EMP = emps.Where(x => _userIdList.Contains(x.USR_ID)).ToList();
                                if (_EMP.Any())
                                {
                                    _EMP.ForEach(x => {
                                        if (!_ccTo.Any(y => y.Item1 == x.EMAIL) && !_mailTo.Any(y => y.Item1 == x.EMAIL))
                                        {
                                            _ccTo.Add(new Tuple <string, string>(x.EMAIL, x.EMP_NAME));
                                        }
                                    });
                                }
                            }
                        }
                    }
                }

                string passwordZip = getPassWord();
                Dictionary <string, Stream> attachment = new Dictionary <string, Stream>();
                //attachment.Add(string.Format("{0}.pdf", _DisplayName), new MemoryStream(renderedBytes));

                using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))
                {
                    var memSteam     = new MemoryStream();
                    var streamWriter = new StreamWriter(memSteam);


                    ZipEntry e = zip.AddEntry(string.Format("{0}.pdf", _DisplayName), new MemoryStream(renderedBytes));
                    e.Password   = passwordZip;
                    e.Encryption = EncryptionAlgorithm.WinZipAes256;

                    var ms = new MemoryStream();
                    ms.Seek(0, SeekOrigin.Begin);

                    zip.Save(ms);

                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Flush();

                    attachment.Add(string.Format("{0}.zip", _DisplayName), ms);
                }

                string str = MC?.MAIL_CONTENT1 ?? string.Empty;

                str = str.Replace("@_DATE_", aplyDt);
                str = str.Replace("@_ITEM_", vitemIdName);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(str);

                try
                {
                    var sms = new SendMail.SendMailSelf();
                    sms.smtpPort    = 25;
                    sms.smtpServer  = Properties.Settings.Default["smtpServer"]?.ToString();
                    sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString();
                    sms.mailPwd     = Properties.Settings.Default["mailPwd"]?.ToString();
                    sms.Mail_Send(
                        new Tuple <string, string>(sms.mailAccount, "金庫管理系統"),
                        _mailTo,
                        _ccTo,
                        MC?.MAIL_SUBJECT ?? "季追蹤庫存表",
                        sb.ToString(),
                        false,
                        attachment
                        );
                }
                catch (Exception ex)
                {
                    result.DESCRIPTION = $"Email 發送失敗請人工通知。";
                    return(Json(result));
                }


                //寄密碼
                try
                {
                    var sms = new SendMail.SendMailSelf();
                    sms.smtpPort    = 25;
                    sms.smtpServer  = Properties.Settings.Default["smtpServer"]?.ToString();
                    sms.mailAccount = Properties.Settings.Default["mailAccount"]?.ToString();
                    sms.mailPwd     = Properties.Settings.Default["mailPwd"]?.ToString();
                    sms.Mail_Send(
                        new Tuple <string, string>(sms.mailAccount, "金庫管理系統"),
                        _mailTo,
                        _ccTo,
                        "季追蹤庫存表-密碼",
                        $"密碼:{passwordZip}",
                        false,
                        null
                        );
                }
                catch (Exception ex)
                {
                    result.DESCRIPTION = $"Email 密碼發送失敗。";
                    return(Json(result));
                }
                #endregion

                result.RETURN_FLAG = true;
                result.DESCRIPTION = "已寄送追蹤報表!";
            }
            catch (Exception ex)
            {
                result.DESCRIPTION = ex.exceptionMessage();
            }
            return(Json(result));
        }