Exemple #1
0
        public string Create(DepartmentModel entity)
        {
            _context.Departments.Add(entity);
            _context.SaveChanges();

            return(entity.DptId);
        }
        public string[] Create(DocIdStore entity)
        {
            _context.DocIdStores.Add(entity);
            _context.SaveChanges();

            return(new string[] { entity.DocType, entity.DocId });
        }
        public int Create(AppUserModel entity)
        {
            _context.AppUsers.Add(entity);
            _context.SaveChanges();

            return(entity.Id);
        }
Exemple #4
0
        public int Create(AppRoleModel entity)
        {
            _context.AppRoles.Add(entity);
            _context.SaveChanges();

            return(entity.RoleId);
        }
        public string Create(RepairDtlModel entity)
        {
            _context.BMEDRepairDtls.Add(entity);
            _context.SaveChanges();

            return(entity.DocId);
        }
Exemple #6
0
        public string ChangePassword(ApplicationUser user, string currentPassword, string newPassword)
        {
            string s = "";

            if (string.IsNullOrEmpty(user.Id))
            {
                s = "錯誤!無此帳號!";
                return(s);
            }
            int id = Convert.ToInt32(user.Id);
            var ur = _context.AppUsers.Find(id);

            if (ur != null)
            {
                // user's password encrypt by DES.
                string DESKey  = "84203025";
                var    checkPW = CryptoExtensions.DESEncrypt(currentPassword, DESKey);
                if (ur.Password == checkPW)
                {
                    var encryptPW = CryptoExtensions.DESEncrypt(newPassword, DESKey);   // Encrypt and check password.
                    ur.Password = encryptPW;
                    _context.Entry(ur).State = EntityState.Modified;
                    _context.SaveChanges();
                    s = "成功";
                    return(s);
                }
            }
            s = "錯誤!原密碼輸入不正確!";
            return(s);
        }
        public string[] Create(RepairEmpModel entity)
        {
            _context.BMEDRepairEmps.Add(entity);
            _context.SaveChanges();

            return(new string[] { entity.DocId, entity.UserId.ToString() });
        }
Exemple #8
0
        public IActionResult Create(RepairEmpModel repairEmp)
        {
            if (ModelState.IsValid)
            {
                _context.BMEDRepairEmps.Add(repairEmp);
                _context.SaveChanges();
                // Recount the all repair time, and set value to RepairDtl.
                RepairDtlModel dtl = _context.BMEDRepairDtls.Where(d => d.DocId == repairEmp.DocId)
                                     .FirstOrDefault();
                if (dtl != null)
                {
                    int hr = _context.BMEDRepairEmps.Where(p => p.DocId == repairEmp.DocId)
                             .Select(p => p.Hour)
                             .DefaultIfEmpty(0).Sum();
                    decimal min = _context.BMEDRepairEmps.Where(p => p.DocId == repairEmp.DocId)
                                  .Select(p => p.Minute)
                                  .DefaultIfEmpty(0).Sum();
                    dtl.Hour = hr + Decimal.Round(min / 60m, 2);
                    _context.BMEDRepairDtls.Update(dtl);
                }
                return(RedirectToAction("Index"));
            }

            return(View(repairEmp));
        }
