Admin import functional

This commit is contained in:
2014-02-02 10:19:02 -05:00
parent 13c5c6cde5
commit 3ab80e283a
41 changed files with 2809 additions and 101 deletions
+211 -2
View File
@@ -1,10 +1,16 @@
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Models;
using MileageTraker.Web.Utility;
using MileageTraker.Web.ViewModels;
using MileageTraker.Web.ViewModels.CreateLog;
using MileageTraker.Web.ViewModels.Log;
using MileageTraker.Web.ViewModels.Vehicle;
@@ -63,7 +69,7 @@ namespace MileageTraker.Web.Controllers
query.Month,
query.LogType.HasValue ? "-" + query.LogType.Value.GetDisplayShortName() : "");
var export = ExcelWriter.WriteXls(filteredLogs, name, name);
var export = ExcelWriter<LogIndexViewModel>.WriteXls(filteredLogs, name, name);
return File(export, "application/ms-excel", name + ".xls");
}
@@ -168,6 +174,13 @@ namespace MileageTraker.Web.Controllers
return View(viewModel);
}
[HttpGet]
public ActionResult Create(LogImportViewModel viewModel)
{
// TODO: complete?
return View();
}
public ActionResult Edit(int id)
{
var log = DataService.GetLog(id);
@@ -236,5 +249,201 @@ namespace MileageTraker.Web.Controllers
var log = DataService.GetLog(id);
return PartialView(new LogPartialDetails(log));
}
}
// TODO: Fix?
public ActionResult ImportUpload()
{
return View();
}
[HttpPost]
public ActionResult Import(ImportUploadViewModel viewModel)
{
if (ModelState.IsValid && viewModel.File != null && viewModel.File.ContentLength > 0)
{
var user = DataService.FindUserByFullName(viewModel.UserName) ??
DataService.FindUserByUsername(viewModel.UserName);
if (user == null)
{
TempData["StatusMessage"] = "User " + viewModel.UserName + " not found";
TempData["StatusMessage-Type"] = "alert-error";
}
else
{
ViewData["UserFullName"] = user.FullName;
var fileName = Path.GetFileName(viewModel.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
viewModel.File.SaveAs(path);
IEnumerable<LogImportViewModel> logImports;
try
{
logImports = LogImporter.Import(path);
// todo: delete file?
return View(logImports.ToList());
}
catch (Exception ex)
{
TempData["StatusMessage"] = "Problem reading excel document: " + ex.Message;
TempData["StatusMessage-Type"] = "alert-error";
}
}
}
return RedirectToAction("ImportUpload");
}
enum ImportStatus
{
Success,
Failure,
Duplicate
}
[HttpPost]
[ActionLog]
public ActionResult ImportCreate(LogImportViewModel viewModel, string userFullName)
{
var buttonAttributes = new Dictionary<string, object> { { "class", "btn btn-mini" }, { "target", "_blank" } };
var correctItLink = HtmlHelper.GenerateLink(
ControllerContext.RequestContext, RouteTable.Routes,
"Correct", "Default", "Create", "Log",
null,
buttonAttributes);
try
{
// verify log type
if (!typeof (MileageLogType).IsValidValue(viewModel.LogType))
{
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = "Invalid Log Type: \"" + viewModel.LogType + "\"",
//Action = correctItLink
}, JsonRequestBehavior.AllowGet);
}
// verify purpose
var purposeType = DataService.FindPurposeType(viewModel.Purpose);
if (purposeType == null)
{
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = "Invalid Purpose: " + viewModel.Purpose,
//Action = correctItLink
}, JsonRequestBehavior.AllowGet);
}
if (!ModelState.IsValid)
{
var errorList = GetModelStateErrorList(ModelState);
// remove the object name from the errors
errorList = errorList.Select(s => s.Replace("viewModel.", ""));
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = string.Join(", ", errorList),
//Action = correctItLink
}, JsonRequestBehavior.AllowGet);
}
var log = viewModel.GetLog();
log.User = DataService.FindUserByFullName(userFullName);
log.Source = HttpContext.Request.Url.AbsolutePath;
log.UserHostAddress = HttpContext.Request.UserHostAddress;
log.UserAgent = HttpContext.Request.UserAgent;
log.Purpose = purposeType;
// check duplicate
var duplicateLogs = DataService.GetDuplicateLogs(log).ToList();
if (duplicateLogs.Any())
{
var link = HtmlHelper.GenerateLink(
ControllerContext.RequestContext, RouteTable.Routes,
"Details", "Default", "Details", "Log",
new RouteValueDictionary(new{ id = duplicateLogs.First().LogId }),
buttonAttributes);
return Json(new
{
Status = ImportStatus.Duplicate.ToString(),
Message = "This log has been previously entered",
Action = link
}, JsonRequestBehavior.AllowGet);
}
// verify vehicle exists
if (DataService.GetVehicle(log.VehicleId) == null)
{
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = "Vehile with supplied ID does not exist",
Action = correctItLink
}, JsonRequestBehavior.AllowGet);
}
// SAVE IT!
DataService.AddLog(log);
var successLink = HtmlHelper.GenerateLink(
ControllerContext.RequestContext, RouteTable.Routes,
"Details", "Default", "Details", "Log",
new RouteValueDictionary(new { id = log.LogId }),
buttonAttributes);
return Json(new
{
Status = ImportStatus.Success.ToString(),
Action = successLink
}, JsonRequestBehavior.AllowGet);
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join(", ", errorMessages);
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = fullErrorMessage,
Action = correctItLink
},
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var message = ex.Message;
return Json(new
{
Status = ImportStatus.Failure.ToString(),
Message = message,
Action = correctItLink
}, JsonRequestBehavior.AllowGet);
}
}
private static IEnumerable<string> GetModelStateErrorList(ModelStateDictionary modelStateDictionary)
{
var errorList =
from kvp in modelStateDictionary
where kvp.Value.Errors.Any()
let errors = string.Join(", ", kvp.Value.Errors.Select(e => e.ErrorMessage))
let msg = kvp.Key + ": " + errors
select msg;
return errorList;
}
public ActionResult ImportTemplate()
{
var template = LogImportTemplateWriter.Write();
return File(template, "application/ms-excel", "MileageTraker_ImportTemplate.xls");
}
}
}