EnVisageOnline/Main/Source/EnVisage/Controllers/ClientsController.cs

424 lines
14 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EnVisage.Code;
using EnVisage.Code.BLL;
using EnVisage.Models;
using jQuery.DataTables.Mvc;
using EnVisage.App_Start;
namespace EnVisage.Controllers
{
[Authorize]
public class ClientsController : BaseController
{
#region Actions
/// <summary>
/// GET: /Clients/
/// </summary>
/// <returns>Empty view</returns>
[HttpGet]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Read)]
public ActionResult Index()
{
return View();
}
/// <summary>
/// Returns JSON client list with filters and sort for jQuery DataTables
/// </summary>
[HttpPost]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Read)]
public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel)
{
int totalRecordCount;
int searchRecordCount;
var clients = GetClients(startIndex: jQueryDataTablesModel.iDisplayStart,
pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(),
totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch,
filters: jQueryDataTablesModel.sSearch_);
return this.DataTablesJson(items: clients,
totalRecords: totalRecordCount,
totalDisplayRecords: searchRecordCount,
sEcho: jQueryDataTablesModel.sEcho);
}
// GET: /Clients/Edit/5
[HttpGet]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult Edit(Guid? id)
{
var model = new ClientModel();
try
{
if (id.HasValue)
{
var manager = new ClientManager(DbContext);
model = manager.LoadWithChildCollections(id.Value) ?? new ClientModel();
}
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
// POST: /Clients/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult Edit(ClientModel model)
{
if (ContentLocker.IsLock("Clients", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
model.TrimStringProperties();
if (ModelState.IsValid)
{
try
{
var manager = new ClientManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Clients", model.Id.ToString(), User.Identity.GetUserName());
return RedirectToAction("Index");
}
catch (BLLException blEx) // handle any system specific error
{
// display error message if required
if (blEx.DisplayError)
ModelState.AddModelError(string.Empty, blEx.Message);
else // if display not requried then display modal form with general error message
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception) // handle any unexpected error
{
LogException(exception);
SetErrorScript();
}
}
// return empty model with validation messages (if any)
return View(model);
}
[HttpGet]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult Delete(Guid? id)
{
if (id == null || id == Guid.Empty)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var model = new ClientModel();
try
{
var manager = new ClientManager(DbContext);
model = manager.LoadClientModel(id.Value);
if (model == null)
return HttpNotFound();
if (model.ProjectsCount > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest,
"Client has projects assigned and could not be deleted");
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
[HttpGet]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult AddContact(Guid Id)
{
if (Id == Guid.Empty)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return PartialView("_addContact", new ContactModel(Id));
}
[HttpPost]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult AddContact(ContactModel model)
{
//if (model.ScenarioId != Guid.Empty && ContentLocker.IsLock("Scenarios", model.ScenarioId.ToString(), User.Identity.GetUserName()))
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
model.TrimStringProperties();
if (ModelState.IsValid)
{
try
{
model.Type = ContactType.ClientContact;
var newcontact = new Contact();
model.CopyTo(newcontact);
if (newcontact.Id == Guid.Empty)
newcontact.Id = Guid.NewGuid();
DbContext.Contacts.Add(newcontact);
DbContext.SaveChanges();
}
catch (BLLException blEx) // handle any system specific error
{
// display error message if required
if (blEx.DisplayError)
ModelState.AddModelError(string.Empty, blEx.Message);
else // if display not requried then display modal form with general error message
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception) // handle any unexpected error
{
LogException(exception);
SetErrorScript();
}
}
var url = HttpContext.Request.UrlReferrer.PathAndQuery;
if (Url.IsLocalUrl(url))
return Redirect(url);
return Redirect("/");
}
// POST: /Clients/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult Delete(ClientModel model)
{
if (ContentLocker.IsLock("Clients", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var manager = new ClientManager(DbContext);
var dbObj = manager.Load(model.Id, false);
if (dbObj == null)
return HttpNotFound();
if (dbObj.Projects.Count > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest,
"Client has projects assigned and could not be deleted");
DbContext.Company2Client.RemoveRange(DbContext.Company2Client.Where(c2s => c2s.ClientId == dbObj.Id));
DbContext.Contact2Project.RemoveRange(DbContext.Contact2Project.Where(c2s => c2s.Contact.ParentId == dbObj.Id));
DbContext.Contacts.RemoveRange(DbContext.Contacts.Where(c => c.ParentId == dbObj.Id));
DbContext.Clients.Remove(dbObj);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Clients", dbObj.Id.ToString(), User.Identity.GetUserName());
return RedirectToAction("Index");
}
// GET: /User/Edit/5
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult EditContact(string Id)
{
if (string.IsNullOrEmpty(Id) || Id == "JSVar")
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var contactId = new Guid(Id);
var contact = new ContactManager(DbContext).LoadContactModel(contactId);
if (contact == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return PartialView("_addContact", contact);
}
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult EditContact(ContactModel model)
{
model.TrimStringProperties();
//if (model.Id == new Guid()) model.Id = Guid.NewGuid();
if (ModelState.IsValid)
{
try
{
var manager = new ContactManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Contact", model.Id.ToString(), User.Identity.GetUserName());
var url1 = HttpContext.Request.UrlReferrer.PathAndQuery;
if (Url.IsLocalUrl(url1))
return Redirect(url1);
return Redirect("/");
}
catch (BLLException blEx) // handle any system specific error
{
// display error message if required
if (blEx.DisplayError)
ModelState.AddModelError(string.Empty, blEx.Message);
else // if display not requried then display modal form with general error message
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception) // handle any unexpected error
{
LogException(exception);
SetErrorScript();
}
}
// return empty model with validation messages (if any)
var url = HttpContext.Request.UrlReferrer.PathAndQuery;
if (Url.IsLocalUrl(url))
return Redirect(url);
return Redirect("/");
}
[AreaSecurity(area = Areas.Clients, level = AccessLevel.Write)]
public ActionResult DeleteContact(string Id)
{
if (string.IsNullOrEmpty(Id) || Id == "JSVar")
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Guid contactId;
if (!Guid.TryParse(Id, out contactId) || contactId == Guid.Empty)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var contact = DbContext.Contacts.FirstOrDefault(c => c.Id == contactId);
if (contact != null)
{
DbContext.Contacts.Remove(contact);
DbContext.SaveChanges();
}
var url = HttpContext.Request.UrlReferrer.PathAndQuery;
return Redirect(Url.IsLocalUrl(url) ? url : "/");
}
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult LoadClients()
{
try
{
var dictionary = new Dictionary<string, ClientApiModel>();
var clients = new ClientManager(DbContext).GetListReadOnly().ToList();
if (clients.Any())
{
dictionary = clients.Select(x => new ClientApiModel(x))
.ToDictionary(x => x.Id.ToString());
}
return Json(dictionary);
}
catch (Exception exception)
{
LogException(exception);
}
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
#endregion
#region Private Methods
private IList<ClientListModel> GetClients(int startIndex,
int pageSize,
ReadOnlyCollection<SortedColumn> sortedColumns,
out int totalRecordCount,
out int searchRecordCount,
string searchString,
ReadOnlyCollection<string> filters)
{
var mngr = new ClientManager(DbContext);
var query = mngr.GetListReadOnly();
//filter
if (!string.IsNullOrWhiteSpace(searchString))
{
query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower()));
}
if (!string.IsNullOrWhiteSpace(filters[0]))
query = query.Where(c => c.Name.ToLower().Contains(filters[0].ToLower()));
if (!string.IsNullOrWhiteSpace(filters[1]))
query = query.Where(c => c.ProjectsCount.ToString().Contains(filters[1]));
if (!string.IsNullOrWhiteSpace(filters[2]) && filters[2] != "All companies")
{
var q = new List<ClientListModel>();
foreach (var companies in query.Select(x => x.Companies))
{
foreach (var company in companies)
{
if (company.ToLower().Contains(filters[2].ToLower()))
{
foreach (var c in query.Where(c => c.Companies.Contains(company)))
{
if (q.All(x => x.Id != c.Id) && c.Companies.Any(x => x == filters[2]))
q.Add(c);
}
}
}
}
query = q.AsEnumerable();
}
//sort
foreach (var sortedColumn in sortedColumns)
{
switch (sortedColumn.PropertyName)
{
case "Id":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Id) : query.OrderByDescending(c => c.Id);
break;
case "ProjectsCount":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.ProjectsCount) : query.OrderByDescending(c => c.ProjectsCount);
break;
case "ClientNumber":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.ClientNumber) : query.OrderByDescending(c => c.ClientNumber);
break;
default:
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Name) : query.OrderByDescending(c => c.Name);
break;
}
}
totalRecordCount = DbContext.Clients.Count();
searchRecordCount = query.Count();
return query.Skip(startIndex).Take(pageSize).ToList();
}
#endregion
}
}