Exemple #9
0
 public IActionResult Create(KeepFormatDtlModel keepformat_dtl)
 {
     if (ModelState.IsValid)
     {
         _context.BMEDKeepFormatDtls.Add(keepformat_dtl);
         _context.SaveChanges();
         return(RedirectToAction("Edit", "KeepFormat", new { Area = "BMED", id = keepformat_dtl.FormatId }));
     }
     return(View(keepformat_dtl));
 }
        public async Task <IActionResult> Create(AssetFileModel assetfile, IEnumerable <IFormFile> file)
        {
            if (ModelState.IsValid)
            {
                string s = "/Files/BMED";
                s += "/Asset";

                var assetFile = _context.AssetFiles.Where(af => af.AssetNo == assetfile.AssetNo && af.SeqNo == assetfile.SeqNo)
                                .Select(af => af.Fid).ToList();
                int?i = null;
                if (assetFile.Count() > 0)
                {
                    i = assetFile.Max();
                }
                if (i == null)
                {
                    assetfile.Fid = 1;
                }
                else
                {
                    assetfile.Fid = Convert.ToInt32(i + 1);
                }
                string WebRootPath = _hostingEnvironment.WebRootPath;
                string path        = Path.Combine(WebRootPath + s, assetfile.AssetNo + "_"
                                                  + assetfile.SeqNo.ToString() + "_" + assetfile.Fid.ToString() + Path.GetExtension(Request.Form.Files[0].FileName));
                string filelink = assetfile.AssetNo + "_" + assetfile.SeqNo.ToString() + "_"
                                  + assetfile.Fid.ToString() + Path.GetExtension(Request.Form.Files[0].FileName);
                try
                {
                    // Upload files.
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await Request.Form.Files[0].CopyToAsync(stream);
                    }
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
                assetfile.FileLink = "Asset/" + filelink;
                assetfile.Rtt      = DateTime.Now;
                _context.AssetFiles.Add(assetfile);
                try
                {
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
                return(View());
            }

            return(Content("錯誤!!"));
        }
        public IActionResult Create(BudgetModel budget)
        {
            if (ModelState.IsValid)
            {
                _context.Budgets.Add(budget);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(budget));
        }
        public void RemoveUserFromRoles(string username, string[] roleNames)
        {
            var user = _context.AppUsers.Where(u => u.UserName == username).FirstOrDefault();

            if (user != null)
            {
                var userInRoles = _context.UsersInRoles.Where(r => roleNames.Contains(r.AppRoles.RoleName))
                                  .Where(r => r.UserName == username).ToList();
                _context.UsersInRoles.RemoveRange(userInRoles);
                _context.SaveChanges();
            }
        }
        public string Create(RepairModel entity)
        {
            try
            {
                _context.BMEDRepairs.Add(entity);
                _context.SaveChanges();
            }catch (Exception e)
            {
                throw e;
            }

            return(entity.DocId);
        }
Exemple #14
0
        public string GetTicketSeq()
        {
            string result = "";
            int    seq    = 0;
            string yyymm  = Convert.ToString((DateTime.Now.Year - 1911) * 100 + DateTime.Now.Month);
            int    cnt    = _context.BMEDTicket_seq_tmps.Where(t => t.YYYMM == yyymm).Count();
            Ticket_seq_tmpModel tmp;

            if (cnt > 0)
            {
                tmp                       = _context.BMEDTicket_seq_tmps.Find(yyymm);
                seq                       = Convert.ToInt32(tmp.TICKET_SEQ) + 1;
                result                    = Convert.ToString(seq);
                tmp.TICKET_SEQ            = Convert.ToString(seq);
                _context.Entry(tmp).State = EntityState.Modified;
            }
            else
            {
                tmp            = new Ticket_seq_tmpModel();
                seq            = Convert.ToInt32(yyymm) * 1000 + 1;
                tmp.YYYMM      = Convert.ToString(yyymm);
                tmp.TICKET_SEQ = Convert.ToString(seq);
                result         = Convert.ToString(seq);
                _context.BMEDTicket_seq_tmps.Add(tmp);
            }
            _context.SaveChanges();

            return(result);
        }
        public ActionResult Edit(KeepEmpModel keepEmp)
        {
            if (ModelState.IsValid)
            {
                var ExistKeepEmp = _context.BMEDKeepEmps.Find(keepEmp.DocId, keepEmp.UserId);
                if (ExistKeepEmp != null)
                {
                    return(new JsonResult(keepEmp)
                    {
                        Value = new { isExist = true, error = "資料已存在!" }
                    });
                }
                else
                {
                    _context.BMEDKeepEmps.Add(keepEmp);
                    _context.SaveChanges();
                }

                // Recount the all keep time, and set value to KeepDtl.
                KeepDtlModel dtl = _context.BMEDKeepDtls.Where(d => d.DocId == keepEmp.DocId)
                                   .FirstOrDefault();
                if (dtl != null)
                {
                    int hr = _context.BMEDKeepEmps.Where(p => p.DocId == keepEmp.DocId)
                             .Select(p => p.Hour)
                             .DefaultIfEmpty(0).Sum();
                    decimal min = _context.BMEDKeepEmps.Where(p => p.DocId == keepEmp.DocId)
                                  .Select(p => p.Minute)
                                  .DefaultIfEmpty(0).Sum();
                    dtl.Hours = hr + Decimal.Round(min / 60m, 2);
                    _context.Entry(dtl).State = EntityState.Modified;
                    _context.SaveChanges();
                }

                // Return ViewComponent for ajax request.
                return(ViewComponent("BMEDKeepEmpList", new { id = keepEmp.DocId, viewType = "Edit" }));
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }
        }
        //
        // GET: /BuyEvaluate/Create
        public IActionResult Create()
        {
            // Get Login User's details.
            var u = _userRepo.Find(ur => ur.UserName == User.Identity.Name).FirstOrDefault();
            BuyEvaluateModel r = new BuyEvaluateModel();
            DepartmentModel  d = _context.Departments.Find(u.DptId);
            VendorModel      v = _context.BMEDVendors.Find(u.VendorId);

            r.DocId     = r.GetID(ref _context);
            r.UserId    = u.Id;
            r.UserName  = u.FullName;
            r.Company   = d.DptId == null ? "" : d.Name_C;
            r.AccDpt    = d.DptId == null ? "" : d.DptId;
            r.AccDptNam = d.DptId == null ? "" : d.Name_C;
            r.Contact   = u.Mobile;
            r.PlantType = "醫療儀器";
            r.Place     = r.AccDptNam;
            r.Rtt       = DateTime.Now;
            _context.BuyEvaluates.Add(r);
            _context.SaveChanges();
            List <SelectListItem> listItem  = new List <SelectListItem>();
            List <SelectListItem> listItem2 = new List <SelectListItem>();
            List <SelectListItem> listItem3 = new List <SelectListItem>();

            listItem3.Add(new SelectListItem {
                Text = "醫療儀器", Value = "醫療儀器"
            });
            listItem3.Add(new SelectListItem {
                Text = "資訊設備", Value = "資訊設備"
            });
            ViewData["PTYPE"] = new SelectList(listItem3, "Value", "Text", "醫療儀器");
            string[]     eng   = roleManager.GetUsersInRole("MedEngineer");
            string[]     buyer = roleManager.GetUsersInRole("Buyer");
            AppUserModel p;

            foreach (string s in eng)
            {
                p = _context.AppUsers.Where(ur => ur.UserName == s).FirstOrDefault();
                if (p != null)
                {
                    listItem.Add(new SelectListItem {
                        Text = "(" + p.UserName + ")" + p.FullName, Value = p.Id.ToString()
                    });
                }
            }
            ViewData["ENG"] = new SelectList(listItem, "Value", "Text");
            //
            foreach (string s2 in buyer)
            {
                p = _context.AppUsers.Where(ur => ur.UserName == s2).FirstOrDefault();
                if (p != null)
                {
                    listItem2.Add(new SelectListItem {
                        Text = "(" + p.UserName + ")" + p.FullName, Value = p.Id.ToString()
                    });
                }
            }
            ViewData["PUR"] = new SelectList(listItem2, "Value", "Text");
            return(View(r));
        }
Exemple #17
0
        public ActionResult Create(BuyFlowModel buyflow)
        {
            if (ModelState.IsValid)
            {
                _context.BuyFlows.Add(buyflow);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(buyflow));
        }
Exemple #18
0
 public IActionResult Edit(AssetKeepModel assetKeep)
 {
     if (ModelState.IsValid)
     {
         assetKeep.KeepEngName           = _context.AppUsers.Find(assetKeep.KeepEngId).FullName;
         _context.Entry(assetKeep).State = EntityState.Modified;
         _context.SaveChanges();
         return(new JsonResult(assetKeep)
         {
             Value = new { success = true, error = "" }
         });
     }
     else
     {
         string msg = "";
         foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
         {
             msg += error.ErrorMessage + Environment.NewLine;
         }
         throw new Exception(msg);
     }
 }
        public IActionResult Create(KeepFormatModel keepformat)
        {
            AppUserModel ur = _context.AppUsers.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();

            keepformat.FormatId = keepformat.FormatId.Trim();
            KeepFormatModel k = _context.BMEDKeepFormats.Find(keepformat.FormatId);

            if (k != null)
            {
                ModelState.AddModelError("", "保養格式代號重複!!");
                return(View(keepformat));
            }
            if (ModelState.IsValid)
            {
                keepformat.Rtp = ur.Id;
                keepformat.Rtt = DateTime.Now;
                _context.BMEDKeepFormats.Add(keepformat);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(keepformat));
        }
Exemple #20
0
 public async Task <IActionResult> Edit(IFormCollection vmodel)
 {
     if (ModelState.IsValid)
     {
         KeepRecordModel r;
         KeepRecordModel r2;
         int             i = vmodel["item.Sno"].Count();
         for (int j = 0; j < i; j++)
         {
             r          = new KeepRecordModel();
             r.DocId    = vmodel["item.DocId"][j];
             r.FormatId = vmodel["item.FormatId"][j];
             r.Sno      = Convert.ToInt32(vmodel["item.Sno"][j]);
             r.Descript = vmodel["item.Descript"][j];
             r.KeepDes  = vmodel["item.KeepDes"][j];
             r2         = _context.BMEDKeepRecords.Find(r.DocId, r.FormatId, r.Sno);
             if (r2 != null)
             {
                 r2.KeepDes = r.KeepDes;
                 _context.Entry(r2).State = EntityState.Modified;
             }
             else
             {
                 _context.BMEDKeepRecords.Add(r);
             }
         }
         try
         {
             _context.SaveChanges();
             return(new JsonResult(vmodel)
             {
                 Value = new { success = true, error = "" }
             });
         }
         catch (Exception ex)
         {
             throw new Exception(ex.Message);
         }
     }
     else
     {
         string msg = "";
         foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
         {
             msg += error.ErrorMessage + Environment.NewLine;
         }
         throw new Exception(msg);
     }
 }
 public JsonResult EditData(DelivDataVModel dv)
 {
     if (ModelState.IsValid)
     {
         DeliveryModel d = _context.Deliveries.Find(dv.DocId);
         if (d != null)
         {
             _context.Entry(d).State = EntityState.Modified;
             d.WartyNt      = dv.WartyNt;
             d.AcceptDate   = dv.AcceptDate;
             d.WartySt      = dv.WartySt;
             d.WartyEd      = dv.WartyEd;
             d.FileTestDate = dv.FileTestDate;
             d.TestUid      = dv.TestUid;
             d.Code         = dv.Code;
             d.Stype2       = dv.Stype2;
             d.OpenDate     = dv.OpenDate;
             d.OrderDate    = dv.OrderDate;
             _context.SaveChanges();
         }
         return(Json(new { success = true, msg = "儲存成功!" }));
     }
     return(Json(new { success = false, msg = "儲存失敗!" }));
 }
        public IActionResult Create(BuyVendorModel buyvendor)
        {
            if (ModelState.IsValid)
            {
                _context.BuyVendors.Add(buyvendor);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(buyvendor));
        }
 public async Task <IActionResult> Edit(KeepDtlModel keepDtlModel)
 {
     if (ModelState.IsValid)
     {
         try
         {
             if (keepDtlModel.IsCharged == "N")
             {
                 //_context.BMEDKeepCosts.RemoveRange(_context.BMEDKeepCosts.Where(c => c.DocId == keepDtlModel.DocId));
                 keepDtlModel.Cost = 0;
             }
             else
             {
                 keepDtlModel.Cost = _context.BMEDKeepCosts.Where(k => k.DocId == keepDtlModel.DocId)
                                     .Select(k => k.TotalCost)
                                     .DefaultIfEmpty(0).Sum();
                 int hr = _context.BMEDKeepEmps.Where(p => p.DocId == keepDtlModel.DocId)
                          .Select(p => p.Hour)
                          .DefaultIfEmpty(0).Sum();
                 decimal min = _context.BMEDKeepEmps.Where(p => p.DocId == keepDtlModel.DocId)
                               .Select(p => p.Minute)
                               .DefaultIfEmpty(0).Sum();
                 keepDtlModel.Hours = hr + Decimal.Round(min / 60m, 2);
             }
             _context.Entry(keepDtlModel).State = EntityState.Modified;
             _context.SaveChanges();
             return(new JsonResult(keepDtlModel)
             {
                 Value = new { success = true, error = "" }
             });
         }
         catch (Exception e)
         {
             throw new Exception(e.Message);
         }
     }
     else
     {
         string msg = "";
         foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
         {
             msg += error.ErrorMessage + Environment.NewLine;
         }
         throw new Exception(msg);
     }
 }
Exemple #24
0
        public IActionResult Edit(RepairCostModel repairCost)
        {
            var ur = _userRepo.Find(u => u.UserName == this.User.Identity.Name).FirstOrDefault();

            /* Change to UpperCase.*/
            if (repairCost.TicketDtl.TicketDtlNo != null)
            {
                repairCost.TicketDtl.TicketDtlNo = repairCost.TicketDtl.TicketDtlNo.ToUpper();
            }
            if (repairCost.SignNo != null)
            {
                repairCost.SignNo = repairCost.SignNo.ToUpper();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (repairCost.StockType == "2")
                    {
                        var dupData = _context.BMEDRepairCosts.Include(c => c.TicketDtl)
                                      .Where(c => c.DocId == repairCost.DocId &&
                                             c.PartName == repairCost.PartName &&
                                             c.Standard == repairCost.Standard &&
                                             c.TicketDtl.TicketDtlNo == repairCost.TicketDtl.TicketDtlNo).FirstOrDefault();
                        if (dupData != null)
                        {
                            string msg = "資料重複儲存!!";
                            return(BadRequest(msg));
                        }
                    }
                    else
                    {
                        var dupData = _context.BMEDRepairCosts.Include(c => c.TicketDtl)
                                      .Where(c => c.DocId == repairCost.DocId &&
                                             c.PartName == repairCost.PartName &&
                                             c.Standard == repairCost.Standard &&
                                             c.SignNo == repairCost.SignNo).FirstOrDefault();
                        if (dupData != null)
                        {
                            string msg = "資料重複儲存!!";
                            return(BadRequest(msg));
                        }
                    }

                    int seqno = _context.BMEDRepairCosts.Where(c => c.DocId == repairCost.DocId)
                                .Select(c => c.SeqNo).DefaultIfEmpty().Max();
                    repairCost.SeqNo = seqno + 1;
                    if (repairCost.StockType == "2")
                    {
                        if (string.IsNullOrEmpty(repairCost.TicketDtl.TicketDtlNo))
                        {
                            //throw new Exception("發票號碼不可空白!!");
                            string msg = "發票號碼不可空白!!";
                            return(BadRequest(msg));
                        }
                        if (repairCost.AccountDate == null)
                        {
                            //throw new Exception("發票日期不可空白!!");
                            string msg = "發票日期不可空白!!";
                            return(BadRequest(msg));
                        }
                        int i = _context.BMEDTicketDtls.Where(d => d.TicketDtlNo == repairCost.TicketDtl.TicketDtlNo)
                                .Select(d => d.SeqNo).DefaultIfEmpty().Max();
                        repairCost.TicketDtl.SeqNo   = i + 1;
                        repairCost.TicketDtl.ObjName = repairCost.PartName;
                        repairCost.TicketDtl.Qty     = repairCost.Qty;
                        repairCost.TicketDtl.Unite   = repairCost.Unite;
                        repairCost.TicketDtl.Price   = repairCost.Price;
                        repairCost.TicketDtl.Cost    = repairCost.TotalCost;
                        TicketModel t = _context.BMEDTickets.Find(repairCost.TicketDtl.TicketDtlNo);
                        if (t == null)
                        {
                            t            = new TicketModel();
                            t.TicketNo   = repairCost.TicketDtl.TicketDtlNo;
                            t.TicDate    = repairCost.AccountDate;
                            t.ApplyDate  = null;
                            t.CancelDate = null;
                            t.VendorId   = repairCost.VendorId;
                            t.VendorName = repairCost.VendorName;
                            repairCost.TicketDtl.Ticket = t;
                            _context.BMEDTickets.Add(t);
                        }
                        _context.BMEDTicketDtls.Add(repairCost.TicketDtl);
                    }
                    else
                    {
                        repairCost.AccountDate = repairCost.AccountDate == null ? DateTime.Now.Date : repairCost.AccountDate;
                        repairCost.TicketDtl   = null;
                    }
                    repairCost.Rtp = ur.Id;
                    repairCost.Rtt = DateTime.Now;
                    if (repairCost.StockType != "0")
                    {
                        repairCost.PartNo = "";
                    }

                    _context.BMEDRepairCosts.Add(repairCost);
                    _context.SaveChanges();
                    //
                    RepairDtlModel dtl = _context.BMEDRepairDtls.Where(d => d.DocId == repairCost.DocId)
                                         .FirstOrDefault();
                    if (dtl != null)
                    {
                        dtl.Cost = _context.BMEDRepairCosts.Where(k => k.DocId == repairCost.DocId)
                                   .Select(k => k.TotalCost)
                                   .DefaultIfEmpty(0).Sum();
                        _context.Entry(dtl).State = EntityState.Modified;
                        _context.SaveChanges();
                    }

                    return(ViewComponent("BMEDRepCostList", new { id = repairCost.DocId, viewType = "Edit" }));
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }
        }
        public async Task <IActionResult> Edit(RepairDtlModel repairDtl)
        {
            if (ModelState.IsValid)
            {
                //if (string.IsNullOrEmpty(repairDtl.DealDes))
                //{
                //    throw new Exception("請輸入[處理描述]!!");
                //}
                try
                {
                    if (repairDtl.IsCharged == "N")
                    {
                        //_context.BMEDRepairCosts.RemoveRange(_context.BMEDRepairCosts.Where(c => c.DocId == repairDtl.DocId));
                        repairDtl.Cost = 0;
                    }
                    else
                    {
                        repairDtl.Cost = _context.BMEDRepairCosts.Where(k => k.DocId == repairDtl.DocId)
                                         .Select(k => k.TotalCost)
                                         .DefaultIfEmpty(0).Sum();
                        int hr = _context.BMEDRepairEmps.Where(p => p.DocId == repairDtl.DocId)
                                 .Select(p => p.Hour)
                                 .DefaultIfEmpty(0).Sum();
                        decimal min = _context.BMEDRepairEmps.Where(p => p.DocId == repairDtl.DocId)
                                      .Select(p => p.Minute)
                                      .DefaultIfEmpty(0).Sum();
                        repairDtl.Hour = hr + Decimal.Round(min / 60m, 2);
                    }
                    _context.Entry(repairDtl).State = EntityState.Modified;

                    /* Edit AssetNo if No exist. */
                    var repairModel = _context.BMEDRepairs.Find(repairDtl.DocId);
                    repairModel.AssetNo = repairDtl.AssetNo;
                    var tempAsset = _context.BMEDAssets.Where(a => a.AssetNo == repairDtl.AssetNo).FirstOrDefault();
                    if (tempAsset != null)
                    {
                        repairModel.AssetName = tempAsset.Cname;
                    }
                    _context.Entry(repairModel).State = EntityState.Modified;

                    _context.SaveChanges();

                    return(new JsonResult(repairDtl)
                    {
                        Value = new { success = true, error = "" }
                    });
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }
        }
Exemple #26
0
        public async Task <IActionResult> NextFlow(AssignModel assign)
        {
            var ur        = _userRepo.Find(u => u.UserName == this.User.Identity.Name).FirstOrDefault();
            var repairDtl = _context.BMEDRepairDtls.Find(assign.DocId);

            /* 工程師的流程控管 */
            if (assign.Cls == "設備工程師")
            {
                /* 如點選有費用、卻無輸入費用明細 */
                var isCharged = _context.BMEDRepairDtls.Where(d => d.DocId == assign.DocId).FirstOrDefault().IsCharged;
                if (isCharged == "Y")
                {
                    var CheckRepairCost = _context.BMEDRepairCosts.Where(c => c.DocId == assign.DocId).FirstOrDefault();
                    if (CheckRepairCost == null)
                    {
                        throw new Exception("尚未輸入費用明細!!");
                    }
                }
            }
            //    var repairDtl = _context.BMEDRepairDtls.Where(d => d.DocId == assign.DocId).FirstOrDefault();
            //    /* 3 = 已完成,4 = 報廢 */
            //    if (repairDtl.DealState == 3 || repairDtl.DealState == 4)
            //    {
            //        if(repairDtl.EndDate == null)
            //        {
            //            throw new Exception("報廢及已完成,需輸入完工日!!");
            //        }
            //    }


            if (assign.FlowCls == "結案" || assign.FlowCls == "廢除")
            {
                assign.FlowUid = ur.Id;
            }
            if (ModelState.IsValid)
            {
                RepairFlowModel rf = _context.BMEDRepairFlows.Where(f => f.DocId == assign.DocId && f.Status == "?").FirstOrDefault();
                if (assign.FlowCls == "驗收人")
                {
                    if (_context.BMEDRepairEmps.Where(emp => emp.DocId == assign.DocId).Count() <= 0)
                    {
                        throw new Exception("沒有維修工程師紀錄!!");
                    }
                    else if (_context.BMEDRepairDtls.Find(assign.DocId).EndDate == null)
                    {
                        throw new Exception("沒有完工日!!");
                    }
                    else if (_context.BMEDRepairDtls.Find(assign.DocId).DealState == 0)
                    {
                        throw new Exception("處理狀態不可空值!!");
                    }
                    if (_context.BMEDRepairDtls.Find(assign.DocId).FailFactor == 0)
                    {
                        throw new Exception("故障原因不可空白!!");
                    }
                    if (string.IsNullOrEmpty(_context.BMEDRepairDtls.Find(assign.DocId).InOut))
                    {
                        throw new Exception("維修方式不可空白!!");
                    }
                    if (_context.BMEDRepairDtls.Find(assign.DocId).DealState == 3 ||
                        _context.BMEDRepairDtls.Find(assign.DocId).DealState == 4 ||
                        _context.BMEDRepairDtls.Find(assign.DocId).DealState == 8)
                    {
                        //Do nothing.
                        //狀態為【已完成】、【報廢】、【退件】才可送至驗收人
                    }
                    else
                    {
                        throw new Exception("送至驗收人處理狀態只可為【已完成】、【報廢】、【退件】!!");
                    }
                }
                if (assign.FlowCls == "結案")
                {
                    if (assign.Cls == "驗收人" && repairDtl != null)
                    {
                        if (repairDtl.IsCharged == "Y")
                        {
                            throw new Exception("有費用之案件不可由驗收人直接結案!");
                        }
                    }
                    RepairDtlModel rd = _context.BMEDRepairDtls.Find(assign.DocId);
                    rd.CloseDate             = DateTime.Now;
                    rf.Opinions              = "[" + assign.AssignCls + "]" + Environment.NewLine + assign.AssignOpn;
                    rf.Status                = "2";
                    rf.UserId                = ur.Id;
                    rf.UserName              = _context.AppUsers.Find(ur.Id).FullName;
                    rf.Rtt                   = DateTime.Now;
                    rf.Rtp                   = ur.Id;
                    _context.Entry(rf).State = EntityState.Modified;
                    _context.Entry(rd).State = EntityState.Modified;

                    _context.SaveChanges();
                    // Save stock to ERP system.
                    var ERPreponse = await SaveToERPAsync(assign.DocId);

                    //Send Mail
                    //To all users in this repair's flow.
                    Tmail        mail = new Tmail();
                    string       body = "";
                    string       sto  = "";
                    AppUserModel u;
                    RepairModel  repair = _context.BMEDRepairs.Find(assign.DocId);
                    mail.from = new System.Net.Mail.MailAddress(ur.Email); //u.Email
                    _context.BMEDRepairFlows.Where(f => f.DocId == assign.DocId)
                    .ToList()
                    .ForEach(f =>
                    {
                        u    = _context.AppUsers.Find(f.UserId);
                        sto += u.Email + ",";
                    });
                    mail.sto = sto.TrimEnd(new char[] { ',' });

                    mail.message.Subject = "醫工工務智能保修系統[醫工請修案-結案通知]:設備名稱: " + repair.AssetName;
                    body += "<p>表單編號:" + repair.DocId + "</p>";
                    body += "<p>申請日期:" + repair.ApplyDate.ToString("yyyy/MM/dd") + "</p>";
                    body += "<p>申請人:" + repair.UserName + "</p>";
                    body += "<p>財產編號:" + repair.AssetNo + "</p>";
                    body += "<p>設備名稱:" + repair.AssetName + "</p>";
                    //body += "<p>請修地點:" + repair.PlaceLoc + " " + repair.BuildingName + " " + repair.FloorName + " " + repair.AreaName + "</p>";
                    body += "<p>放置地點:" + repair.PlaceLoc + "</p>";
                    body += "<p>故障描述:" + repair.TroubleDes + "</p>";
                    body += "<p>處理描述:" + rd.DealDes + "</p>";
                    body += "<p><a href='http://dms.cch.org.tw/EDIS/Account/Login'" + "?DocId=" + repair.DocId + "&dealType=BMEDRepViews" + ">檢視案件</a></p>";
                    body += "<br/>";
                    body += "<h3>此封信件為系統通知郵件,請勿回覆。</h3>";
                    body += "<br/>";
                    //body += "<h3 style='color:red'>如有任何疑問請聯絡工務部,分機3033或7033。<h3>";
                    mail.message.Body       = body;
                    mail.message.IsBodyHtml = true;
                    mail.SendMail();
                }
                else if (assign.FlowCls == "廢除")
                {
                    rf.Opinions = "[廢除]" + Environment.NewLine + assign.AssignOpn;
                    rf.Status   = "3";
                    rf.Rtt      = DateTime.Now;
                    rf.Rtp      = ur.Id;
                    _context.Entry(rf).State = EntityState.Modified;
                    _context.SaveChanges();
                }
                else
                {
                    //轉送下一關卡
                    rf.Opinions = "[" + assign.AssignCls + "]" + Environment.NewLine + assign.AssignOpn;
                    rf.Status   = "1";
                    rf.Rtt      = DateTime.Now;
                    rf.Rtp      = ur.Id;
                    _context.Entry(rf).State = EntityState.Modified;
                    _context.SaveChanges();
                    //
                    RepairFlowModel flow = new RepairFlowModel();
                    flow.DocId    = assign.DocId;
                    flow.StepId   = rf.StepId + 1;
                    flow.UserId   = assign.FlowUid.Value;
                    flow.UserName = _context.AppUsers.Find(assign.FlowUid.Value).FullName;
                    flow.Status   = "?";
                    flow.Cls      = assign.FlowCls;
                    flow.Rtt      = DateTime.Now;
                    _context.BMEDRepairFlows.Add(flow);
                    _context.SaveChanges();

                    //Send Mail
                    //To user and the next flow user.
                    Tmail        mail = new Tmail();
                    string       body = "";
                    AppUserModel u;
                    RepairModel  repair = _context.BMEDRepairs.Find(assign.DocId);
                    mail.from = new System.Net.Mail.MailAddress(ur.Email); //ur.Email
                    u         = _context.AppUsers.Find(flow.UserId);
                    mail.to   = new System.Net.Mail.MailAddress(u.Email);  //u.Email
                                                                           //mail.cc = new System.Net.Mail.MailAddress("*****@*****.**");
                    mail.message.Subject = "醫工工務智能保修系統[醫工請修案]:設備名稱: " + repair.AssetName;
                    body += "<p>表單編號:" + repair.DocId + "</p>";
                    body += "<p>申請日期:" + repair.ApplyDate.ToString("yyyy/MM/dd") + "</p>";
                    body += "<p>申請人:" + repair.UserName + "</p>";
                    body += "<p>財產編號:" + repair.AssetNo + "</p>";
                    body += "<p>設備名稱:" + repair.AssetName + "</p>";
                    body += "<p>故障描述:" + repair.TroubleDes + "</p>";
                    //body += "<p>請修地點:" + repair.PlaceLoc + " " + repair.BuildingName + " " + repair.FloorName + " " + repair.AreaName + "</p>";
                    body += "<p>放置地點:" + repair.PlaceLoc + "</p>";
                    body += "<p><a href='http://dms.cch.org.tw/EDIS/Account/Login'" + "?docId=" + repair.DocId + "&dealType=BMEDRepEdit" + ">處理案件</a></p>";
                    body += "<br/>";
                    body += "<h3>此封信件為系統通知郵件,請勿回覆。</h3>";
                    body += "<br/>";
                    //body += "<h3 style='color:red'>如有任何疑問請聯絡工務部,分機3033或7033。<h3>";
                    mail.message.Body       = body;
                    mail.message.IsBodyHtml = true;
                    mail.SendMail();
                }

                return(new JsonResult(assign)
                {
                    Value = new { success = true, error = "" }
                });
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }
        }
        public async Task <IActionResult> NextFlow(AssignModel assign)
        {
            var ur = _userRepo.Find(u => u.UserName == this.User.Identity.Name).FirstOrDefault();

            /* 工程師的流程控管 */
            if (assign.Cls == "設備工程師")
            {
                /* 如點選有費用、卻無輸入費用明細 */
                var isCharged = _context.BMEDKeepDtls.Where(d => d.DocId == assign.DocId).FirstOrDefault().IsCharged;
                if (isCharged == "Y")
                {
                    var CheckRepairCost = _context.BMEDKeepCosts.Where(c => c.DocId == assign.DocId).FirstOrDefault();
                    if (CheckRepairCost == null)
                    {
                        throw new Exception("尚未輸入費用明細!!");
                    }
                }
            }

            if (assign.FlowCls == "結案" || assign.FlowCls == "廢除")
            {
                assign.FlowUid = ur.Id;
            }
            if (ModelState.IsValid)
            {
                KeepFlowModel kf = _context.BMEDKeepFlows.Where(f => f.DocId == assign.DocId && f.Status == "?").FirstOrDefault();
                if (assign.FlowCls == "驗收人")
                {
                    if (_context.BMEDKeepEmps.Where(emp => emp.DocId == assign.DocId).Count() <= 0)
                    {
                        throw new Exception("沒有維修工程師紀錄!!");
                    }
                    else if (_context.BMEDKeepDtls.Find(assign.DocId).EndDate == null)
                    {
                        throw new Exception("沒有完工日!!");
                    }
                    if (_context.BMEDKeepDtls.Find(assign.DocId).Result == null)
                    {
                        throw new Exception("保養結果不可空白!!");
                    }
                    if (string.IsNullOrEmpty(_context.BMEDKeepDtls.Find(assign.DocId).InOut))
                    {
                        throw new Exception("保養方式不可空白!!");
                    }
                }
                if (assign.FlowCls == "結案")
                {
                    KeepDtlModel kd = _context.BMEDKeepDtls.Find(assign.DocId);
                    kd.CloseDate             = DateTime.Now;
                    kf.Opinions              = "[" + assign.AssignCls + "]" + Environment.NewLine + assign.AssignOpn;
                    kf.Status                = "2";
                    kf.UserId                = ur.Id;
                    kf.UserName              = _context.AppUsers.Find(ur.Id).FullName;
                    kf.Rtt                   = DateTime.Now;
                    kf.Rtp                   = ur.Id;
                    _context.Entry(kf).State = EntityState.Modified;
                    _context.Entry(kd).State = EntityState.Modified;

                    _context.SaveChanges();
                    // Save stock to ERP system.
                    //var ERPreponse = await SaveToERPAsync(assign.DocId);

                    //Send Mail
                    //To all users in this keep's flow.
                    Tmail        mail = new Tmail();
                    string       body = "";
                    string       sto  = "";
                    AppUserModel u;
                    KeepModel    keep = _context.BMEDKeeps.Find(assign.DocId);
                    mail.from = new System.Net.Mail.MailAddress(ur.Email); //u.Email
                    _context.BMEDKeepFlows.Where(f => f.DocId == assign.DocId)
                    .ToList()
                    .ForEach(f =>
                    {
                        u    = _context.AppUsers.Find(f.UserId);
                        sto += u.Email + ",";
                    });
                    mail.sto = sto.TrimEnd(new char[] { ',' });

                    mail.message.Subject = "醫工工務智能保修系統[醫工保養案-結案通知]:設備名稱: " + keep.AssetName;
                    body += "<p>表單編號:" + keep.DocId + "</p>";
                    body += "<p>送單日期:" + keep.SentDate.Value.ToString("yyyy/MM/dd") + "</p>";
                    body += "<p>申請人:" + keep.UserName + "</p>";
                    body += "<p>財產編號:" + keep.AssetNo + "</p>";
                    body += "<p>設備名稱:" + keep.AssetName + "</p>";
                    body += "<p>放置地點:" + keep.PlaceLoc + "</p>";
                    body += "<p>保養結果:" + kd.Result + "</p>";
                    body += "<p>保養描述:" + kd.Memo + "</p>";
                    body += "<p><a href='http://dms.cch.org.tw/EDIS/Account/Login'" + "?DocId=" + keep.DocId + "&dealType=BMEDKeepViews" + ">檢視案件</a></p>";
                    body += "<br/>";
                    body += "<h3>此封信件為系統通知郵件,請勿回覆。</h3>";
                    body += "<br/>";
                    //body += "<h3 style='color:red'>如有任何疑問請聯絡工務部,分機3033或7033。<h3>";
                    mail.message.Body       = body;
                    mail.message.IsBodyHtml = true;
                    mail.SendMail();
                }
                else if (assign.FlowCls == "廢除")
                {
                    kf.Opinions = "[廢除]" + Environment.NewLine + assign.AssignOpn;
                    kf.Status   = "3";
                    kf.Rtt      = DateTime.Now;
                    kf.Rtp      = ur.Id;
                    _context.Entry(kf).State = EntityState.Modified;
                    _context.SaveChanges();
                }
                else
                {
                    //轉送下一關卡
                    kf.Opinions = "[" + assign.AssignCls + "]" + Environment.NewLine + assign.AssignOpn;
                    kf.Status   = "1";
                    kf.Rtt      = DateTime.Now;
                    kf.Rtp      = ur.Id;
                    _context.Entry(kf).State = EntityState.Modified;
                    _context.SaveChanges();
                    //
                    KeepFlowModel flow = new KeepFlowModel();
                    flow.DocId    = assign.DocId;
                    flow.StepId   = kf.StepId + 1;
                    flow.UserId   = assign.FlowUid.Value;
                    flow.UserName = _context.AppUsers.Find(assign.FlowUid.Value).FullName;
                    flow.Status   = "?";
                    flow.Cls      = assign.FlowCls;
                    flow.Rtt      = DateTime.Now;
                    _context.BMEDKeepFlows.Add(flow);
                    _context.SaveChanges();

                    //Send Mail
                    //To user and the next flow user.
                    Tmail        mail = new Tmail();
                    string       body = "";
                    AppUserModel u;
                    KeepModel    keep = _context.BMEDKeeps.Find(assign.DocId);
                    mail.from = new System.Net.Mail.MailAddress(ur.Email); //ur.Email
                    u         = _context.AppUsers.Find(flow.UserId);
                    mail.to   = new System.Net.Mail.MailAddress(u.Email);  //u.Email
                                                                           //mail.cc = new System.Net.Mail.MailAddress("*****@*****.**");
                    mail.message.Subject = "醫工工務智能保修系統[醫工保養案]:設備名稱: " + keep.AssetName;
                    body += "<p>表單編號:" + keep.DocId + "</p>";
                    body += "<p>送單日期:" + keep.SentDate.Value.ToString("yyyy/MM/dd") + "</p>";
                    body += "<p>申請人:" + keep.UserName + "</p>";
                    body += "<p>財產編號:" + keep.AssetNo + "</p>";
                    body += "<p>設備名稱:" + keep.AssetName + "</p>";
                    body += "<p>放置地點:" + keep.PlaceLoc + "</p>";
                    body += "<p><a href='http://dms.cch.org.tw/EDIS/Account/Login'" + "?docId=" + keep.DocId + "&dealType=BMEDKeepEdit" + ">處理案件</a></p>";
                    body += "<br/>";
                    body += "<h3>此封信件為系統通知郵件,請勿回覆。</h3>";
                    body += "<br/>";
                    //body += "<h3 style='color:red'>如有任何疑問請聯絡工務部,分機3033或7033。<h3>";
                    mail.message.Body       = body;
                    mail.message.IsBodyHtml = true;
                    mail.SendMail();
                }

                return(new JsonResult(assign)
                {
                    Value = new { success = true, error = "" }
                });
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }
        }
Exemple #28
0
        // GET: BMED/Keep/Create
        public IActionResult Create()
        {
            KeepModel    r  = new KeepModel();
            AppUserModel ur = _context.AppUsers.Where(u => u.UserName == this.User.Identity.Name).FirstOrDefault();

            r.Email = ur.Email == null ? "" : ur.Email;
            DepartmentModel d = _context.Departments.Find(ur.DptId);

            r.DocId       = GetID();
            r.UserId      = ur.Id;
            r.UserName    = ur.FullName;
            r.UserAccount = ur.UserName;
            r.SentDate    = DateTime.Now;
            r.DptId       = d == null ? "" : d.DptId;
            r.Company     = d == null ? "" : d.Name_C;
            r.AccDpt      = d == null ? "" : d.DptId;
            r.AccDptName  = d == null ? "" : d.Name_C;
            r.Ext         = ur.Ext == null ? "" : ur.Ext;
            r.CheckerId   = ur.Id;
            //
            _context.BMEDKeeps.Add(r);
            _context.SaveChanges();

            List <SelectListItem> listItem = new List <SelectListItem>();
            List <SelectListItem> AccDpt   = new List <SelectListItem>();

            _context.Departments.ToList()
            .ForEach(dp =>
            {
                AccDpt.Add(new SelectListItem
                {
                    Value    = dp.DptId,
                    Text     = dp.Name_C,
                    Selected = false
                });
            });
            ViewData["AccDpt"] = AccDpt;

            //
            List <AssetModel> alist = null;

            if (ur.DptId != null)
            {
                alist = _context.BMEDAssets.Where(at => at.AccDpt == ur.DptId)
                        .Where(at => at.DisposeKind != "報廢").ToList();
            }
            else if (ur.VendorId > 0)
            {
                string s = Convert.ToString(ur.VendorId);
                alist = _context.BMEDAssets.Where(at => at.AccDpt == s)
                        .Where(at => at.DisposeKind != "報廢").ToList();
            }

            /* 擷取該使用者單位底下所有人員 */
            var dptUsers = _context.AppUsers.Where(a => a.DptId == ur.DptId).ToList();
            List <SelectListItem> dptMemberList = new List <SelectListItem>();

            foreach (var item in dptUsers)
            {
                dptMemberList.Add(new SelectListItem
                {
                    Text  = item.FullName,
                    Value = item.Id.ToString()
                });
            }
            ViewData["DptMembers"] = new SelectList(dptMemberList, "Value", "Text");

            return(View(r));
        }
        public IActionResult NextFlow(DelivFlowModel DelivFlow)
        {
            if (ModelState.IsValid)
            {
                // Get Login User's details.
                var ur = _userRepo.Find(usr => usr.UserName == User.Identity.Name).FirstOrDefault();

                if (DelivFlow.SelOpin == "其他" && string.IsNullOrEmpty(DelivFlow.Opinions))
                {
                    throw new Exception("請填寫意見欄!!");
                }
                DelivFlowModel rf = _context.DelivFlows.Where(df => df.DocId == DelivFlow.DocId)
                                                       .Where(df => df.Status == "?").ToList().FirstOrDefault();
                if (rf == null)
                {
                    throw new Exception("查無流程!");
                }
                if (rf.Cls == "得標廠商")
                {
                    if (_context.BMEDAssets.Where(a => a.Docid == DelivFlow.DocId).Count() <= 0)
                    {
                        throw new Exception("沒有設備紀錄! 請新增設備!");
                    }
                }
                List<DelivFlowModel> rflist = _context.DelivFlows.Where(df => df.DocId == DelivFlow.DocId).ToList();
                DeliveryModel r = _context.Deliveries.Find(DelivFlow.DocId);
                AppUserModel u;
                Tmail mail;
                string body = "";
                if (DelivFlow.Cls == "結案")
                {
                    string sto = "";
                    //KeepDtl rd = db.KeepDtls.Find(KeepFlow.Docid);
                    rf.Opinions = DelivFlow.SelOpin + Environment.NewLine + DelivFlow.Opinions;
                    rf.Status = "2";
                    rf.Rtt = DateTime.Now;
                    rf.Rtp = ur.Id;
                    _context.Entry(rf).State = EntityState.Modified;
                    _context.SaveChanges();
                    //
                    mail = new Tmail();
                    u = _context.AppUsers.Find(ur.Id);
                    mail.from = new System.Net.Mail.MailAddress(u.Email); //u.Email
                    foreach (DelivFlowModel rr in rflist)
                    {
                        u = _context.AppUsers.Find(rr.UserId);
                        sto += u.Email + ",";
                    }
                    mail.sto = sto.TrimEnd(new char[] { ',' });
                    //mail.cc = new System.Net.Mail.MailAddress("*****@*****.**");
                    mail.message.Subject = "醫療儀器管理資訊系統[驗收案-結案通知]:採購案號: " + r.PurchaseNo;
                    body += "<p>申請人:" + r.UserName + "</p>";
                    body += "<p>合約號碼:" + r.ContractNo + "</p>";
                    body += "<p>採購案號:" + r.PurchaseNo + "</p>";
                    body += "<p><a href='http://dms.cch.org.tw/MvcMedEngMgr'>前往網站檢視</a></p>";
                    body += "<br/>";
                    body += "<h3>this is a inform letter from system manager.Do not reply for it.</h3>";
                    mail.message.Body = body;
                    mail.message.IsBodyHtml = true;
                    //mail.SendMail();
                    return new JsonResult(DelivFlow)
                    {
                        Value = new { success = true, error = "" },
                    };
                }
                DelivFlow.StepId = rf.StepId + 1;
                DelivFlow.Rtt = DateTime.Now;
                switch (DelivFlow.Cls)
                {
                    case "申請者":
                        DelivFlow.UserId = r.UserId;
                        break;
                }
                DelivFlow.Status = "?";
                u = _context.AppUsers.Find(DelivFlow.UserId);
                DelivFlow.Role = roleManager.GetRolesForUser(u.Id).FirstOrDefault();
                rf.Opinions = DelivFlow.SelOpin + Environment.NewLine + DelivFlow.Opinions;
                rf.Status = "1";
                rf.Rtp = ur.Id;
                DelivFlow.Opinions = null;
                _context.Entry(rf).State = EntityState.Modified;
                _context.DelivFlows.Add(DelivFlow);
                _context.SaveChanges();
                //
                mail = new Tmail();
                body = "";
                u = _context.AppUsers.Find(ur.Id);
                mail.from = new System.Net.Mail.MailAddress(u.Email); //u.Email
                u = _context.AppUsers.Find(DelivFlow.UserId);
                mail.to = new System.Net.Mail.MailAddress(u.Email); //u.Email
                //mail.cc = new System.Net.Mail.MailAddress("*****@*****.**");
                mail.message.Subject = "醫療儀器管理資訊系統[驗收案]:採購案號: " + r.PurchaseNo;
                body += "<p>申請人:" + r.UserName + "</p>";
                body += "<p>合約號碼:" + r.ContractNo + "</p>";
                body += "<p>採購案號:" + r.PurchaseNo + "</p>";
                body += "<p><a href='http://dms.cch.org.tw/MvcMedEngMgr'>處理案件</a></p>";
                body += "<br/>";
                body += "<p>若有任何問題,請與驗收工程師(" + _context.AppUsers.Find(r.EngId).FullName + ")聯絡</p>";
                body += "<h3>this is a inform letter from system manager.Do not reply for it.</h3>";
                mail.message.Body = body;
                mail.message.IsBodyHtml = true;
                //mail.SendMail();
                return new JsonResult(DelivFlow)
                {
                    Value = new { success = true, error = "" }
                };
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }

        }
        public async Task <IActionResult> Upload(AttainFileModel attainFile)
        {
            var  ur   = _userRepo.Find(u => u.UserName == this.User.Identity.Name).FirstOrDefault();
            long size = attainFile.Files.Sum(f => f.Length);

            // full path to file in temp location
            var filePath = Path.GetTempFileName();

            if (ModelState.IsValid)
            {
                try
                {
                    string s = "/Files/BMED";
//#if DEBUG
//                    s = "/App_Data";
//#endif
                    switch (attainFile.DocType)
                    {
                    case "0":
                        s += "/Budget/";
                        break;

                    case "1":
                        s += "/Repair/";
                        break;

                    case "2":
                        s += "/Keep/";
                        break;

                    case "3":
                        s += "/BuyEvaluate/";
                        break;

                    case "4":
                        s += "/Delivery/";
                        break;

                    case "5":
                        s += "/Asset/";
                        break;
                    }
                    var i = _context.BMEDAttainFiles
                            .Where(a => a.DocType == attainFile.DocType)
                            .Where(a => a.DocId == attainFile.DocId).ToList();
                    attainFile.SeqNo = i.Count == 0 ? 1 : i.Select(a => a.SeqNo).Max() + 1;

                    string WebRootPath = _hostingEnvironment.WebRootPath;
                    string path        = Path.Combine(WebRootPath + s + attainFile.DocId + "_"
                                                      + attainFile.SeqNo.ToString() + Path.GetExtension(attainFile.Files[0].FileName));
                    // Upload files.
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await attainFile.Files[0].CopyToAsync(stream);
                    }

                    // Save file details to AttainFiles table.
                    string filelink = attainFile.DocId + "_"
                                      + attainFile.SeqNo.ToString() + Path.GetExtension(attainFile.Files[0].FileName);
                    switch (attainFile.DocType)
                    {
                    case "0":
                        attainFile.FileLink = "Budget/" + filelink;
                        break;

                    case "1":
                        attainFile.FileLink = "Repair/" + filelink;
                        break;

                    case "2":
                        attainFile.FileLink = "Keep/" + filelink;
                        break;

                    case "3":
                        attainFile.FileLink = "BuyEvaluate/" + filelink;
                        break;

                    case "4":
                        attainFile.FileLink = "Delivery/" + filelink;
                        break;

                    case "5":
                        attainFile.FileLink = "Asset/" + filelink;
                        break;
                    }
                    attainFile.Rtt = DateTime.Now;
                    attainFile.Rtp = ur.Id;
                    _context.BMEDAttainFiles.Add(attainFile);
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            else
            {
                string msg = "";
                foreach (var error in ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors))
                {
                    msg += error.ErrorMessage + Environment.NewLine;
                }
                throw new Exception(msg);
            }

            TempData["SendMsg"] = "上傳成功";
            if (attainFile.DocType == "2")
            {
                return(RedirectToAction("Edit", "Keep", new { area = "BMED", id = attainFile.DocId }));
            }
            return(RedirectToAction("Edit", "Repair", new { area = "BMED", id = attainFile.DocId }));

            //return new JsonResult(attainFile)
            //{
            //    Value = new { success = true, error = "" },
            //};
        }