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

263 lines
8.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using EnVisage.Code;
using jQuery.DataTables.Mvc;
using EnVisage.Models;
using EnVisage.Code.BLL;
using EnVisage.App_Start;
namespace EnVisage.Controllers
{
public class ContactController : BaseController
{
#region Actions
// GET: /Contact/
public ActionResult Index()
{
return View();
}
/// <summary>
/// Returns JSON user list with filters and sort for jQuery DataTables
/// </summary>
[HttpPost]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Read)]
public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel)
{
int totalRecordCount;
int searchRecordCount;
var contacts = GetContacts(startIndex: jQueryDataTablesModel.iDisplayStart,
pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(),
totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch);
return this.DataTablesJson(items: contacts,
totalRecords: totalRecordCount,
totalDisplayRecords: searchRecordCount,
sEcho: jQueryDataTablesModel.sEcho);
}
// GET: /Contact/Edit/5
[HttpGet]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Edit(Guid? id)
{
var model = new ContactModel();
try
{
if (id.HasValue)
{
var manager = new ContactManager(DbContext);
model = manager.LoadContactModel(id.Value) ?? new ContactModel();
}
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
return View(model);
}
// POST: /Contact/Edit/5
// Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные
// сведения см. в статье http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Edit(ContactModel model)
{
if (ContentLocker.IsLock("Contact", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
model.TrimStringProperties();
//if (model.Id == new Guid()) model.Id = Guid.NewGuid();
if (ModelState.IsValid)
{
try
{
model.Type = ContactType.CompanyContact;
var manager = new ContactManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Contact", 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: /Contact/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 ContactModel();
try
{
var manager = new ContactManager(DbContext);
model = manager.LoadContactModel(id.Value);
if (model == null)
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: /Contact/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Delete(ContactModel model)
{
if (ContentLocker.IsLock("Contact", model.Id.ToString(), User.Identity.GetUserName()))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var manager = new ContactManager(DbContext);
var dbObj = manager.Load(model.Id, false);
if (dbObj == null)
return HttpNotFound();
DbContext.Contacts.Remove(dbObj);
DbContext.SaveChanges();
ContentLocker.RemoveLock("Contact", dbObj.Id.ToString(), User.Identity.GetUserName());
return RedirectToAction("Index");
}
#endregion
#region Models
/// <summary>
/// An UI representation of company contact to be displayed as list items
/// </summary>
public class ListCompanyContact
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int Contact2ProjectLinks { get; set; }
public string Classification { get; set; }
}
#endregion
#region Private Methods
private IEnumerable<ListCompanyContact> GetContacts(int startIndex,
int pageSize,
IEnumerable<SortedColumn> sortedColumns,
out int totalRecordCount,
out int searchRecordCount,
string searchString)
{
var companyContactType = ContactType.CompanyContact;
var query = DbContext.Contacts
.Join(DbContext.Companies, c => c.ParentId, cmp => cmp.Id, (c, cmp) => new { c, cmp })
.Where(t => t.c.Type == companyContactType)
.Select(t => new ListCompanyContact
{
Id = t.c.Id,
FirstName = t.c.FirstName,
LastName = t.c.LastName,
Email = t.c.Email,
Phone = t.c.Phone,
Company = t.cmp.Name,
Contact2ProjectLinks = t.c.Contact2Project.Count,
Classification = ((InternalContactClassification)t.c.ContactClassification).ToString()
});
//filter
if (!string.IsNullOrWhiteSpace(searchString))
{
query = query.Where(c => c.LastName.ToLower().Contains(searchString.ToLower()) || c.FirstName.ToLower().Contains(searchString.ToLower()));
}
//sort
foreach (var sortedColumn in sortedColumns)
{
switch (sortedColumn.PropertyName)
{
case "Email":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Email) : query.OrderByDescending(c => c.Email);
break;
case "Phone":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Phone) : query.OrderByDescending(c => c.Phone);
break;
case "Company":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Company) : query.OrderByDescending(c => c.Company);
break;
case "Contact2ProjectLinks":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Contact2ProjectLinks) : query.OrderByDescending(c => c.Contact2ProjectLinks);
break;
case "Classification":
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Classification) : query.OrderByDescending(c => c.Classification);
break;
default:
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.LastName) : query.OrderByDescending(c => c.LastName);
break;
}
}
totalRecordCount = DbContext.Contacts.Count(c => c.Type == companyContactType);
searchRecordCount = query.Count();
return query.Skip(startIndex).Take(pageSize).ToList();
}
#endregion
}
}