using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EnVisage.App_Start;
using EnVisage.Code;
using EnVisage.Code.BLL;
using EnVisage.Models;
using jQuery.DataTables.Mvc;
using Resources;
namespace EnVisage.Controllers
{
[Authorize]
public class CompanyController : BaseController
{
#region Actions
///
/// GET: /Company/
///
/// Parent company view
[AreaSecurity(area = Areas.Company, level = AccessLevel.Read)]
public ActionResult Index()
{
if (!SecurityManager.CheckSecurityObjectPermission(Areas.Company, AccessLevel.Read))
return Redirect("/");
var model = new CompanyModel();
try
{
var manager = new CompanyManager(DbContext);
model = manager.LoadParent() ?? new CompanyModel();
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
///
/// Returns JSON company list with filters and sort for jQuery DataTables
///
[HttpPost]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Read)]
public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel)
{
int totalRecordCount;
int searchRecordCount;
var clients = GetChildCompanies(startIndex: jQueryDataTablesModel.iDisplayStart,
pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(),
totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch);
return this.DataTablesJson(items: clients,
totalRecords: totalRecordCount,
totalDisplayRecords: searchRecordCount,
sEcho: jQueryDataTablesModel.sEcho);
}
// GET: /Company/EditParent/5
[HttpGet]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult EditParent(Guid? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var model = new CompanyModel();
try
{
var manager = new CompanyManager(DbContext);
model = manager.LoadCompanyModel(id.Value);
if (model == null || model.Id == Guid.Empty)
return HttpNotFound();
// Load company attached users
model.Watchers = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && (x.RelationType == CollaborationRole.Watcher)).Select(x => x.UserId).ToList();
model.Contributors = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && (x.RelationType == CollaborationRole.Contributor)).Select(x => x.UserId).ToList();
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
// POST: /Company/EditParent/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.Company, level = AccessLevel.Write)]
public ActionResult EditParent(CompanyModel model)
{
if (model == null || ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
model.TrimStringProperties();
if (ModelState.IsValid)
{
try
{
var manager = new CompanyManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Company", 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);
}
// GET: /Company/Edit/5
[HttpGet]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Edit(Guid? id)
{
var model = new CompanyModel();
try
{
if (id.HasValue)
{
var manager = new CompanyManager(DbContext);
model = manager.LoadWithChildCollections(id.Value) ?? new CompanyModel();
// Load company attached users
model.Watchers = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && (x.RelationType == CollaborationRole.Watcher)).Select(x => x.UserId).ToList();
model.Contributors = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && (x.RelationType == CollaborationRole.Contributor)).Select(x => x.UserId).ToList();
}
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
// POST: /Company/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.Company, level = AccessLevel.Write)]
public ActionResult Edit(CompanyModel model)
{
if (model == null || ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
model.TrimStringProperties();
if (ModelState.IsValid)
{
try
{
var manager = new CompanyManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Company", 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);
}
// GET: /Company/Delete/5
[HttpGet]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Delete(Guid? id)
{
if (id == null || id == Guid.Empty)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var model = new CompanyModel();
try
{
var manager = new CompanyManager(DbContext);
model = manager.LoadCompanyModel(id.Value);
if (model == null)
return HttpNotFound();
if (model.ProjectsCount > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasAssignedProjects_Error);
if (model.CompaniesCount > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasChildCompanies_Error);
if (model.TeamsCount > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasAssignedTeams_Error);
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
// POST: /Company/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Delete(CompanyModel model)
{
if (ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var manager = new CompanyManager(DbContext);
var dbObj = manager.Load(model.Id, false);
if (dbObj == null)
return HttpNotFound();
if (dbObj.Projects.Count > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasAssignedProjects_Error);
if (dbObj.Company1.Count > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasChildCompanies_Error);
if (dbObj.Teams.Count > 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Company_Delete_CompanyHasAssignedTeams_Error);
// Related Views, Clients & Strategic Goals are deleted via db-cascade delete constraints
DbContext.Contact2Project.RemoveRange(DbContext.Contact2Project.Where(c2s => c2s.Contact.ParentId == dbObj.Id));
DbContext.Contacts.RemoveRange(DbContext.Contacts.Where(c => c.ParentId == dbObj.Id));
DbContext.Companies.Remove(dbObj);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Company", dbObj.Id.ToString(), User.Identity.GetUserName());
return RedirectToAction("Index");
}
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult AddEditCompany(Guid? id)
{
var model = new CompanyModel();
try
{
if (id.HasValue)
{
var manager = new CompanyManager(DbContext);
model = manager.LoadWithChildCollections(id.Value) ?? new CompanyModel();
// Load company attached users
model.Watchers = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && x.RelationType == CollaborationRole.Watcher).Select(x => x.UserId).ToList();
model.Contributors = DbContext.User2Company.Where(x => x.CompanyId.Equals(model.Id) && x.RelationType == CollaborationRole.Contributor).Select(x => x.UserId).ToList();
}
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return PartialView("_addCompany", model);
}
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult LoadCompanies()
{
try
{
var dictionary = new Dictionary();
var companies = new CompanyManager(DbContext).LoadCompanies();
if (companies != null && companies.Any())
{
dictionary = companies.Select(x => new CompanyApiModel(x))
.ToDictionary(x => x.Id.ToString());
}
return Json(dictionary);
}
catch (Exception exception)
{
LogException(exception);
}
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
#endregion
#region Models
///
/// An UI representation of company to be displayed as list items
///
public class ListCompany
{
public Guid Id { get; set; }
public string Name { get; set; }
public int ProjectsCount { get; set; }
public int CompaniesCount { get; set; }
public int TeamsCount { get; set; }
public IList Clients { get; set; }
public IList Views { get; set; }
}
#endregion
#region Private Methods
private IList GetChildCompanies(int startIndex,
int pageSize,
ReadOnlyCollection sortedColumns,
out int totalRecordCount,
out int searchRecordCount,
string searchString)
{
IQueryable query =
DbContext.Companies.Include(x => x.Projects)
.Include(x => x.Company2Client)
.Include(x => x.Company2View)
.Include(x => x.Teams)
.AsNoTracking()
.Where(c => c.ParentCompanyId != null)
.Select(c => new ListCompany
{
Id = c.Id,
Name = c.Name,
ProjectsCount = c.Projects.Count,
CompaniesCount = c.Company1.Count,
TeamsCount = c.Teams.Count,
Clients = c.Company2Client.Select(x => x.Client.Name).ToList(),
Views = c.Company2View.Select(x => x.View.Name).ToList()
});
//filter
if (!string.IsNullOrWhiteSpace(searchString))
{
query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower()));
}
//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 "TeamsCount":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.TeamsCount) : query.OrderByDescending(c => c.TeamsCount);
break;
default:
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Name) : query.OrderByDescending(c => c.Name);
break;
}
}
totalRecordCount = DbContext.Companies.Count(c => c.ParentCompanyId != null);
searchRecordCount = query.Count();
return query.Skip(startIndex).Take(pageSize).ToList();
}
#endregion
}
}