demo20230512/Areas/admin/Controllers/ParameterDatabaseController.cs

449 lines
21 KiB
C#
Raw Normal View History

2023-05-12 10:20:28 +08:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using Weee.Areas.Admin.Supports;
using Weee.Areas.Admin.ViewModels;
using Weee.Models.Paramemter;
using Weee.DAL;
using System.Net;
using PagedList;
using System.Threading;
using Weee.Models;
namespace Weee.Areas.Admin.Controllers
{
public class ParameterDatabaseController : AdminControllerBase
{
private string fileSavedPath = WebConfigurationManager.AppSettings["UploadPath"];
public ParameterDatabaseController(WeeeDataContext db)
: base(db)
{
}
public ActionResult Index(int simaproVersionID = 0, int simaproCategoryID = 0
, int simaproTypeID = 0, int page = 1, string searchString = null)
{
var simaproViewModel = new SimaproIndexViewModel();
if (db.SimaproVersions.ToList().Count() == 0)
{
ViewBag.errorMsg = "Please Import Data";
return View();
}
simaproViewModel.SimaproVersions = db.SimaproVersions.Where(x => x.IsActive == true)
.OrderByDescending(x=>x.ID).ToList();
//simaproViewModel.SimaproVersion = simaproVersionID == 0 ? db.SimaproVersions.First() : db.SimaproVersions.Find(simaproVersionID);
simaproViewModel.SimaproVersion = simaproVersionID == 0 ? new SimaproVersion() : db.SimaproVersions.Find(simaproVersionID);
simaproViewModel.SimaproParameterCategories = simaproViewModel.SimaproVersion.Categories.ToList();
//DL-39 begin
//simaproViewModel.SimaproParameterCategory = simaproCategoryID == 0 ? simaproViewModel.SimaproParameterCategories.First() : db.SimaproCategories.Find(simaproCategoryID);//DL-39
if (simaproCategoryID != 0)
{
var categories = simaproViewModel.SimaproVersion.Categories.ToList();
foreach (var itm in categories)
{
if (itm.ID == simaproCategoryID)
{
simaproViewModel.SimaproParameterCategory = db.SimaproCategories.Find(simaproCategoryID);
break;
}
}
if (simaproViewModel.SimaproParameterCategory == null)
{
//DL-77
if (simaproViewModel.SimaproVersion.Categories.ToList().Count > 0)
{
simaproViewModel.SimaproParameterCategory = simaproViewModel.SimaproVersion.Categories.ToList().First();
}
else
{
simaproViewModel.SimaproParameterCategory = null;
}
//simaproViewModel.SimaproParameterCategory = simaproViewModel.SimaproVersion.Categories.ToList().First();
}
}
else
{
simaproViewModel.SimaproParameterCategory = simaproViewModel.SimaproParameterCategories.Count > 0 ? simaproViewModel.SimaproParameterCategories.First() : null; //DL-77
//simaproViewModel.SimaproParameterCategory = simaproViewModel.SimaproParameterCategories.First();//DL-77
}
//end
simaproViewModel.SimaproParameterTypes = simaproViewModel.SimaproParameterCategory !=null? simaproViewModel.SimaproParameterCategory.SubTypes.ToList() : null; //DL-77
//simaproViewModel.SimaproParameterTypes = simaproViewModel.SimaproParameterCategory.SubTypes.ToList();//DL-77
var count = simaproViewModel.SimaproParameterCategory != null ? simaproViewModel.SimaproParameterCategory.SubTypes.ToList().Count() : 0; //DL-77
//var count = simaproViewModel.SimaproParameterCategory.SubTypes.ToList().Count(); //DL-77
if (simaproTypeID == 0)
{
if (count > 0)
{
//DL-77 begin
simaproViewModel.SimaproParameterType = simaproViewModel.SimaproParameterCategory != null ? simaproViewModel.SimaproParameterCategory.SubTypes.ToList().First() : null;
ViewBag.simaproCategoryID = simaproViewModel.SimaproParameterType != null ? simaproViewModel.SimaproParameterType.ID : 0;
//simaproViewModel.SimaproParameterType = simaproViewModel.SimaproParameterCategory.SubTypes.ToList().First();
//ViewBag.simaproCategoryID = simaproViewModel.SimaproParameterType.ID;
//DL-77 end
}
}
else
{
if (count > 0)
{
foreach (var type in simaproViewModel.SimaproParameterTypes)
{
if (type.ID == simaproTypeID)
{
simaproViewModel.SimaproParameterType = type;
break;
}
}
if (simaproViewModel.SimaproParameterType == null)
{
simaproViewModel.SimaproParameterType = simaproViewModel.SimaproParameterCategory != null ? simaproViewModel.SimaproParameterCategory.SubTypes.ToList().FirstOrDefault() : null;//DL-77
//simaproViewModel.SimaproParameterType = simaproViewModel.SimaproParameterCategory.SubTypes.ToList().FirstOrDefault();//DL-77
}
}
//simaproViewModel.SimaproParameterType = db.SimaproTypes.Find(simaproTypeID);
}
//simaproViewModel.SimaproParameterType = simaproTypeID == 0 ? simaproViewModel.SimaproParameterCategory.SubTypes.ToList().First() : db.SimaproTypes.Find(simaproTypeID);
//end
if (searchString != null && searchString.Trim()!="")
{
searchString = searchString.Trim();
simaproViewModel.parameters = db.SimaproParameters
.Where(x => x.Remark.Contains(searchString) ||
x.Encoding.Contains(searchString) ||
x.Database.Contains(searchString))
.Where(x=>x.Type.Category.VersionID==simaproVersionID)
.Where(x=>x.Type.CategoryID == simaproCategoryID)
.OrderBy(x=>x.Encoding)
.ToPagedList(page, 10); //DL-39 add categoryid to where clauseS
}
else if (simaproViewModel.SimaproParameterType != null)
{
simaproViewModel.parameters = simaproViewModel.SimaproParameterType.Parameters
.OrderBy(x=>x.Encoding)
.ToPagedList(page, 10);
}
//simaproViewModel.parameters = simaproViewModel.SimaproParameterType.Parameters.ToPagedList(1, 10);//39
ViewBag.searchString = searchString;
ViewBag.simaproVersionID = simaproVersionID;
ViewBag.simaproCategoryID = simaproCategoryID;
ViewBag.simaproTypeID = simaproTypeID;
ViewBag.page = page;
return View(simaproViewModel);
}
public ActionResult Edit(int simaproParameterID = 0)
{
if (simaproParameterID == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var simaproParameter = db.SimaproParameters.Find(simaproParameterID);
if (simaproParameter == null) return HttpNotFound();
return View(simaproParameter);
}
[HttpPost]
[Weee.Filter.MvcLog("Edit", "SimaproDatabase")]
public ActionResult Edit(SimaproParameter simaproParameter, int simaproParameterID = 0)
{
var updatedSimaproParameter = db.SimaproParameters.Find(simaproParameterID);
updatedSimaproParameter.DisplayNameTW = simaproParameter.DisplayNameTW;
updatedSimaproParameter.DisplayNameEN = simaproParameter.DisplayNameEN;
updatedSimaproParameter.DisplayNameCN = simaproParameter.DisplayNameCN;
db.SaveChanges();
return RedirectToAction("Edit", new { simaproParameterID = simaproParameterID });
}
public ActionResult EditSimaproVersion(int simaproVersionID = 0)
{
if (simaproVersionID == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var simaproVersion = db.SimaproVersions.Find(simaproVersionID);
if (simaproVersion == null) return HttpNotFound();
var versions = db.SimaproVersions;
var qry = versions
.Where(x => x.ID == simaproVersionID)
.Select(x => x.Categories
.SelectMany(y => y.SubTypes.
SelectMany(z => z.Parameters)).Count());
ViewBag.ParameterCount = qry.First().ToString();
return View(simaproVersion);
}
[HttpPost]
[Weee.Filter.MvcLog("EditSimaproVersion", "SimaproDatabase")]
public ActionResult EditSimaproVersion(SimaproVersion simaproVersion, string count)
{
ViewBag.ParameterCount = count;
if (string.IsNullOrWhiteSpace(simaproVersion.Version))
{
ViewBag.errorMsg = "請填寫版本描述";
return View("EditSimaproVersion", simaproVersion);
}
var isVersionExist = db.SimaproVersions.Where(x => x.ID != simaproVersion.ID && x.Version == simaproVersion.Version).AsEnumerable().Any();
if (isVersionExist)
{
ViewBag.errorMsg = "版本描述不得重複";
return View("EditSimaproVersion", simaproVersion);
}
if (string.IsNullOrWhiteSpace(simaproVersion.paraSource))
{
ViewBag.errorMsg = "請填寫係數來源";
return View("EditSimaproVersion", simaproVersion);
}
if (string.IsNullOrWhiteSpace(simaproVersion.Description))
{
ViewBag.errorMsg = "請填寫描述";
return View("EditSimaproVersion", simaproVersion);
}
var updatedSimaproVersion = db.SimaproVersions.Find(simaproVersion.ID);
updatedSimaproVersion.Version = simaproVersion.Version;
updatedSimaproVersion.Description = simaproVersion.Description;
updatedSimaproVersion.paraSource = simaproVersion.paraSource;
db.SaveChanges();
return RedirectToAction("Import");
}
public ActionResult Detail(int simaproParameterID = 0)
{
if (simaproParameterID == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var simaproParameter = db.SimaproParameters.Find(simaproParameterID);
if (simaproParameter == null) return HttpNotFound();
return View(simaproParameter);
}
public ActionResult ToggleStatus(int id)
{
var v = db.SimaproVersions.Find(id);
v.IsActive = !v.IsActive;
v.IsDeleteable = false;
db.SaveChanges();
return RedirectToAction("import");
}
public ActionResult DeleteVersion(int id)
{
//delete lca before delete simapro parameters
//var ids = db.SimaproParameters.Where(x => x.Type.Category.VersionID == id).Select(x=>x.ID).ToList();
//var lcaIDs = db.ProductLCAProductSurveyForm_Material.Where(x => ids.Contains((int)x.ParameterID)).Select(x=>x.LCAID).ToList();
var lcaIDs = db.ProductLCAProductSurveyForm_Material.Join(db.SimaproParameters, x => x.ParameterID, sp => sp.ID, (x, sp) => new { versionID = sp.Type.Category.VersionID, LCAID = x.LCAID }).Where(x => x.versionID == id).Select(x => x.LCAID).Distinct().ToList();
var lcaIDs2 = db.ProductLCAProductSurveyForm_Material.Join(db.SimaproCategories, x => x.ParameterTypeID, sc => sc.ID, (x, sc) => new { versionID = sc.VersionID, LCAID = x.LCAID }).Where(x => x.versionID == id).Select(x => x.LCAID).Distinct().ToList();
var totalLcaIDs = lcaIDs.Union(lcaIDs2).ToList();
for (int i = 0; i < totalLcaIDs.Count; i++)
{
var lcaID = totalLcaIDs[i];
LCA lca = db.LCAs.Find(lcaID);
if (lca is OrganizationLCA)
{
OrganizationLCA olca = lca as OrganizationLCA;
var qry4 = (from a in db.OrganizationOtherCompound
where a.LCAID == olca.ID
select a);
db.OrganizationOtherCompound.RemoveRange(qry4);
olca = db.OrganizationLCAs.Find(lcaID);
db.OrganizationLCAs.Remove(olca);
}
else if (lca is ProductLCA)
{
ProductLCA plca = lca as ProductLCA;
var qry1 = db.ProductLCAFabSurveyResults.Find(lcaID);
if (qry1 != null)
db.ProductLCAFabSurveyResults.Remove(qry1);
var qry3 = (from a in db.ProductLCAReplyRequests
join b in db.ProductLCAProductSurveyForm_Material on a.ID equals b.ID
where b.LCAID == lcaID
select a);
db.ProductLCAReplyRequests.RemoveRange(qry3);
var qry2 = db.ProductLCAProductSurveyForm_Material.Where(x => x.LCAID == lcaID);
db.ProductLCAProductSurveyForm_Material.RemoveRange(qry2);
var qry5 = db.ProductLCAFabSurveyForm_Transport.Where(x => x.LCAID == lcaID);
db.ProductLCAFabSurveyForm_Transport.RemoveRange(qry5);
var qry6 = db.ProductLCAFabSurveyForm_OtherCompound.Where(x => x.LCAID == lcaID);
db.ProductLCAFabSurveyForm_OtherCompound.RemoveRange(qry6);
var qry7 = db.ProductLCAFabSurveyForm_Wastes.Where(x => x.LCAID == lcaID);
db.ProductLCAFabSurveyForm_Wastes.RemoveRange(qry7);
var qry8 = db.ProductLCAFabSurveyForm_WasteTransport.Where(x => x.LCAID == lcaID);
db.ProductLCAFabSurveyForm_WasteTransport.RemoveRange(qry8);
var qry9 = db.ProductLCAFabSurveyForm_WaterUsage.Where(x => x.LCAID == lcaID);
db.ProductLCAFabSurveyForm_WaterUsage.RemoveRange(qry9);
var qry10 = db.ProductLCAAbandonedStages.Where(x => x.ID == lcaID);
db.ProductLCAAbandonedStages.RemoveRange(qry10);
var qry11 = db.ProductLCAReplyRequests.Where(x => x.RepliedLCAID == lcaID);
db.ProductLCAReplyRequests.RemoveRange(qry11);
plca = db.ProductLCAs.Find(lcaID);
db.ProductLCAs.Remove(plca);
}
db.LCAs.Remove(lca);
db.SaveChanges();
}
var v = db.SimaproVersions.Find(id);
db.SimaproVersions.Remove(v);
db.SaveChanges();
return RedirectToAction("import");
}
public ActionResult Import()
{
try
{
ViewBag.errorMsg = TempData["errorMsg"];
ViewBag.successMsg = TempData["successMsg"];
var versions = db.SimaproVersions.OrderByDescending(x=>x.ID);
var qry = versions
.Select(x => x.Categories
.SelectMany(y => y.SubTypes.
SelectMany(z => z.Parameters)).Count());
var versionsList = versions.ToList();
ViewBag.ParameterCounts = qry.ToList();
ViewBag.History = versionsList;
ViewBag.version = DateTime.Now.ToString("yyMMddHHmmss");
List<int> relatedCount = new List<int>();
var relatedCountQuery = db.ProductLCAProductSurveyForm_Material.Join(db.SimaproParameters, x => x.ParameterID, sp => sp.ID, (x, sp) => new { versionID = sp.Type.Category.VersionID, LCAID = x.LCAID });
var relatedCountQuery2 = db.ProductLCAProductSurveyForm_Material.Join(db.SimaproCategories, x => x.ParameterTypeID, sc => sc.ID, (x, sc) => new { versionID = sc.VersionID, LCAID = x.LCAID });
for (int i = 0; i < versionsList.Count; i++)
{
var versionID = versionsList[i].ID;
var count = relatedCountQuery.Where(x => x.versionID == versionID).Select(x => x.LCAID).Distinct().Count();
var count2 = relatedCountQuery2.Where(x => x.versionID == versionID).Select(x => x.LCAID).Distinct().Count();
relatedCount.Add((count + count2));
}
ViewBag.relatedCount = relatedCount;
}
catch (Exception ex)
{
string err = ex.Message;
Thread.Sleep(0);
}
return View();
}
[HttpPost]
[Weee.Filter.MvcLog("Import", "SimaproDatabase")]
public ActionResult Upload(string description = "", string parasource = "", string version="")
{
if (Request == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
HttpPostedFileBase file = Request.Files["UploadedFile"];
if (!this.UploadFileIsValid(file))
return RedirectToAction("Import");
if (version == "")
{
TempData["errorMsg"] = "請填寫版本描述";
return RedirectToAction("Import");
}
var isVersionExist = db.SimaproVersions.Where(x =>x.Version == version).AsEnumerable().Any();
if (isVersionExist)
{
TempData["errorMsg"] = "版本描述不得重複";
return RedirectToAction("Import");
}
if (parasource == "")
{
TempData["errorMsg"] = "請填寫係數來源";
return RedirectToAction("Import");
}
if (description == "")
{
TempData["errorMsg"] = "請填寫描述";
return RedirectToAction("Import");
}
try
{
var fileName = this.FileUploadHandler(file);
//var version2 = DateTime.Now.ToString("yyyyMMdd_") + Path.GetFileNameWithoutExtension(file.FileName).Substring(0, Math.Min(10, Path.GetFileNameWithoutExtension(file.FileName).Length));
description += $"\n({Path.GetFileNameWithoutExtension(file.FileName)})";
this.ImportExcelToDatabase(fileName, version, description, parasource);
TempData["successMsg"] = "File Import Success!";
}
catch (Exception exception)
{
if (exception.InnerException != null &&
exception.InnerException.Message.CompareTo(
"External table is not in the expected format.")
== 0)
{
TempData["errorMsg"] = "請使用*.xlsx檔案";
}
else
TempData["errorMsg"] = exception.Message;
return RedirectToAction("Import");
}
return RedirectToAction("Import");
}
private string FileUploadHandler(HttpPostedFileBase file)
{
string result;
if (file == null) { throw new ArgumentNullException("file", "Upload failed: No File!"); }
if (file.ContentLength <= 0) { throw new InvalidOperationException("Upload failed: There is no content in this file"); }
string virtualBaseFilePath = Url.Content(fileSavedPath);
string filePath = HttpContext.Server.MapPath(virtualBaseFilePath);
if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); }
string fileName = string.Concat(DateTime.Now.ToString("yyyyMMddHHmmssfff"), Path.GetExtension(file.FileName).ToLower());
string fullFilePath = Path.Combine(Server.MapPath(fileSavedPath), fileName);
file.SaveAs(fullFilePath);
result = fileName;
return result;
}
private void ImportExcelToDatabase(string savedFileName, string version, string description, string parasource)
{
var fileName = string.Concat(Server.MapPath(fileSavedPath), "/", savedFileName);
var excelImporter = new SimaproExcelImporter(fileName);
excelImporter.InsertSimaproData(version, description, parasource);
excelImporter.DeleteExcelFile(fileName);
}
private bool UploadFileIsValid(HttpPostedFileBase file)
{
if (file == null)
{
TempData["errorMsg"] = "Please upload the file";
return false;
}
if (file.ContentLength <= 0)
{
TempData["errorMsg"] = "Please upload the file";
return false;
}
string fileExistName = Path.GetExtension(file.FileName).ToLower();
if (!fileExistName.Equals(".xls", StringComparison.OrdinalIgnoreCase) &&
!fileExistName.Equals(".xlsx", StringComparison.OrdinalIgnoreCase) &&
!fileExistName.Equals(".csv", StringComparison.OrdinalIgnoreCase))
{
TempData["errorMsg"] = "Please upload xls or xlsx format file";
return false;
}
return true;
}
}
}