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

270 lines
9.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using EnVisage;
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
{
/// <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; }
}
// GET: /Contact/
public ActionResult Index()
{
return View();
}
/// <summary>
/// Returns JSON user list with filters and sort for jQuery DataTables
/// </summary>
[HttpPost]
[AreaSecurityAttribute(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);
}
private IEnumerable<ListCompanyContact> GetContacts(int startIndex,
int pageSize,
IEnumerable<SortedColumn> sortedColumns,
out int totalRecordCount,
out int searchRecordCount,
string searchString)
{
int companyContactType = ContactType.CompanyContact.GetHashCode();
var query = from c in DbContext.Contacts
join cmp in DbContext.Companies on c.ParentId equals cmp.Id
where c.Type == companyContactType
select new ListCompanyContact
{
Id = c.Id,
FirstName = c.FirstName,
LastName = c.LastName,
Email = c.Email,
Phone = c.Phone,
Company = cmp.Name,
Contact2ProjectLinks = c.Contact2Project.Count(),
Classification = ((InternalContactClassification)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":
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.Email);
else
query = query.OrderByDescending(c => c.Email);
break;
case "Phone":
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.Phone);
else
query = query.OrderByDescending(c => c.Phone);
break;
case "Company":
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.Company);
else
query = query.OrderByDescending(c => c.Company);
break;
case "Contact2ProjectLinks":
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.Contact2ProjectLinks);
else
query = query.OrderByDescending(c => c.Contact2ProjectLinks);
break;
case "Classification":
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.Classification);
else
query = query.OrderByDescending(c => c.Classification);
break;
default:
if (sortedColumn.Direction == SortingDirection.Ascending)
query = query.OrderBy(c => c.LastName);
else
query = query.OrderByDescending(c => c.LastName);
break;
}
}
totalRecordCount = DbContext.Contacts.Where(c => c.Type == companyContactType).Count();
searchRecordCount = query.Count();
return query.Skip(startIndex).Take(pageSize).ToList();
}
// GET: /Contact/Edit/5
[HttpGet]
[AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Edit(Guid? id)
{
var model = new ContactModel();
try
{
var manager = new ContactManager(DbContext);
model = (ContactModel)manager.Load(id) ?? new ContactModel();
}
catch (BLLException blEx)
{
if (blEx.DisplayError)
SetErrorScript(message: blEx.Message);
else
{
LogException(blEx);
SetErrorScript();
}
}
catch (Exception exception)
{
LogException(exception);
SetErrorScript();
}
if (model == null) model = new ContactModel();
return View(model);
}
// POST: /Contact/Edit/5
// Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные
// сведения см. в статье http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Edit(ContactModel model)
{
if (ContentLocker.IsLock("Contact", model.Id.ToString(), User.Identity.Name))
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.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: /Contact/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 ContactModel();
try
{
var manager = new ContactManager(DbContext);
model = (ContactModel)manager.Load(id);
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]
[AreaSecurityAttribute(area = Areas.Company, level = AccessLevel.Write)]
public ActionResult Delete(ContactModel model)
{
if (ContentLocker.IsLock("Contact", model.Id.ToString(), User.Identity.Name))
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.Name);
return RedirectToAction("Index");
}
}
}