using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using EnVisage; using EnVisage.App_Start; using EnVisage.Code; using EnVisage.Code.BLL; using EnVisage.Models; using jQuery.DataTables.Mvc; using EnVisage.Code.HtmlHelpers; using Microsoft.AspNet.Identity; namespace EnVisage.Controllers { [Authorize] public class CompanyController : BaseController { /// /// 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 IList Clients { get; set; } public IList Views { get; set; } } /// /// GET: /Company/ /// /// Parent company view [AreaSecurityAttribute(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 = (CompanyModel)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] [AreaSecurityAttribute(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); } private IList GetChildCompanies(int startIndex, int pageSize, ReadOnlyCollection sortedColumns, out int totalRecordCount, out int searchRecordCount, string searchString) { IQueryable query = from c in DbContext.Companies where c.ParentCompanyId != null select new ListCompany() { Id = c.Id, Name = c.Name, ProjectsCount = c.Projects.Count(), CompaniesCount = c.Company1.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": if (sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.Id); else query = query.OrderByDescending(c => c.Id); break; case "ProjectsCount": if (sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.ProjectsCount); else query = query.OrderByDescending(c => c.ProjectsCount); break; default: if (sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.Name); else query = query.OrderByDescending(c => c.Name); break; } } totalRecordCount = DbContext.Companies.Count(c => c.ParentCompanyId != null); searchRecordCount = query.Count(); return query.Skip(startIndex).Take(pageSize).ToList(); } // GET: /Company/EditParent/5 [HttpGet] [AreaSecurityAttribute(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 = (CompanyModel)manager.Load(id) ?? new CompanyModel(); if (model.Id == Guid.Empty) return HttpNotFound(); } 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] [AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)] public ActionResult EditParent(CompanyModel model) { if (model == null || ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.Name)) 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.Name); 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] [AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)] public ActionResult Edit(Guid? id) { var model = new CompanyModel(); try { var manager = new CompanyManager(DbContext); model = (CompanyModel)manager.LoadWithChildCollections(id) ?? 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); } // 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] [AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)] public ActionResult Edit(CompanyModel model) { if (model == null || ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.Name)) 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.Name); 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] [AreaSecurityAttribute(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 = (CompanyModel)manager.Load(id); if (model == null) return HttpNotFound(); if (model.ProjectsCount > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Company has assigned projects and could not be deleted"); if (model.CompaniesCount > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Company has child companies 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); } // POST: /Company/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)] public ActionResult Delete(CompanyModel model) { if (ContentLocker.IsLock("Company", model.Id.ToString(), User.Identity.Name)) 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, "Company has assigned projects and could not be deleted"); if (dbObj.Company1.Count > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Company has child companies and could not be deleted"); DbContext.Company2View.RemoveRange(DbContext.Company2View.Where(c2s => c2s.CompanyId == dbObj.Id)); DbContext.Company2Client.RemoveRange(DbContext.Company2Client.Where(c2s => c2s.CompanyId == 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.StrategicGoal2Company.RemoveRange(DbContext.StrategicGoal2Company.Where(s2c => s2c.CompanyId == dbObj.Id)); DbContext.Companies.Remove(dbObj); DbContext.SaveChanges(); ContentLocker.RemoveLock("Company", dbObj.Id.ToString(), User.Identity.Name); return RedirectToAction("Index"); } [AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)] public ActionResult AddEditCompany(Guid? id) { var model = new CompanyModel(); try { var manager = new CompanyManager(DbContext); model = (CompanyModel)manager.LoadWithChildCollections(id) ?? new CompanyModel(); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return PartialView("_addCompany", model); } } }