demo20230512/Service/ProductLCA/WeeeSheetDataService.cs
2023-05-12 10:20:28 +08:00

516 lines
27 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Weee.DAL;
using Weee.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Weee.Models.Paramemter;
using Qcarbon.ViewModels.DTO.withFactor;
using System.Globalization;
using Qcarbon.ExcelImportExport.LcaOrganization.excelImportLCAdata;
using System.Net;
using Microsoft.WindowsAzure.Storage.Table.Queryable;
using Qcarbon.ViewModels.ExcelImportExport.LcaOrganization.excelExportOrgLCAdata;
using Weee.Models.Survey_form_metadata;
namespace Weee.Service
{
public class WeeeSheetDataService : WeeeLCADataService
{
public WeeeSheetDataService(WeeeDataContext db)
: base(db)
{
}
#region
// if the sheet is monthly data : page , search page size do not care
public IQueryable<TEntity> GetSheet<TEntity>(int LCAID) where TEntity : class, SheetData
{
if (!AuthorizedLCAs.Contains(LCAID))
throw new Exception("not authorized");
IQueryable<TEntity> ret= _db.Set<TEntity>().Where(x => x.LCAID == LCAID)
.OrderByDescending(x => x.ID);
return ret;
}
public IEnumerable<SheetData> SaveSheet(IEnumerable<SheetData> ToBeSave)
{
foreach (var item in ToBeSave)
{
if (!AuthorizedLCAs.Contains(item.LCAID)) throw new Exception("not authorized");
var entry = _db.Entry(item);
if (item.ID == 0)
{
entry.State = EntityState.Added;
}
else
{
entry.State = EntityState.Modified;
}
}
_db.SaveChanges();
return ToBeSave;
}
public SheetHeader GetSheetHeader(int LCAID, Categories cate)
{
if (!AuthorizedLCAs.Contains(LCAID)) throw new Exception("not authorized");
var sheetheader = _db.SheetHeaders.Find(new object[] { LCAID, cate });
if (sheetheader == null)
return new SheetHeader();
else
return _db.SheetHeaders.Find(new object[]{LCAID,cate});
}
public void SaveSheetHeader(SheetHeader header)
{
if (!AuthorizedLCAs.Contains(header.LCAID)) throw new Exception("not authorized");
var a = _db.SheetHeaders.Find(new object[]{header.LCAID,header.Category});
if (a == null) _db.SheetHeaders.Add(header);
else
{
_db.Entry(a).State = EntityState.Detached;
_db.Entry(header).State = EntityState.Modified;
}
_db.SaveChanges();
}
public SheetData SaveSheetItem(SheetData toBeSave)
{
if (!AuthorizedLCAs.Contains(toBeSave.LCAID)) throw new Exception("not authorized");
var entry = _db.Entry(toBeSave);
if (toBeSave.ID == 0)
{
entry.State = EntityState.Added;
}
else
{
entry.State = EntityState.Modified;
entry.Property(x => x.LCAID).IsModified = false;
}
_db.SaveChanges();
return toBeSave;
}
public void DeleteSheet<TEntity>(int LCAID) where TEntity : class, SheetData
{
var LCA = GetLCA(LCAID);
if (LCA.Status != LCAStatus.New
&& LCA.Status != LCAStatus.Processing
&& LCA.Status != LCAStatus.Rejected) throw new Exception("Business logic error , should not delete sheet data in this status: " + LCA.Status.ToString());
var entries = _db.Set<TEntity>().Where(x => x.LCAID == LCAID);
foreach (var entry in entries)
{
var ToBeDelete = _db.Entry(entry);
ToBeDelete.State = EntityState.Deleted;
}
_db.SaveChanges();
}
public void DeleteMaterials(int? LCAID,int? ID, MaterialType? MType)
{
if (LCAID !=null && !AuthorizedLCAs.Contains((int)LCAID)) throw new Exception("Not authroize");
var mats = _db.ProductLCAProductSurveyForm_Material.Where(x=>true);
if (LCAID != null)
mats = mats.Where(x => x.LCAID == LCAID);
if (ID != null)
mats = mats.Where(x => x.ID == ID);
if (MType != null)
mats = mats.Where(x => x.MaterialType == MType);
var materialIDs = mats.Select(x => x.ID).ToList();
var materialComposites = _db.ProductLCASurveyForm_MaterialComposite.Where(x => materialIDs.Contains((int)x.materialID));
_db.ProductLCASurveyForm_MaterialComposite.RemoveRange(materialComposites);
_db.ProductLCAProductSurveyForm_Material.RemoveRange(mats);
_db.SaveChanges();
}
public void UpdateMaterialComposites(int MaterialID, List<ProductLCASurveyForm_MaterialComposite> composites)
{
if (composites == null)
return;
var compositesIDs = composites.Select(x => x.ID).ToList();
var deletes = _db.ProductLCASurveyForm_MaterialComposite.Where(x => x.materialID == MaterialID && !compositesIDs.Contains(x.ID));
_db.ProductLCASurveyForm_MaterialComposite.RemoveRange(deletes);
foreach (var item in composites)
{
var entry = _db.Entry(item);
if (item.ID == 0)
{
entry.State = EntityState.Added;
}
else
{
entry.State = EntityState.Modified;
}
}
_db.SaveChanges();
}
public void DeleteSheetItem<TEntity>(int ID) where TEntity : class, SheetData
{
var entry = _db.Set<TEntity>().Where(x => x.ID == ID).Single();
var LCA = GetLCA(entry.LCAID);
if (LCA.Status != LCAStatus.New && LCA.Status != LCAStatus.Processing) throw new Exception("Business logic error , should not delete sheet data in this status: " + LCA.Status.ToString());
var ToBeDelete = _db.Entry(entry);
ToBeDelete.State = EntityState.Deleted;
_db.SaveChanges();
}
#endregion
public IQueryable<refrigerantWithFactor> getRefrigerantWithFactor(int LCAID)
{
//var qry = (from a in _db.LCACommonSurveyForm_Refrigerant
// join b in _db.Parameters on a.ParameterID equals b.ID
// join c in _db.Parameters on a.ParameterID2 equals c.ID
// where a.LCAID == LCAID
// select new refrigerantWithFactor
// {
// ID = a.ID,
// ModelNumber = a.ModelNumber,
// TotalNumber = a.TotalNumber,
// ParameterID = a.ParameterID,
// ParameterID2 = a.ParameterID2,
// LCAID = a.LCAID,
// ProcessName = a.ProcessName,
// ResponsibleUnit = a.ResponsibleUnit,
// Name = a.Name,
// Scalar = a.Scalar,
// KgCO2e = a.KgCO2e,
// CreatedTime = a.CreatedTime,
// Description = a.Description,
// activityDataType = a.activityDataType,
// emitParaType = a.emitParaType,
// UsedMonth = a.UsedMonth,
// factor = c.Value,
// GWP = b.Value
// }).AsQueryable();
var qry = (from a in _db.LCACommonSurveyForm_Refrigerant
join b1 in _db.AssessmentReportGWP on a.ARnGWPid equals b1.ID into b2
from b in b2.DefaultIfEmpty()
join c in _db.LCAs on a.LCAID equals c.ID
join d in _db.Parameters on a.ParameterID2 equals d.ID
where a.LCAID == LCAID
orderby a.ID
select new refrigerantWithFactor
{
ID = a.ID,
ModelNumber = a.ModelNumber,
TotalNumber = a.TotalNumber,
ParameterID = a.ARnGWPid,
ParameterID2 = a.ParameterID2,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
UsedMonth = a.UsedMonth,
factor=d.Value,
GWP= (b == null ? 0 : (c.ARversion == "AR6" ? b.AR6GWP100 : (c.ARversion == "AR4" ? b.AR4GWP100 : b.AR5GWP100)))
}).AsQueryable();
return qry;
}
public IQueryable<fireEquipmentWithFactor> getFireEquipmentWithFactor(int LCAID)
{
//var qry = (from a in _db.LCACommonSurveyForm_FireEquipment
// join b in _db.Parameters on a.ParameterID equals b.ID
// where a.LCAID == LCAID
// select new fireEquipmentWithFactor
// {
// ID = a.ID,
// Quantity = a.Quantity,
// ParameterID = a.ParameterID,
// LCAID = a.LCAID,
// ProcessName = a.ProcessName,
// ResponsibleUnit = a.ResponsibleUnit,
// Name = a.Name,
// Scalar = a.Scalar,
// KgCO2e = a.KgCO2e,
// CreatedTime = a.CreatedTime,
// Description = a.Description,
// activityDataType = a.activityDataType,
// emitParaType = a.emitParaType,
// factor =b.Value
// }).AsQueryable();
var qry = (from a in _db.LCACommonSurveyForm_FireEquipment
join b1 in _db.AssessmentReportGWP on a.ARnGWPid equals b1.ID into b2
from b in b2.DefaultIfEmpty()
join c in _db.LCAs on a.LCAID equals c.ID
where a.LCAID == LCAID
select new fireEquipmentWithFactor
{
ID = a.ID,
Quantity = a.Quantity,
ParameterID = a.ARnGWPid,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
factor =(b==null?0:(c.ARversion=="AR6"?b.AR6GWP100:(c.ARversion=="AR4"?b.AR4GWP100:b.AR5GWP100)))
}).AsQueryable();
return qry;
}
public IQueryable<kitchenWithFactor> getKitchenWithFactor(int LCAID)
{
var qry = (from a in _db.LCACommonSurveyForm_Kitchen
join b in _db.Parameters on a.ParameterID equals b.ID
where a.LCAID == LCAID
select new kitchenWithFactor
{
ID = a.ID,
ReferenceFileUrl = a.ReferenceFileUrl,
ReferencePhotoUrl = a.ReferencePhotoUrl,
ParameterID = a.ParameterID,
Type = a.Type,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
ParameterValue = a.ParameterValue,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
factor = b.Value,
Evidence = a.Evidence,
heatValue = a.heatValue
}).AsQueryable();
return qry;
}
public IQueryable<kitchenWithFactor> getKitchenFilterWarmGasTypeWithFactor(int LCAID, int WarmGasType)
{
var qry = (from a in _db.LCACommonSurveyForm_Kitchen
join b in _db.Parameters on a.ParameterID equals b.ID
join c in _db.YearlyParameters on a.ParameterID equals c.ID
join d in _db.YearlyParameterTypes on c.TypeID equals d.ID
where a.LCAID == LCAID
where d.warmGasType == (WarmGasType)WarmGasType
select new kitchenWithFactor
{
ID = a.ID,
ReferenceFileUrl = a.ReferenceFileUrl,
ReferencePhotoUrl = a.ReferencePhotoUrl,
ParameterID = a.ParameterID,
Type = a.Type,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
ParameterValue = a.ParameterValue,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
factor = b.Value
}).AsQueryable();
return qry;
}
public IQueryable<gasolineEquipmentWithFactor> getGasolineEquipmentWithFactor(int LCAID)
{
var qry = (from a in _db.LCACommonSurveyForm_GasolineEquipment
join b in _db.Parameters on a.ParameterID equals b.ID
where a.LCAID == LCAID
select new gasolineEquipmentWithFactor
{
ID = a.ID,
ReferenceFileUrl = a.ReferenceFileUrl,
ReferencePhotoUrl = a.ReferencePhotoUrl,
ParameterID = a.ParameterID,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
ParameterValue = a.ParameterValue,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
factor = b.Value,
Evidence = a.Evidence
}).AsQueryable();
return qry;
}
public IQueryable<vehicleWithFactor> getVehicleWithFactor(int LCAID)
{
var qry = (from a in _db.LCACommonSurveyForm_Vehicle
join b in _db.Parameters on a.ParameterID equals b.ID
where a.LCAID == LCAID
select new vehicleWithFactor
{
ID = a.ID,
CarPlateNo = a.CarPlateNo,
Type = a.Type,
ReferenceFileUrl = a.ReferenceFileUrl,
ReferencePhotoUrl = a.ReferencePhotoUrl,
ParameterID = a.ParameterID,
LCAID = a.LCAID,
ProcessName = a.ProcessName,
ResponsibleUnit = a.ResponsibleUnit,
Name = a.Name,
Scalar = a.Scalar,
ParameterValue = a.ParameterValue,
KgCO2e = a.KgCO2e,
CreatedTime = a.CreatedTime,
Description = a.Description,
activityDataType = a.activityDataType,
emitParaType = a.emitParaType,
Evidence = a.Evidence,
factor = b.Value
}).AsQueryable();
return qry;
}
public Dictionary<string, decimal> getWorkhourFactors()
{
Dictionary<string, decimal> ret = new Dictionary<string, decimal>();
var lan = CultureInfo.CurrentCulture.Name;
var qry = (from a in _db.NonYearlyParameters
join b in _db.NonYearlyParameterTypes on a.TypeID equals b.ID
join c in _db.NonYearlyParameterCategories on b.CategoryID equals c.ID
join d in _db.Parameters on a.ID equals d.ID
where a.IsHistory == false && c.Category == Categories.Septic && b.DisplayNameTW != "GWP"
select new
{
b.DisplayNameTW,
b.DisplayNameCN,
b.DisplayNameEN,
d.Value
}).AsQueryable();
if (qry.Any())
{
if (lan == "zh-TW")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayNameTW, rec.Value);
if (lan == "en-US")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayNameEN, rec.Value);
if (lan == "zh-CN")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayNameCN, rec.Value);
}
return ret;
}
public Dictionary<string, decimal> getN2OandCH4Factors(int LCAID)
{
var arVersion = (from a in _db.LCAs
where a.ID == LCAID
select a.ARversion).FirstOrDefault();
Dictionary<string, decimal> ret = new Dictionary<string, decimal>();
var qry = (from a in _db.AssessmentReportGWP
where a.chemicalFormula == "CH4" || a.chemicalFormula == "N2O"
select new {
DisplayName = a.chemicalFormula,
AR4GWP100 = a.AR4GWP100,
AR5GWP100 = a.AR5GWP100,
AR6GWP100 = a.AR6GWP100
}).AsQueryable();
if (qry.Any())
{
if (arVersion == null || arVersion == "AR6")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayName, rec.AR6GWP100);
else if (arVersion == "AR5")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayName, rec.AR5GWP100);
else if (arVersion == "AR4")
foreach (var rec in qry.ToList())
ret.Add(rec.DisplayName, rec.AR4GWP100);
}
return ret;
}
public bool SaveImportData(excelExportOrgLCAdataVM vm, ImportOrganizationLCA importLCA, int LCAID)
{
var transac = _db.Database.BeginTransaction();
try
{
_db.SheetHeaders.RemoveRange(_db.SheetHeaders.Where(x =>x.LCAID == LCAID &&
(x.Category == Categories.Vehicle || x.Category == Categories.Kitchen || x.Category == Categories.GasolineEquipment || x.Category == Categories.Refrigerant
|| x.Category == Categories.FireEquipment || x.Category == Categories.OtherCompound || x.Category == Categories.Septic || x.Category == Categories.Electric || x.Category == Categories.Steam)));
_db.LCACommonSurveyForm_Vehicle.RemoveRange(_db.LCACommonSurveyForm_Vehicle.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_Kitchen.RemoveRange(_db.LCACommonSurveyForm_Kitchen.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_GasolineEquipment.RemoveRange(_db.LCACommonSurveyForm_GasolineEquipment.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_Refrigerant.RemoveRange(_db.LCACommonSurveyForm_Refrigerant.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_FireEquipment.RemoveRange(_db.LCACommonSurveyForm_FireEquipment.Where(x => x.LCAID == LCAID));
_db.OrganizationOtherCompound.RemoveRange(_db.OrganizationOtherCompound.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_WorkHour.RemoveRange(_db.LCACommonSurveyForm_WorkHour.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_PowerUsage.RemoveRange(_db.LCACommonSurveyForm_PowerUsage.Where(x => x.LCAID == LCAID));
_db.LCACommonSurveyForm_SteamUsage.RemoveRange(_db.LCACommonSurveyForm_SteamUsage.Where(x => x.LCAID == LCAID));
if (importLCA.VehicleSheet.Count > 0)
{
_db.LCACommonSurveyForm_Vehicle.AddRange(importLCA.VehicleSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Vehicle, SheetFillerName = vm._orgLCAdata2fuels.commonFields.LCAStarter, Department = vm._orgLCAdata2fuels.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata2fuels.commonFields.LCAStarterPhone });
}
if (importLCA.KitchenSheet.Count > 0)
{
_db.LCACommonSurveyForm_Kitchen.AddRange(importLCA.KitchenSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Kitchen, SheetFillerName = vm._orgLCAdata2fuels.commonFields.LCAStarter, Department = vm._orgLCAdata2fuels.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata2fuels.commonFields.LCAStarterPhone });
}
if (importLCA.GasolineEquipmentSheet.Count > 0)
{
_db.LCACommonSurveyForm_GasolineEquipment.AddRange(importLCA.GasolineEquipmentSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.GasolineEquipment, SheetFillerName = vm._orgLCAdata2fuels.commonFields.LCAStarter, Department = vm._orgLCAdata2fuels.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata2fuels.commonFields.LCAStarterPhone });
}
if (importLCA.RefrigerantSheet.Count > 0)
{
_db.LCACommonSurveyForm_Refrigerant.AddRange(importLCA.RefrigerantSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Refrigerant, SheetFillerName = vm._orgLCAdata7rfg.commonFields.LCAStarter, Department = vm._orgLCAdata7rfg.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata7rfg.commonFields.LCAStarterPhone });
}
if (importLCA.FireEquipmentSheet.Count > 0)
{
_db.LCACommonSurveyForm_FireEquipment.AddRange(importLCA.FireEquipmentSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.FireEquipment, SheetFillerName = vm._orgLCAdata8fire.commonFields.LCAStarter, Department = vm._orgLCAdata8fire.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata8fire.commonFields.LCAStarterPhone });
}
if (importLCA.OtherCompound.Count > 0)
{
_db.OrganizationOtherCompound.AddRange(importLCA.OtherCompound);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.OtherCompound, SheetFillerName = vm._orgLCAdata9others.commonFields.LCAStarter, Department = vm._orgLCAdata9others.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata9others.commonFields.LCAStarterPhone });
}
if (importLCA.WorkHourSheet.Count > 0)
{
_db.LCACommonSurveyForm_WorkHour.AddRange(importLCA.WorkHourSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Septic, SheetFillerName = vm._orgLCAdata6workHr.commonFields.LCAStarter, Department = vm._orgLCAdata6workHr.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata6workHr.commonFields.LCAStarterPhone });
}
if (importLCA.PowerUsageSheet.Count > 0)
{
_db.LCACommonSurveyForm_PowerUsage.AddRange(importLCA.PowerUsageSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Electric, SheetFillerName = vm._orgLCAdata10elec.commonFields.LCAStarter, Department = vm._orgLCAdata10elec.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata10elec.commonFields.LCAStarterPhone });
}
if (importLCA.SteamUsageSheet.Count > 0)
{
_db.LCACommonSurveyForm_SteamUsage.AddRange(importLCA.SteamUsageSheet);
_db.SheetHeaders.Add(new SheetHeader() {LCAID = LCAID, Category = Categories.Steam, SheetFillerName = vm._orgLCAdata11steamVM.commonFields.LCAStarter, Department = vm._orgLCAdata11steamVM.commonFields.LCAStarterDepartment, Phone = vm._orgLCAdata11steamVM.commonFields.LCAStarterPhone });
}
_db.SaveChanges();
transac.Commit();
}
catch (Exception ex)
{
transac.Rollback();
return false;
}
return true;
}
}
}