public async Task <ActionResult> Login(string returnUrl, string customerId = null) { ViewBag.ReturnUrl = returnUrl; ViewBag.CustomerId = customerId; if (User.Identity.IsAuthenticated) { if (!string.IsNullOrWhiteSpace(customerId)) { OverviewDAL db = new OverviewDAL(); IEnumerable <Customer> userCustomers = await db.GetUserCustomers(User.Identity.GetUserId()); if (userCustomers.Count() > 0) { Customer customer = userCustomers.First(); //If the query string contains a customer id set that customer and the dault on log in if (!string.IsNullOrEmpty(customerId)) { string[] customerIds = userCustomers.Select(i => i.CustomerId).ToArray(); if (customerId.Contains(customerId)) { customer = userCustomers.Where(i => i.CustomerId == customerId).First(); } } if (customer.DatabaseName == DataBases.NetsuiteInsphire && !AppGlobal.InsphireEnabled) { // An InspHire user is trying to log in when InspHire is disabled, so prevent them ModelState.AddModelError("", Resources.AccountDisabledInspHireDisabled); return(View()); } else { Session["ActiveCustomer"] = customer; } } } if (string.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToAction("Index", "Overview")); } else { return(Redirect(returnUrl)); } } return(View()); }
public async Task <ActionResult> EnergyConsumption(string venueCodeSelected, string orderStatus) { //GET DATA REQUIRED FOR CSV GENERATION OverviewDAL db = new OverviewDAL(); RentalsDAL rentals_db = new RentalsDAL(); ViewModels.Overview.OverviewViewModel model = new ViewModels.Overview.OverviewViewModel(); model.TrackUnitStartDate = Convert.ToDateTime(Session["StartDate"]); model.TrackUnitEndDate = Convert.ToDateTime(Session["EndDate"]); var motorUsages = await GetMotroUsage(model.TrackUnitStartDate, model.TrackUnitEndDate, orderStatus); model.FuelConsumptionPerMachine = db.GetDWHCustConsPerMachine(ActiveCustomer.DatabaseName, ActiveCustomer.CompanyId, ActiveCustomer.CustomerId, model.TrackUnitStartDate.Date, model.TrackUnitEndDate.Date); var groupedConsumption = model.FuelConsumptionPerMachine.GroupBy(x => new { x.inventtransid, x.serialNumber }); List <_ConsumptionAndSerialNo> csList = new List <_ConsumptionAndSerialNo>(); foreach (var gc in groupedConsumption) { //There will be only one value against the group of inventransid and serialno so we will take the first value var consumption = gc.Select(x => x.machineconsumption).FirstOrDefault(); //this is the total consumption for the machine var noOfHours = gc.Select(x => x.machinerunningHourM1).FirstOrDefault(); //this is the total number of hours the above is cost is calculated var unit = gc.Select(x => x.unit).FirstOrDefault(); csList.Add(new _ConsumptionAndSerialNo { ConsumptionCost = noOfHours > 0 ? consumption / noOfHours : 0, SerialNo = gc.Key.serialNumber, Unit = unit }); } //we will further check if there is more than one serial numbers with different cost value so to take the average of the same. var finalConsumptionList = csList.GroupBy(x => x.SerialNo).Select(y => new _ConsumptionAndSerialNo { SerialNo = y.Key, ConsumptionCost = y.Average(z => z.ConsumptionCost), Unit = y.FirstOrDefault().Unit }); var reportInfo = (from mu in motorUsages join sc in finalConsumptionList on mu.SerialNumber equals sc.SerialNo select new _ReportInfo { MachineName = mu.MachineType, MachineType = mu.MachineType, SerialNumber = mu.SerialNumber, TransactionDate = mu.TransDate, Value = mu.RunningHour * sc.ConsumptionCost, ValueUnit = sc.Unit }).ToList(); return(CreateReport(Resources.EnergyConsumption, model.TrackUnitStartDate, model.TrackUnitEndDate, reportInfo, "Energy_Consumption")); }
public ActionResult AccountManagerPicture(string databaseName, string customerId, string companyId) { APIAuth auth = new APIAuth(Request, Response); AuthInfo authInfo = auth.CheckLogin(); if (authInfo.IsAuthenticated) { Customer localCust = new Customer(); localCust.DatabaseName = databaseName; localCust.CustomerId = customerId; localCust.CompanyId = companyId; //Check if this user has access to this customer var userCustomers = db.GetUserCustomersSync(authInfo.User.Id); if (userCustomers.Count(x => x.CustomerKey == localCust.CustomerKey) > 0) { // Get the customer's account manager's details AccountManager accountManager = new OverviewDAL().GetAccountManagerDetailsSync(localCust).FirstOrDefault(); // Get the URL for the account manager's image string accountManagerImageURL = DownloadsHelper.GetAccountManagerImageURL(accountManager.Email); // Download the account manager image WebClient webClient = new WebClient(); byte[] accountManagerImageBytes = webClient.DownloadData(accountManagerImageURL); // Return the account manager image as bytes return(File(accountManagerImageBytes, System.Net.Mime.MediaTypeNames.Image.Jpeg)); } else { return(auth.Forbidden()); } } else { return(auth.Forbidden()); } }
//This Original Code: Can be cleared once we are sure the new function is doing fine. //public async Task<ActionResult> MotorUsage(string venueCodeSelected, string orderStatus) //{ // //GET DATA REQUIRED FOR CSV GENERATION // OverviewDAL db = new OverviewDAL(); // RentalsDAL rentals_db = new RentalsDAL(); // DateTime TrackUnitStartDate = Convert.ToDateTime(Session["TrackUnitStartDate"]); // DateTime TrackUnitEndDate = Convert.ToDateTime(Session["TrackUnitEndDate"]); // IEnumerable<RentalOrder> fuelConsumptionPerMachineOrders = await db.GetRentalOrders(ActiveCustomer, TrackUnitStartDate, TrackUnitEndDate); // IEnumerable<MotorUsage> motorUsages = db.GetDWHCustRunningHourPerMachinePerDay(ActiveCustomer, TrackUnitStartDate, TrackUnitEndDate); // //Get rental status codes from query string // if (!string.IsNullOrWhiteSpace(orderStatus)) // { // string[] orderStatusCodes = orderStatus.Split(','); // //Filter out machines with no matching order status // fuelConsumptionPerMachineOrders = fuelConsumptionPerMachineOrders.Where(i => orderStatusCodes.Contains(i.OrderStatusId)); // } // //Filter out machines with no matchinging order // motorUsages = motorUsages.Where(i => fuelConsumptionPerMachineOrders.Select(x => x.ObjectId).Contains(i.SerialNumber)); // //Filterout machine with no run time data // //below line is commented in response to the Ticket#367 so to avoid skipping the non-used dates // //motorUsages = motorUsages.Where(i => i.RunningHour > 0.0m); // //Get a list of non duplicate dates from the motor usage data // List<DateTime> motorUsageDates = motorUsages.GroupBy(i => i.TransDate).Select(i => i.Key).OrderByDescending(i => i).ToList(); // //Get a list of non diplicate machine from the data (Serial number is the unique ID here) // List<MotorUsage> motorUsageMachines = motorUsages.GroupBy(i => i.SerialNumber).Select(i => new MotorUsage() { SerialNumber = i.Key, MachineType = i.First().MachineType }).ToList(); // //Find the template breeam report // var fi = new FileInfo(HttpContext.Server.MapPath("/App_Data/ReportTemp/motor-usage.xlsx")); // //Load the template into memory and begin adding customer information // using (var energyconsumption = new ExcelPackage(fi)) // { // var ws = energyconsumption.Workbook.Worksheets["Consumption"]; // Dictionary<string, string> machineColumns = new Dictionary<string, string>(); // //Add Date column heading // ws.Cells["A1:C1"].Merge = true; // ws.Cells["A1"].Value = Resources.RunningHours; // int headerRow = 3; // string headingCell = "A" + headerRow.ToString(); // ws.Cells[headingCell].IsRichText = true; // var dateRichText = ws.Cells[headingCell].RichText; // //ws.Cells["A7"].Value = // ws.Cells[headingCell].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin); // var dateRichTextValue = dateRichText.Add(Resources.Date); // dateRichTextValue.Bold = true; // //Loop though and create column headings for each of the machines // for (int i = 0; i < motorUsageMachines.Count(); i++) // { // string columnName = utlStore.GetExcelColumn(i + 2); // machineColumns.Add(motorUsageMachines.ElementAt(i).SerialNumber, columnName); // var Cell = ws.Cells[columnName + headerRow.ToString()]; // Cell.IsRichText = true; // var RichText = Cell.RichText; // var RichValue = RichText.Add(motorUsageMachines.ElementAt(i).MachineType + "(" + motorUsageMachines.ElementAt(i).SerialNumber + ")" + Environment.NewLine); // RichValue.Bold = true; // RichValue = RichText.Add(Resources.StartRentalDate + ": " + TrackUnitStartDate.ToString("dd/MM/yyyy")); // RichValue.Color = System.Drawing.Color.Green; // RichValue.Bold = false; // Cell.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin); // Cell.AutoFitColumns(30); // } // int rowCount = headerRow + 1; // foreach (DateTime date in motorUsageDates) // { // ws.Cells["A" + rowCount.ToString()].Value = date.ToShortDateString(); // IEnumerable<MotorUsage> dateMachines = motorUsages.Where(i => i.TransDate.Date == date.Date); // foreach (MotorUsage machine in dateMachines) // { // ws.Cells[machineColumns[machine.SerialNumber] + rowCount.ToString()].Value = machine.RunningHour.ToString("N2"); // } // rowCount++; // } // return File(energyconsumption.GetAsByteArray(), ".xlsx", "Motor_Usage_" + TrackUnitStartDate.ToShortDateString() + "-" + TrackUnitEndDate.ToShortDateString() + "_" + ActiveCustomer.Name + ".xlsx"); // }; //} private async Task <IEnumerable <MotorUsage> > GetMotroUsage(DateTime TrackUnitStartDate, DateTime TrackUnitEndDate, string orderStatus) { //GET DATA REQUIRED FOR CSV GENERATION OverviewDAL db = new OverviewDAL(); RentalsDAL rentals_db = new RentalsDAL(); IEnumerable <RentalOrder> fuelConsumptionPerMachineOrders = await db.GetRentalOrders(ActiveCustomer, TrackUnitStartDate, TrackUnitEndDate); IEnumerable <MotorUsage> motorUsages = db.GetDWHCustRunningHourPerMachinePerDay(ActiveCustomer, TrackUnitStartDate, TrackUnitEndDate); //Get rental status codes from query string if (!string.IsNullOrWhiteSpace(orderStatus)) { string[] orderStatusCodes = orderStatus.Split(','); //Filter out machines with no matching order status fuelConsumptionPerMachineOrders = fuelConsumptionPerMachineOrders.Where(i => orderStatusCodes.Contains(i.OrderStatusId)); } //Filter out machines with no matchinging order motorUsages = motorUsages.Where(i => fuelConsumptionPerMachineOrders.Select(x => x.ObjectId).Contains(i.SerialNumber)); return(motorUsages); }
public async Task <bool> PushCreationEmail(Transfer transfer, RentalOrderDetails machine) { OverviewDAL overviewDAL = new OverviewDAL(); Customer senderCustomer = ActiveCustomer; Customer recipientCustomer = overviewDAL.GetCustomer(transfer.DatabaseName, transfer.DataAreaId, transfer.CustAccount); //Build email template model TransferEmail emailModel = new TransferEmail(); IdentityUser Sender = UserTable.GetUserById(transfer.TransferFromUserId); ContactPerson Recipient = db.GetContactPersonById(transfer.ContactPersonId); ContactPerson contactPerson = db.GetContactPersonById(transfer.ContactPersonId); emailModel.SenderFullName = Sender.FirstName + " " + Sender.LastName; emailModel.RecipientFullName = Recipient.ContactPersonName; emailModel.Machine = machine; emailModel.Transfer = transfer; emailModel.AcceptLink = ConfigurationManager.AppSettings["DomainURL"] + "?/Projects/Index"; emailModel.DeclineLink = ConfigurationManager.AppSettings["DomainURL"] + "/Projects/Index"; //Generate HTML for the confirmation email ViewData.Model = emailModel; var pushRequestConfirmation = new StringWriter(); var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "~/Views/Emails/ProjectPushRequestConfirmation.cshtml"); var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, pushRequestConfirmation); viewResult.View.Render(viewContext, pushRequestConfirmation); viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); //Generate HTML for the notification email ViewData.Model = emailModel; var pushRequest = new StringWriter(); viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "~/Views/Emails/ProjectPushRequest.cshtml"); viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, pushRequest); viewResult.View.Render(viewContext, pushRequest); viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); string senderEmail = ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("Email").Value; string senderOnRentEmail = await db.GetOnRentEmailAddress(senderCustomer); string senderAmEmail = (await new OverviewDAL().GetAccountManagerDetails(senderCustomer)).Email; string[] senderNotificationEmails = null; if (!String.IsNullOrEmpty(senderCustomer.NotificationEmailAddress)) { senderNotificationEmails = senderCustomer.NotificationEmailAddress.Split(';'); } string recipientEmail = Recipient.ContactPersonEmail; string recipientOnRentEmail = await db.GetOnRentEmailAddress(recipientCustomer); string recipientAmEmail = (await new OverviewDAL().GetAccountManagerDetails(recipientCustomer)).Email; string[] recipientNotificationEmails = null; if (!String.IsNullOrEmpty(recipientCustomer.NotificationEmailAddress)) { recipientNotificationEmails = recipientCustomer.NotificationEmailAddress.Split(';'); } bool sucess = false; if (MailClient.SendEmail(senderCustomer, Resources.TransferRequested, pushRequestConfirmation.GetStringBuilder().ToString(), senderAmEmail, senderEmail, senderOnRentEmail, senderNotificationEmails)) { if (MailClient.SendEmail(recipientCustomer, Resources.TransferRequested, pushRequest.GetStringBuilder().ToString(), recipientAmEmail, recipientEmail, recipientOnRentEmail, recipientNotificationEmails)) { sucess = true; } } return(sucess); }
public async Task <IEnumerable <RentalOrder> > Process(IEnumerable <RentalOrder> orders, IEnumerable <TrackUnitData> units, Customer activeCustomer, string userId, string mapTrans = "") { if (this.ViewType == "Map" && orders.Count() > 0) { this.OrderStatusesCheck.Add("20"); this.ResultsPerPage = "All"; orders = orders.Where(x => this.OrderStatusesCheck.Contains(x.OrderStatusId)); if (!String.IsNullOrEmpty(mapTrans)) { var machine = orders.Where(x => x.InventTransId == mapTrans).FirstOrDefault(); this.OrderNumber = machine == null ? "" : machine.SalesId; this.SerialNumberSearch = machine == null ? "" : machine.ObjectId; } } this.CustomerAccounts = orders.Select <RentalOrder, CustomerAccount>(x => new CustomerAccount { CustAccount = x.CustAccount, AccountName = x.AccountName }).Distinct() .OrderByDescending(x => this.CustomerAccountsCheck.Contains(x.CustAccount)).ThenBy(y => y.AccountName); if (this.ShowFuelConsumptionMachines == "true") { OverviewDAL overviewDAL = new OverviewDAL(); IEnumerable <FuelConsumption> fuelConsumptionPerMachine = overviewDAL.GetDWHCustConsPerMachine(activeCustomer.DatabaseName, activeCustomer.CompanyId, activeCustomer.CustomerId, this.StartDate, this.EndDate); orders = orders.Where(i => fuelConsumptionPerMachine.Select(n => n.inventtransid).Contains(i.InventTransId)); } if (this.ShowGPSTrackedMachines == "true") { OverviewDAL overviewDAL = new OverviewDAL(); //Get required data IEnumerable <OnSiteMachine> OnSiteMachines = overviewDAL.GetDWHMachineOnSite(activeCustomer); //Remove OnSiteMachines with no LastActive date OnSiteMachines = OnSiteMachines.Where(i => i.lastActiveDate.HasValue && i.lastActiveDate != Convert.ToDateTime("1900-01-01")).ToList(); //Filter out machines past the users active hours selection units = units.Where(i => i.GpsFixTime > DateTime.Now.AddHours(-this.TrackUnitHours)); //Remove machines which dont have matching OnsiteMachines List <string> onSiteSerialNumbers = OnSiteMachines.Select(i => i.serialNumber).ToList(); orders = orders.Where(i => onSiteSerialNumbers.Contains(i.ObjectId)).ToList(); } if (this.ShowNotInUse == "true") { OverviewDAL overviewDAL = new OverviewDAL(); if (activeCustomer.overviewVersion == null || activeCustomer.overviewVersion == "1") { var customers = orders.Select(x => x.CustAccount).Distinct(); int daysNotInUse = (await new ROLWeb.Models.UserStore().FindByIdAsync(userId)).MachinesNotInUseDays; var OverviewDAL = new ROLWeb.Models.Overview.OverviewDAL(); var tempOrders = orders; orders = Enumerable.Empty <RentalOrder>(); foreach (string customer in customers) { var machines = OverviewDAL.GetMachinesNotInUse(activeCustomer.DatabaseName, activeCustomer, daysNotInUse.ToString()); var selectedOrders = tempOrders.Join(machines, x => new { x.CustAccount, x.SalesId, x.ObjectId }, y => new { CustAccount = customer, y.SalesId, y.ObjectId }, (ord, mac) => ord); orders = orders.Concat(selectedOrders); } } else if (activeCustomer.overviewVersion == "2") { //Get required data IEnumerable <OnSiteMachine> OnSiteMachines = overviewDAL.GetDWHMachineOnSite(activeCustomer); //Remove OnSiteMachines with no LastActive date OnSiteMachines = OnSiteMachines.Where(i => i.lastActiveDate.HasValue && i.lastActiveDate != Convert.ToDateTime("1900-01-01")).ToList(); int daysNotInUse = (await new ROLWeb.Models.UserStore().FindByIdAsync(userId)).MachinesNotInUseDays; int MachinesNotInUseHours = daysNotInUse * 24; //filterout machines in use OnSiteMachines = OnSiteMachines.Where(i => Convert.ToDateTime(i.lastActiveDate) < DateTime.Now.AddHours(-MachinesNotInUseHours) || Convert.ToDateTime(i.lastActiveDate).Date == DateTime.Now.AddDays(1).Date); //Filter out machines past the users active hours selection units = units.Where(i => i.GpsFixTime > DateTime.Now.AddHours(-this.TrackUnitHours)); //Remove machines which dont have matching OnsiteMachines List <string> onSiteSerialNumbers = OnSiteMachines.Select(i => i.serialNumber).ToList(); orders = orders.Where(i => onSiteSerialNumbers.Contains(i.ObjectId)).ToList(); } } // Filtering if (this.CustomerAccountsCheck.Count() > 0) { orders = orders.Where(x => this.CustomerAccountsCheck.Contains(x.CustAccount)); } if (!String.IsNullOrWhiteSpace(this.VenueSearch)) { orders = orders.Where(x => x.DeliveryName.ToLower().Contains(this.VenueSearch.ToLower()) || x.DeliveryCity.ToLower().Contains(this.VenueSearch.ToLower())); } if (!String.IsNullOrWhiteSpace(this.OrderNumber)) { orders = orders.Where(x => x.SalesId.Contains(this.OrderNumber)); } if (!String.IsNullOrWhiteSpace(this.PurchOrderSearch)) { orders = orders.Where(x => x.PurchOrderFormNum.ToLower().Contains(this.PurchOrderSearch.ToLower())); } if (!String.IsNullOrWhiteSpace(this.ProductSearch)) { orders = orders.Where(x => x.ProductId.ToLower().Contains(this.ProductSearch.ToLower()) || x.ItemName.ToLower().Contains(this.ProductSearch.ToLower())); } if (!String.IsNullOrWhiteSpace(this.FleetNumberSearch)) { orders = orders.Where(x => x.AssetId.ToLower().Contains(this.FleetNumberSearch.ToLower())); } if (!String.IsNullOrWhiteSpace(this.SerialNumberSearch)) { orders = orders.Where(x => x.ObjectId.ToLower().Contains(this.SerialNumberSearch.ToLower())); } this.OrderStatuses = orders.Select <RentalOrder, OrderStatus>(x => new OrderStatus(activeCustomer.DatabaseName) { OrderStatusId = x.OrderStatusId }).Distinct().OrderBy(y => y.OrderStatusName); if (this.OrderStatusesCheck.Count() > 0) { orders = orders.Where(x => this.OrderStatusesCheck.Contains(x.OrderStatusId)); } if (this.ContactPersonsCheck.Count() > 0) { orders = orders.Where(x => this.ContactPersonsCheck.Contains(x.ContactPersonId)); } if (!string.IsNullOrEmpty(this.ProjectLeader)) { orders = orders.Where(x => x.ContactPersonId == ProjectLeader); } this.Venues = orders.Select <RentalOrder, Venue>(x => new Venue { DeliveryName = x.DeliveryName, DeliveryCity = x.DeliveryCity, RorVenueCode = x.RorVenueCode }).Distinct() .OrderByDescending(x => this.VenueCheck.Contains(x.RorVenueCode)).ThenBy(y => y.DeliveryName); this.ItemGroups = orders.Select <RentalOrder, ItemGroup>(x => new ItemGroup { ItemGroupId = x.ItemGroupId, ItemGroupName = x.ItemGroupName }).Distinct() .OrderByDescending(x => this.ItemGroupCheck.Contains(x.ItemGroupId)).ThenBy(y => y.ItemGroupName); this.PriceRateCodes = orders.Select <RentalOrder, String>(x => x.PriceRateCode).Distinct(); if (this.VenueCheck.Count() > 0) { orders = orders.Where(x => this.VenueCheck.Contains(x.RorVenueCode)); } if (this.PriceRateCodeCheck.Count() > 0) { orders = orders.Where(x => this.PriceRateCodeCheck.Contains(x.PriceRateCode)); } if (this.ShowMachinesOnRent == "true") { List <string> itemGroupCheck = this.ItemGroups.Where(i => i.ItemGroupId != "31900").Select(i => i.ItemGroupId).ToList(); this.ItemGroupCheck = itemGroupCheck; } if (this.ShowExtrasOnRent == "true") { List <string> itemGroupCheck = this.ItemGroups.Where(i => i.ItemGroupId == "31900").Select(i => i.ItemGroupId).ToList(); this.ItemGroupCheck = itemGroupCheck; } if (this.ItemGroupCheck.Count() > 0) { orders = orders.Where(x => this.ItemGroupCheck.Contains(x.ItemGroupId)); } if (this.RentalTermCheck.Count() > 0) { orders = orders.Where(x => this.RentalTermCheck.Contains(x.RentalTerm)); } if (units != null) { foreach (var order in orders) { var unit = units.Where(x => x.ReferenceNumber == order.ObjectId).FirstOrDefault(); if (unit != null) { order.IsMachineLocalized = true; order.Latitude = unit.Latitude; order.Longitude = unit.Longitude; TimeSpan diffTime = DateTime.Now.Subtract(unit.GpsFixTime); if (diffTime.TotalMinutes > 240) { order.markerColor = "yellow"; } else if (unit.Speed > 15) { order.markerColor = "green"; } else if (unit.Input1.Value == true) { order.markerColor = "blue"; } else { order.markerColor = "red"; } } else { order.IsMachineLocalized = false; order.Latitude = 0.0; order.Longitude = 0.0; order.markerColor = ""; } } } if (this.ShowGPSTrackedMachines == "true" || this.ShowNotInUse == "true") { orders = orders.Where(i => i.IsMachineLocalized == true); } this.ContactPersons = orders.Select <RentalOrder, ContactPerson>(x => new ContactPerson { ContactPersonId = x.ContactPersonId, ContactPersonName = x.ContactPerson }).Distinct() .OrderByDescending(x => this.ContactPersonsCheck.Contains(x.ContactPersonId)).ThenBy(y => y.ContactPersonName); // Ordering if (this.OrderBy == "OnHireAsc") { orders = orders.OrderBy(x => x.DateOnHire).ThenBy(x => x.InventTransId); } if (this.OrderBy == "OnHireDesc") { orders = orders.OrderByDescending(x => x.DateOnHire).ThenByDescending(x => x.InventTransId); } // Calculations if (this.ResultsPerPage == "5") { this.Orders = orders.Skip((this.CurrentPage - 1) * 5).Take(5); this.TotalPages = (int)Math.Ceiling((decimal)orders.Count() / 5); } else if (this.ResultsPerPage == "15") { this.Orders = orders.Skip((this.CurrentPage - 1) * 15).Take(15); this.TotalPages = (int)Math.Ceiling((decimal)orders.Count() / 15); } else if (this.ResultsPerPage == "25") { this.Orders = orders.Skip((this.CurrentPage - 1) * 25).Take(25); this.TotalPages = (int)Math.Ceiling((decimal)orders.Count() / 25); } else if (this.ResultsPerPage == "All") { this.Orders = orders; this.TotalPages = 1; } this.TotalOrders = orders.Count(); this.CurrentPage = Math.Max(this.CurrentPage, 1); this.CurrentPage = Math.Min(this.TotalPages, this.CurrentPage); if (this.ViewType == "Map") { var machine = this.Orders.Where(x => x.IsMachineLocalized).FirstOrDefault(); if (this.Orders.Count() == 1) { this.MapDetails = Json.Encode(new { Latitude = machine == null ? 0.0 : machine.Latitude, Longitude = machine == null ? 0.0 : machine.Longitude, Zoom = 14, mapBounds = false }); } else { this.MapDetails = Json.Encode(new { Latitude = machine == null ? 0.0 : machine.Latitude, Longitude = machine == null ? 0.0 : machine.Longitude, Zoom = 9, mapBounds = true }); } } return(orders); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl, string customerId = null) { if (ModelState.IsValid) { var user = await UserManager.FindAsync(model.UserName, model.Password); if (user != null) { OverviewDAL db = new OverviewDAL(); IEnumerable <Customer> userCustomers = await db.GetUserCustomers(user.Id); if (userCustomers.Count() > 0) { Customer customer = userCustomers.First(); //If the query string contains a customer id set that customer and the dault on log in if (!string.IsNullOrEmpty(customerId)) { string[] customerIds = userCustomers.Select(i => i.CustomerId).ToArray(); if (customerId.Contains(customerId)) { customer = userCustomers.Where(i => i.CustomerId == customerId).First(); } } if (customer.DatabaseName == DataBases.NetsuiteInsphire && !AppGlobal.InsphireEnabled) { // An InspHire user is trying to log in when InspHire is disabled, so prevent them ModelState.AddModelError("", Resources.AccountDisabledInspHireDisabled); } else { Session["ActiveCustomer"] = customer; await SignInAsync(user, false); if (string.IsNullOrWhiteSpace(returnUrl)) { return(RedirectToAction("Index", "Overview")); } else { return(Redirect(returnUrl)); } } } else { ModelState.AddModelError("", Resources.AccountNotActivated); } } else { ModelState.AddModelError("", Resources.InvalidCredentials); } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Orders(DateTime startDate, DateTime endDate, string databaseName, string customerId, string companyId) { APIAuth auth = new APIAuth(Request, Response); AuthInfo authInfo = auth.CheckLogin(); if (authInfo.IsAuthenticated) { Customer localCust = new Customer(); localCust.DatabaseName = databaseName; localCust.CustomerId = customerId; localCust.CompanyId = companyId; //Check if this user has access to this customer var userCustomers = db.GetUserCustomersSync(authInfo.User.Id); //Customer selectedCompany = userCustomers.Where(x => x.CustomerKey == localCust.CustomerKey).First(); //return Json(new { foo = "ok", baz = "alee" }); //if (selectedCompany != null) if (userCustomers.Count(x => x.CustomerKey == localCust.CustomerKey) > 0) { IEnumerable <RentalOrder> orders; Customer activeCust = db.GetCustomer(localCust.DatabaseName, localCust.CompanyId, localCust.CustomerId); if (activeCust.showChildBROrders) { var validCustomers = new OverviewDAL().GetCustomersRegisteredSync().Where(x => x.DatabaseName == activeCust.DatabaseName && x.CompanyId == activeCust.CompanyId); orders = db.GetRentalOrdersChildBRSync(activeCust, startDate, endDate); orders = orders.Join(validCustomers, x => x.CustAccount, y => y.CustomerId, (ord, cust) => ord); } else { orders = db.GetRentalOrdersSync(localCust, startDate, endDate); } //need to manually add trackunit data RentalsDAL dbRental = new RentalsDAL(); IEnumerable <TrackUnitData> units = dbRental.GetTrackUnitDataSync(); using (var orderEnum = orders.GetEnumerator()) { while (orderEnum.MoveNext()) { RentalOrder order = orderEnum.Current; var unit = units.Where(x => x.ReferenceNumber == order.ObjectId).FirstOrDefault(); if (unit != null) { order.IsMachineLocalized = true; order.Latitude = unit.Latitude; order.Longitude = unit.Longitude; TimeSpan diffTime = DateTime.Now.Subtract(unit.GpsFixTime); if (diffTime.TotalMinutes > 240) { order.markerColor = "yellow"; } else if (unit.Speed > 15) { order.markerColor = "green"; } else if (unit.Input1.Value == true) { order.markerColor = "blue"; } else { order.markerColor = "red"; } } else { order.IsMachineLocalized = false; order.Latitude = 0.0; order.Longitude = 0.0; order.markerColor = ""; } } } //END trackunit //new CustomJsonResult( //return Content(new JavaScriptSerializer().Serialize(orders.ToList()), "application/json"); return(new CustomJsonResult { Data = orders.ToList() }); } else { return(Json(new { error = "No access" }, JsonRequestBehavior.AllowGet)); } } else { return(auth.Forbidden()); } }
public async Task <ActionResult> CO2Emissions(string venueCodeSelected, string orderStatus) { //GET DATA REQUIRED FOR CSV GENERATION OverviewDAL db = new OverviewDAL(); RentalsDAL rentals_db = new RentalsDAL(); ViewModels.Overview.OverviewViewModel model = new ViewModels.Overview.OverviewViewModel(); model.TrackUnitStartDate = Convert.ToDateTime(Session["TrackUnitStartDate"]); model.TrackUnitEndDate = Convert.ToDateTime(Session["TrackUnitEndDate"]); IEnumerable <RentalOrder> orders = await ActiveCustomer.GetRentalOrders(rentals_db, model.TrackUnitStartDate.Date, model.TrackUnitEndDate.Date); model.FuelConsumptionPerMachine = db.GetDWHCustConsPerMachine(ActiveCustomer.DatabaseName, ActiveCustomer.CompanyId, ActiveCustomer.CustomerId, model.TrackUnitStartDate, model.TrackUnitEndDate); if (!string.IsNullOrWhiteSpace(orderStatus)) { string[] orderStatusCodes = orderStatus.Split(','); IEnumerable <RentalOrder> FuelConsumptionPerMachineOrders = await ActiveCustomer.GetRentalOrders(new RentalsDAL(), model.TrackUnitStartDate, model.TrackUnitEndDate); string[] orderInventTransIds = FuelConsumptionPerMachineOrders.Where(i => orderStatusCodes.Contains(i.OrderStatusId)).Select(i => i.InventTransId).ToArray(); model.FuelConsumptionPerMachine = model.FuelConsumptionPerMachine.Where(i => orderInventTransIds.Contains(i.inventtransid)); } if (!string.IsNullOrEmpty(venueCodeSelected)) { model.FuelConsumptionPerMachine = model.FuelConsumptionPerMachine.Where(i => i.rorvenuecode == venueCodeSelected).ToList(); } model.SelectMachines = model.FuelConsumptionPerMachine .GroupBy( i => i.machineType, (i1, i2) => new SelectMachine() { Code = i1, Name = i2.First().machineTypeDesc, Count = i2.Count() }) .OrderBy(i => i.Name); //Find the template breeam report var fi = new FileInfo(HttpContext.Server.MapPath("/App_Data/ReportTemp/breeam-report.xlsx")); //Load the template into memory and begin adding customer information using (var breeamReport = new ExcelPackage(fi)) { var ws = breeamReport.Workbook.Worksheets["H. Materieel"]; ws.Cells["A1"].Value = Resources.CO2ProducedByMachines; ws.Cells["D1"].Value = Resources.BuildingSiteMachines; ws.Cells["A7"].Value = Resources.Date; ws.Cells["B7"].Value = Resources.CompanyName; ws.Cells["C7"].Value = Resources.MachineType; ws.Cells["D7"].Value = Resources.Brand; ws.Cells["E7"].Value = Resources.SerialNumber; ws.Cells["F7"].Value = Resources.AdverageFuel; ws.Cells["G7"].Value = Resources.RunningHours; ws.Cells["H7"].Value = Resources.DailyFuelConsumption; ws.Cells["I7"].Value = Resources.KGCo2Total; ws.Cells["J7"].Value = Resources.RentalPeriod; int rowCount = 8; foreach (var machine in model.FuelConsumptionPerMachine) { string date = model.TrackUnitStartDate.ToShortDateString() + "-" + model.TrackUnitEndDate.ToShortDateString(); RentalOrder order = orders.Where(i => i.InventTransId == machine.inventtransid && i.ObjectId == machine.serialNumber).FirstOrDefault(); string companyName = ActiveCustomer.Name; string machineType = "N/A"; foreach (var machineModel in model.SelectMachines) { if (machineModel.Code == machine.machineType) { machineType = machineModel.Name; break; } } string brandAndModel = machine.machineType; string serialNumber = machine.serialNumber; string adverageFuel = string.Format("{0:n1}", (machine.machineconsumption / (Decimal)(model.TrackUnitEndDate - model.TrackUnitStartDate).TotalDays)); string runningHours = string.Format("{0:n1}", machine.machinerunningHourM1); string dailyConsumption = string.Format("{0:n1}", machine.machineconsumption); string kgCO2Total = string.Format("{0:n1}", machine.machineEmission); string rentalPeriod = "N/A"; if (order != null) { rentalPeriod = order.DateOnHire.ToShortDateString() + "-" + order.ExpectedDateOffHire.ToShortDateString(); } ws.Cells["A" + rowCount.ToString()].Value = date; ws.Cells["B" + rowCount.ToString()].Value = companyName; ws.Cells["C" + rowCount.ToString()].Value = machineType; ws.Cells["D" + rowCount.ToString()].Value = brandAndModel; ws.Cells["E" + rowCount.ToString()].Value = serialNumber; ws.Cells["F" + rowCount.ToString()].Value = adverageFuel; ws.Cells["G" + rowCount.ToString()].Value = runningHours; ws.Cells["H" + rowCount.ToString()].Value = dailyConsumption; ws.Cells["I" + rowCount.ToString()].Value = kgCO2Total; ws.Cells["J" + rowCount.ToString()].Value = rentalPeriod; rowCount++; } return(File(breeamReport.GetAsByteArray(), ".xlsx", "BREEAM_" + model.TrackUnitStartDate.ToShortDateString() + "-" + model.TrackUnitEndDate.ToShortDateString() + "_" + ActiveCustomer.Name + ".xlsx")); }; }
public void LoginTestUser() { var userManager = new UserManager <IdentityUser>(new UserStore()) { PasswordHasher = new MyPasswordHasher() }; var authenticationManager = HttpContext.GetOwinContext().Authentication; OverviewDAL db = new OverviewDAL(); userManager.UserValidator = new UserValidator <IdentityUser>(userManager) { AllowOnlyAlphanumericUserNames = false }; var ActiveCustomer = Session["ActiveCustomer"]; if (ActiveCustomer == null) { Session["ActiveCustomer"] = new Customer() { City = "Bournemouth", CompanyId = "1", ContactEmailAddress = "*****@*****.**", ContactPhoneNumber = "07756393728", CustomerId = "1", DatabaseName = "DB1", DEPOT = "This Depot", dwnldInspection = true, dwnldMachineCertificates = true, dwnldOpManual = true, dwnldProdSpecs = true, getDocsFromItem = true, InspHireAcct = null, InspHireCountryCode = null, MachineNotInUseAlerts = true, MoreContactLink = "More Contacts", Name = "Dans test user", NotificationEmailAddress = "*****@*****.**", OffHireEmailAddress = "*****@*****.**", OnHireEmailAddress = "*****@*****.**", requestInspectionSheet = true, showChildBRInvoices = true, showChildBROrders = true, showDownloadRentalAgreement = true, showFilterRentalDuration = true, showMyContacts = true, showMyImprovements = true, showMyInvoices = true, showMyInvoicesDownloadInvoice = true, showMyInvoicesExportToExcel = true, showMyProjects = true, showMyRentals = true, showMyRentalsDetails = true, showMyRentalsDetailsMachineSpecs = true, showMyRentalsDetailsOverview = true, showMyRentalsExportToExcel = true, showMyRentalsMapView = true, showMyRentalsOffRent = true, showMyTraining = true, showNewRental = true, showOverviewCosts = true, showOverviewMachinesNotInUse = true, showOverviewMap = true, showRentalAgreement = true, showTraining = true, SPCODE = null, TermsAndConditionsLink = "Terms and conditions", useInvoiceAccount = true, UseRiwalCompanyEmailAddress = true, UseRiwalCompanyOffHireEmailAddress = true }; } var user = userManager.FindAsync("*****@*****.**", "b0dig_QRIWAL").Result; //IEnumerable<Customer> userCustomers = db.GetUserCustomers(user.Id).Result; //Customer customer = userCustomers.First(); //Session["ActiveCustomer"] = customer; var identity = userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie).Result; identity.AddClaim(new Claim("FullName", user.FirstName + ' ' + user.LastName)); identity.AddClaim(new Claim("Email", user.Email)); identity.AddClaim(new Claim("TermsAndConditionsAccepted", user.TermsAndConditionsAccepted ? "1" : "0")); Session["Culture"] = user.Culture; string culture = CultureHelper.GetImplementedCulture(user.Culture); HttpCookie cookie = Request.Cookies["_culture"]; if (cookie != null) { cookie.Value = culture; } else { cookie = new HttpCookie("_culture"); cookie.Value = culture; cookie.Expires = DateTime.Now.AddYears(1); } Response.Cookies.Add(cookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); }