initial add

This commit is contained in:
Jonathan Ouellette
2022-09-27 14:10:30 -07:00
parent 91fd8a50a9
commit 580e90f6a2
3941 changed files with 954648 additions and 19 deletions

View File

@ -0,0 +1,531 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Fab2ApprovalSystem.Models;
using System.Web.Security;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.DMO;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
//
// GET: /Account/Login
[AllowAnonymous]
// try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
try
{
//if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
//{
// return RedirectToLocal(returnUrl);
//}
UserAccountDMO userDMO = new UserAccountDMO();
bool isLoginValid;
MembershipProvider domainProvider;
#if(DEBUG)
isLoginValid = true;
#endif
#if (!DEBUG)
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
isLoginValid = true;
else
{
isLoginValid = Functions.NA_ADAuthenticate(model.LoginID, model.Password);
if (!isLoginValid)
{
isLoginValid = Functions.IFX_ADAuthenticate(model.LoginID, model.Password);
isIFX = true;
}
}
#endif
if (isLoginValid)
{
//Check ITAR Permissions from AD group
#if(!DEBUG)
try
{
bool hasITARAccess = false;
//========TEMP CODE - NEEDS TO BE DELETED
//Functions.WriteEvent("Using DB for EC Auth for user " + model.LoginID, System.Diagnostics.EventLogEntryType.Information);
//hasITARAccess = userDMO.GetEC_AD_Users(model.LoginID);
//=============END OF TEMP CODE
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
hasITARAccess = true;
}
else
{
hasITARAccess = Functions.NA_HasITARAccess(model.LoginID, model.Password);
if (!hasITARAccess) // check the IFX domain
hasITARAccess = Functions.IFX_HasITARAccess(model.LoginID, model.Password);
}
userDMO.UpdateInsertITARAccess(model.LoginID, hasITARAccess ? "1" : "0");
}
catch (Exception ex)
{
ModelState.AddModelError("", "Not a member of the EC Domain" + ex.Message);
return View(model);
}
#endif
LoginModel user = userDMO.GetUser(model.LoginID);
if (user != null)
{
Session[GlobalVars.SESSION_USERID] = user.UserID;
Session[GlobalVars.SESSION_USERNAME] = user.FullName;
Session[GlobalVars.IS_ADMIN] = user.IsAdmin;
Session[GlobalVars.OOO] = user.OOO;
Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID);
FormsAuthentication.SetAuthCookie(user.LoginID, true);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
catch (Exception ex)
{
Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException , System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message);
}
return View(model);
// If we got this far, something failed, redisplay form
}
////
//// POST: /Account/Login
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
//{
// if (ModelState.IsValid)
// {
// var user = await UserManager.FindAsync(model.UserName, model.Password);
// if (user != null)
// {
// await SignInAsync(user, model.RememberMe);
// return RedirectToLocal(returnUrl);
// }
// else
// {
// ModelState.AddModelError("", "Invalid username or password.");
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Register(RegisterViewModel model)
//{
// if (ModelState.IsValid)
// {
// var user = new ApplicationUser() { UserName = model.UserName };
// var result = await UserManager.CreateAsync(user, model.Password);
// if (result.Succeeded)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToAction("Index", "Home");
// }
// else
// {
// AddErrors(result);
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
//ViewBag.StatusMessage =
// message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
// : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
// : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
// : message == ManageMessageId.Error ? "An error has occurred."
// : "";
//ViewBag.HasLocalPassword = HasPassword();
//ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
////
//// POST: /Account/Manage
//[HttpPost]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Manage(ManageUserViewModel model)
//{
// bool hasPassword = HasPassword();
// ViewBag.HasLocalPassword = hasPassword;
// ViewBag.ReturnUrl = Url.Action("Manage");
// if (hasPassword)
// {
// if (ModelState.IsValid)
// {
// IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
// if (result.Succeeded)
// {
// return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
// }
// else
// {
// AddErrors(result);
// }
// }
// }
// else
// {
// // User does not have a password so remove any validation errors caused by a missing OldPassword field
// ModelState state = ModelState["OldPassword"];
// if (state != null)
// {
// state.Errors.Clear();
// }
// if (ModelState.IsValid)
// {
// IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
// if (result.Succeeded)
// {
// return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
// }
// else
// {
// AddErrors(result);
// }
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
////
//// GET: /Account/ExternalLoginCallback
//[AllowAnonymous]
//public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
//{
// var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
// if (loginInfo == null)
// {
// return RedirectToAction("Login");
// }
// // Sign in the user with this external login provider if the user already has a login
// var user = await UserManager.FindAsync(loginInfo.Login);
// if (user != null)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToLocal(returnUrl);
// }
// else
// {
// // If the user does not have an account, then prompt the user to create an account
// ViewBag.ReturnUrl = returnUrl;
// ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
// return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName });
// }
//}
//
// POST: /Account/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
}
//
// GET: /Account/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded)
{
return RedirectToAction("Manage");
}
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
//
// POST: /Account/ExternalLoginConfirmation
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
//{
// if (User.Identity.IsAuthenticated)
// {
// return RedirectToAction("Manage");
// }
// if (ModelState.IsValid)
// {
// // Get the information about the user from the external login provider
// var info = await AuthenticationManager.GetExternalLoginInfoAsync();
// if (info == null)
// {
// return View("ExternalLoginFailure");
// }
// var user = new ApplicationUser() { UserName = model.UserName };
// var result = await UserManager.CreateAsync(user);
// if (result.Succeeded)
// {
// result = await UserManager.AddLoginAsync(user.Id, info.Login);
// if (result.Succeeded)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToLocal(returnUrl);
// }
// }
// AddErrors(result);
// }
// ViewBag.ReturnUrl = returnUrl;
// return View(model);
//}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
//AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
//AuthenticationManager.SignOut();
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
//return RedirectToAction("HierarchicalDataTest", "Home");
return RedirectToAction("MyTasks", "Home");
//return RedirectToAction("Index", "Home", new { tabName = "MyTasks"});
}
}
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
}

View File

@ -0,0 +1,630 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
public class AdminController : Controller
{
// GET: /Admin/
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
var model = userDMO.GetAllUsers();
return View(model);
}
else
return Content("Not Autthorized");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult AssignRoles()
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
ViewBag.ToplevelNode = GetRoles_SubRolesList();
return View();
}
else
return Content("Not Autthorized");
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request)
{
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// For the Administration of the Users
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request)
{
return Json(userDMO.GetAllUsers().ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="subRole"></param>
/// <returns></returns>
public JsonResult GetAllUserListBySubRole(int subRole)
{
IEnumerable<LoginModel> userlist = adminDMO.GetAllUsersBySubRole(subRole);
return Json(userlist, JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public JsonResult AllSubRoles(string showInactiveRoles = "")
{
List<Role> roles = adminDMO.GetSubRoles();
ParentChildModel parent;
ParentChildModel child = new ParentChildModel();
List<ParentChildModel> newRoles = new List<ParentChildModel>();
foreach (Role r in roles)
{
parent = new ParentChildModel();
parent.id = r.RoleID;
parent.parentid = -1;
parent.text = r.RoleName;
parent.value = r.RoleID.ToString();
foreach (SubRole sr in r.SubRoles)
{
if (sr.Inactive)
{
// hide inactive roles unless parameter says otherwise
if (showInactiveRoles.Equals("true") == false)
continue;
}
child = new ParentChildModel();
child.id = sr.SubRoleID;
child.parentid = r.RoleID;
child.text = sr.SubRoleCategoryItem + (sr.Inactive ? " (Inactive)" : "");
child.value = sr.SubRoleID.ToString();
newRoles.Add(child);
}
newRoles.Add(parent);
};
return Json(newRoles, JsonRequestBehavior.AllowGet);
}
//
/// <summary>
///OBSOLETE FUNCTION BELOW FOR THE KENDO TREEVIEW
/// </summary>
/// <returns></returns>
private IEnumerable<TreeViewItemModel> GetRoles_SubRolesList()
{
List<Role> roles = adminDMO.GetSubRoles();
List<TreeViewItemModel> ToplevelNode = new List<TreeViewItemModel>();
List<TreeViewItemModel> parentList = new List<TreeViewItemModel>();
List<TreeViewItemModel> childList = new List<TreeViewItemModel>();
TreeViewItemModel parent = new TreeViewItemModel();
TreeViewItemModel child = new TreeViewItemModel();
foreach (Role r in roles)
{
parent = new TreeViewItemModel();
parent.HasChildren = true;
parent.Text = r.RoleName;
parent.Id = r.RoleID.ToString();
foreach (SubRole sr in r.SubRoles)
{
child = new TreeViewItemModel();
child.Text = sr.SubRoleCategoryItem;
child.Id = sr.SubRoleID.ToString();
parent.Items.Add(child);
}
ToplevelNode.Add(parent);
};
return ToplevelNode;
}
/// <summary>
///
/// </summary>
/// <param name="subRole"></param>
/// <param name="users"></param>
/// <returns></returns>
public ActionResult AddUserRoles(int subRole, string users)
{
adminDMO.AddUserRoles(subRole, users);
return View();
}
/// <summary>
///
/// </summary>
/// <param name="subRole"></param>
/// <param name="users"></param>
/// <returns></returns>
public ActionResult DeleteUserRoles(int subRole, string users)
{
adminDMO.DeleteUserRoles(subRole, users);
return View();
}
//
// GET: /Workflow/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Workflow/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Workflow/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="model"></param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BatchUpdateUser([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<LoginModel> model)
{
//if (model != null && ModelState.IsValid)
//{
// userDMO.UpdateUser(model);
//}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateUser([DataSourceRequest] DataSourceRequest request, LoginModel model)
{
if (model != null && ModelState.IsValid)
{
userDMO.UpdateUser(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="model"></param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteUser([DataSourceRequest] DataSourceRequest request, LoginModel model)
{
if (model != null && ModelState.IsValid)
{
userDMO.DeleteUser(model);
trainingDMO.DeleteAssignmentByUserId(model.UserID);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="model"></param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model)
{
try
{
if (model != null && ModelState.IsValid)
{
userDMO.InsertUser(model);
}
}
catch (Exception ex)
{
// TODO
throw new Exception(ex.Message);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate)
{
int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate);
if (returnValue == 3) // the delegator is already a delegator to someone else
{
return Content("3");
}
else
return Content("");
// TODO - Send an email to the OOO person and to the Delegated person
//return View();
}
/// <summary>
///
/// </summary>
/// <param name="oooUserID"></param>
public void ExpireOOOStatus(int oooUserID)
{
MiscDMO.ExpireOOOStatus(oooUserID);
// TODO - Does it need to send an email
}
public ActionResult ManageTrainingGroups()
{
//List<TrainingGroup> allGroups = GetTrainingGroups();
//return View(allGroups);
if ((bool)Session[GlobalVars.IS_ADMIN])
{
ViewBag.AllGroups = GetTrainingGroups();
return View();
}
else
return Content("Not Autthorized");
}
public void RefreshGroups()
{
ViewBag.AllGroups = GetTrainingGroups();
}
public ActionResult TrainingGroups()
{
List<TrainingGroup> trainingGroups = adminDMO.GetTrainingGroups();
return PartialView(trainingGroups);
}
public List<TrainingGroup> GetTrainingGroups()
{
List<TrainingGroup> TrainingGroups = adminDMO.GetTrainingGroups();
//List<TreeViewItemModel> ToplevelNode = new List<TreeViewItemModel>();
//List<TreeViewItemModel> parentList = new List<TreeViewItemModel>();
//List<TreeViewItemModel> childList = new List<TreeViewItemModel>();
//TreeViewItemModel parent = new TreeViewItemModel();
//TreeViewItemModel child = new TreeViewItemModel();
//parent = new TreeViewItemModel();
//parent.HasChildren = true;
//parent.Text = "Training Groups";
//foreach (TrainingGroup group in TrainingGroups)
//{
// child = new TreeViewItemModel();
// child.Text = group.TrainingGroupName;
// child.Id = group.TrainingGroupID.ToString();
// parent.Items.Add(child);
//}
//ToplevelNode.Add(parent);
////foreach (Role r in roles)
////{
//// parent = new TreeViewItemModel();
//// parent.HasChildren = true;
//// parent.Text = r.RoleName;
//// parent.Id = r.RoleID.ToString();
//// foreach (SubRole sr in r.SubRoles)
//// {
//// child = new TreeViewItemModel();
//// child.Text = sr.SubRoleCategoryItem;
//// child.Id = sr.SubRoleID.ToString();
//// parent.Items.Add(child);
//// }
//// ToplevelNode.Add(parent);
////};
return TrainingGroups;
}
public ActionResult AddNewTrainingGroup(string groupName)
{
try
{
adminDMO.AddNewTrainingGroup(groupName);
return Json(new {test = "Succesfully saved" });
}
catch
{
return Content("Unable to Save Group", "application/json");
}
}
public ActionResult DeleteTrainingGroup(int groupID)
{
try
{
adminDMO.DeleteTrainingGroup(groupID);
return Json(new { response = "Successfully Deleted" });
}
catch
{
return Json(new { response = "Unsuccessfully Deleted" });
}
}
public ActionResult ViewTrainingGroup(int TrainingGroupID)
{
ViewBag.GroupID = TrainingGroupID;
return View();
}
public ActionResult TrainingGroupPartial(int TrainingGroupID)
{
ViewBag.AllUsers = userDMO.GetAllUsers();
ViewBag.TrainingGroupId = TrainingGroupID;
List<TrainingGroupMember> trainingGroupMembers = adminDMO.GetTrainingGroupMembers(TrainingGroupID);
return PartialView(trainingGroupMembers);
}
public ActionResult AddToGroup(int userId, int groupId)
{
adminDMO.AddUserToGroup(userId, groupId);
return Json(new { test = "Succesfully saved" });
}
public ActionResult DeleteFromGroup(int userId, int groupId)
{
adminDMO.DeleteFromGroup(userId, groupId);
return Json(new { test = "Succesfully removed" });
}
public ActionResult JobSchedulerConfiguration()
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
return View();
}
else
return Content("Not Autthorized");
}
public ActionResult TrainingReportConfig()
{
ViewBag.AllUsers = userDMO.GetAllUsers();
List<TrainingReportUser> currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers();
List<LoginModel> currentTrainingReportUsers = new List<LoginModel>();
foreach (TrainingReportUser id in currentTrainingReportUsersIds)
{
currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId));
}
ViewBag.CurrentReportUsers = currentTrainingReportUsers;
return PartialView();
}
public ActionResult TECNNotificationConfig()
{
ViewBag.AllUsers = userDMO.GetAllUsers();
List<TECNNotificationsUser> currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers();
List<LoginModel> currentTECNNotificationUsers = new List<LoginModel>();
foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds)
{
currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId));
}
ViewBag.CurrentReportUsers = currentTECNNotificationUsers;
return PartialView();
}
public ActionResult AddToTrainingReport(int userId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
//Check to make sure user is not apart of the group already
bool userExists = false;
//bool userValid = true;
List<TrainingReportUser> existingUsers = adminDMO.GetTrainingReportUsers();
foreach (var item in existingUsers)
{
if (item.UserId == userId)
{
userExists = true;
}
}
//Check if user is valid
var validUser = userDMO.GetUserByID(userId);
//Add to group
if (!userExists && validUser != null)
{
adminDMO.TrainingReportAddUser(userId);
return Json("Success Added");
}
else
{
return Content("User either doesn't exist OR is already added");
}
}
else
{
return Content("Not Autthorized");
}
}
public ActionResult AddToTECNNotification(int userId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
//Check to make sure user is not apart of the group already
bool userExists = false;
//bool userValid = true;
List<TECNNotificationsUser> existingUsers = adminDMO.GetTECNNotificationUsers();
foreach (var item in existingUsers)
{
if (item.UserId == userId)
{
userExists = true;
}
}
//Check if user is valid
var validUser = userDMO.GetUserByID(userId);
//Add to group
if (!userExists && validUser != null)
{
try
{
adminDMO.TECNExpirationAddUser(userId);
}
catch (Exception e)
{
string exception = e.Message;
return Content(exception);
}
return Json("Success Added");
}
else
{
return Content("User either doesn't exist OR is already added");
}
}
else
{
return Content("Not Autthorized");
}
}
public ActionResult DeleteFromTrainingReport(int userId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
try
{
adminDMO.TrainingReportDeleteUser(userId);
return Content("Successfully Deleted");
}
catch
{
return Content("Error while trying to delete");
}
}
else
{
return Content("Not Autthorized");
}
}
public ActionResult DeleteFromTECNNotification(int userId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
try
{
adminDMO.TECNExpirationDeleteUser(userId);
return Content("Successfully Deleted");
}
catch
{
return Content("Error while trying to delete");
}
}
else
{
return Content("Not Autthorized");
}
}
}
}

View File

@ -0,0 +1,633 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using System.IO;
using System.Configuration;
using Fab2ApprovalSystem.Utilities;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter]
public class AuditController : Controller
{
AuditDMO auditDMO = new AuditDMO();
UserUtilities adUsers = new UserUtilities();
// GET: Audit
public ActionResult Index()
{
return View();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult Create()
{
Audit audit = new Audit();
try
{
// TODO: Add insert logic here
audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
auditDMO.InsertAudit(audit);
return RedirectToAction("Edit", new { issueID = audit.AuditNo });
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
/// <returns></returns>
public ActionResult Edit(int issueID)
{
int isITARCompliant = 1;
Audit audit = new Audit();
try
{
List<int> userList = auditDMO.Get8DQA();
ViewBag.MesaUsers = adUsers.GetMesaUsers();
int QAs = userList.Find(delegate(int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; });
ViewBag.Is8DQA = "false";
if (QAs != 0)
{
ViewBag.Is8DQA = "true";
}
audit = auditDMO.GetAuditItem(issueID, (int)Session[GlobalVars.SESSION_USERID]);
//transform audit users from string to list, delimited by a comma.
if(audit.Auditees == null || !audit.Auditees.Contains(","))
{
ViewBag.AuditeeNames = audit.Auditees;
}
else
{
string[] auditeeNames = audit.Auditees.Split(',');
ViewBag.AuditeeNames = auditeeNames.ToList();
}
ViewBag.IsSubmitter = false;
if(audit.OriginatorID == (int)Session[GlobalVars.SESSION_USERID])
{
ViewBag.IsSubmitter = true;
}
if((bool)Session[GlobalVars.IS_ADMIN] != true)
{
ViewBag.IsAdmin = false;
}
else
{
ViewBag.IsAdmin = true;
}
if ((audit.RecordLockIndicator && audit.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])
|| audit.AuditStatus != 0 ) //open
{
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
}
if (ViewBag.IsAdmin == false && ViewBag.IsSubmitter == false)
{
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
}
else
{
ViewBag.UserList = auditDMO.GetUserList();
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
//ViewBag.AuditStandardList = auditDMO.GetAuditStandardList();
ViewBag.AuditorList = auditDMO.GetAuditorList();
ViewBag.AuditAreaList = auditDMO.GetAuditAreaList();
ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories();
ViewBag.CANoList = auditDMO.GetCorrectiveActionNoList();
}
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
throw new Exception(e.Message);
}
return View(audit);
}
/// <summary>
///
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Edit(Audit model)
{
try
{
var data = model;
auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]);
}
catch (Exception ex)
{
return Content(ex.Message);
}
return Content("Successfully Saved");
}
/// <summary>
///
/// </summary>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult CheckCAStatus(int auditNo)
{
int dataCount = -1;
try
{
dataCount = auditDMO.GetOpenCACountByAuditNo(auditNo);
}
catch (Exception ex)
{
throw;
}
return Content(dataCount.ToString());
}
/// <summary>
///
/// </summary>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult ReadOnlyAudit(int auditNo)
{
Audit audit = new Audit();
audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]);
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
ViewBag.AuditorList = auditDMO.GetAuditorList();
ViewBag.AuditAreaList = auditDMO.GetAuditAreaList();
ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories();
return View(audit);
}
/// <summary>
///
/// </summary>
/// <param name="AuditReportFiles"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult AuditReportAttachSave(IEnumerable<HttpPostedFileBase> AuditReportFiles, int auditNo)
{
try
{
// The Name of the Upload component is "files"
if (AuditReportFiles != null)
{
foreach (var file in AuditReportFiles)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
//var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);
DirectoryInfo di;
var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo;
di = new DirectoryInfo(ccPhysicalPath);
if (!di.Exists)
di.Create();
var guid = Guid.NewGuid().ToString();
var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension);
file.SaveAs(physicalPath);
AuditReportAttachment attach = new AuditReportAttachment()
{
AuditNo = auditNo,
FileGUID = guid,
FileName = fileName,
UploadedByID = (int)Session[GlobalVars.SESSION_USERID]
};
//ccDMO.InsertCCAttachment(attach);
auditDMO.InsertAuditReportAttachment(attach);
}
}
}
catch
{
throw;
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult AuditReportAttachment_Read([DataSourceRequest] DataSourceRequest request, int auditNo)
{
return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="attachID"></param>
[HttpPost]
public void DeleteAuditReportAttachment(int attachID)
{
auditDMO.DeleteAuditReportAttachment(attachID);
}
/// <summary>
///
/// </summary>
/// <param name="fileGuid"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public FileResult DownloadAuditReportAttachment(string fileGuid, int auditNo)
{
try
{
string fileName = auditDMO.GetAuditReportAttachmentFileName(fileGuid);
string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));
string ecnFolderPath = Functions.GetAttachmentFolder() + "Audit\\" + auditNo.ToString();
var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension);
var FDir_AppData = Functions.GetAttachmentFolder();
if (!sDocument.StartsWith(FDir_AppData))
{
// Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(sDocument))
{
return null;
//throw new Exception("File not found");
}
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
catch
{
// TODO - proces the error
throw;
}
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo)
{
return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public ActionResult InsertAuditFindingsItem(AuditFindings data)
{
Audit audit = new Audit();
auditDMO.InsertAuditFindingsItem(data);
audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
return Json(audit, JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public ActionResult UpdateAuditFindingsItem(AuditFindings data)
{
Audit audit = new Audit();
auditDMO.UpdateAuditFindingsItem(data);
audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
return Json(audit, JsonRequestBehavior.AllowGet);
}
public ActionResult DeleteAuditFindingsItem(int auditFindingsID)
{
var af = auditDMO.GetAuditFindingsByID(auditFindingsID);
auditDMO.DeleteAuditFindingsItem(auditFindingsID);
var audit = auditDMO.GetAuditItem(af.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
return Json(audit, JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
public void ReleaseLockOnDocument(int issueID)
{
try
{
auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID);
}
catch (Exception e)
{
try
{
Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
}
catch { }
auditDMO.ReleaseLockOnDocument(-1, issueID);
}
}
// CA Findings ======================================================================================================================
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult InsertCAFindingsItem(CAFindings data)
{
auditDMO.InsertCAFindings(data);
if (data.ResponsibilityOwnerID != null)
{
// send an email notification
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult UpdateCAFindingsItem(CAFindings data)
{
auditDMO.UpdateCAFindings(data);
if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID)
{
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="caNo"></param>
/// <returns></returns>
public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo)
{
return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="d7PAID"></param>
/// <returns></returns>
public ActionResult GetCAFindingsItemAttachments([DataSourceRequest] DataSourceRequest request, int caFindingsID)
{
return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="d7paID"></param>
/// <returns></returns>
public ActionResult GetCAFindingsItem(int caFindingsID)
{
var model = new CAFindings();
model = auditDMO.GetCAFindingsItem(caFindingsID);
return PartialView("_CAFindingsAttachment", model);
}
/// <summary>
///
/// </summary>
/// <param name="caFindingsID"></param>
[HttpPost]
public void DeleteCAFindingsItem(int caFindingsID)
{
auditDMO.DeleteCAFindingsItem(caFindingsID);
}
/// <summary>
///
/// </summary>
/// <param name="D7PA_Attachemnt"></param>
/// <param name="d7PAID"></param>
/// <param name="caNo"></param>
/// <returns></returns>
public ActionResult SaveCAFindings_Attachemnt(IEnumerable<HttpPostedFileBase> CAFindings_Attachemnt, int caFindingsID, int auditNo)
{
try
{
// The Name of the Upload component is "files"
if (CAFindings_Attachemnt != null)
{
foreach (var file in CAFindings_Attachemnt)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
//var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);
DirectoryInfo di;
var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo;
di = new DirectoryInfo(ccPhysicalPath);
if (!di.Exists)
di.Create();
var guid = Guid.NewGuid().ToString();
var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension);
file.SaveAs(physicalPath);
AuditReportAttachment attach = new AuditReportAttachment()
{
CAFindingsID = caFindingsID,
AuditNo = auditNo,
FileGUID = guid,
FileName = fileName,
UploadedByID = (int)Session[GlobalVars.SESSION_USERID]
};
auditDMO.InsertAuditReportAttachment(attach);
}
}
}
catch
{
throw;
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
/// <param name="currentStep"></param>
public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID)
{
try
{
string emailSentList = "";
//List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
string email = MiscDMO.GetEmail(responsibleOwnerID);
string emailTemplate = "CorrectiveActionFindingAssigned.txt";
string userEmail = string.Empty;
string subject = "5s/CA Findings";
string senderName = "CorrectiveAction";
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[5];
emailparams[0] = Functions.ReturnAuditNoStringFormat(issueID);
emailparams[1] = dueDate.ToString();
emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.Audit);
emailparams[3] = GlobalVars.hostURL;
emailparams[4] = issueID.ToString();
userEmail = email;
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
emailSentList += email + ",";
try
{
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email });
}
catch { }
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString });
//throw e;
}
}
public ActionResult IsCAAssignedToAudit(int caNo, int auditNo)
{
return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString());
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,673 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Utilities;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class HomeController : Controller
{
LotDispositionDMO ldDMO = new LotDispositionDMO();
MRB_DMO mrbDMO = new MRB_DMO();
WorkflowDMO wfDMO = new WorkflowDMO();
ECN_DMO ecnDMO = new ECN_DMO();
PartsRequestDMO prDMO = new PartsRequestDMO();
UserUtilities userDMO = new UserUtilities();
UserAccountDMO originalUserDMO = new UserAccountDMO();
TrainingDMO trainingDMO = new TrainingDMO();
/// <summary>
///
/// </summary>
/// <param name="tabName"></param>
/// <returns></returns>
public ActionResult Index(string tabName)
{
ViewBag.ActiveTabName = tabName;
return View();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult MyTasks()
{
return View();
}
public ActionResult AllDocuments()
{
return View();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult SpecialWorkRequestList()
{
return View();
}
public ActionResult MRBList()
{
return View();
}
public ActionResult ECNList()
{
return View();
}
public ActionResult TrainingList()
{
return View();
}
public ActionResult LotDispositionList()
{
return View();
}
public ActionResult AuditList()
{
return View();
}
public ActionResult CorrectiveActionList()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="viewOption"></param>
/// <returns></returns>
public ActionResult ECN_TECN(string viewOption)
{
ViewBag.ViewOption = viewOption;
return View();
}
public ActionResult ChangeControlList()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetTaskList([DataSourceRequest]DataSourceRequest request, string tabName)
{
try
{
ViewBag.ActiveTabName = tabName;
IEnumerable<IssuesViewModel> data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]);
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// TODO record the error
throw ex;
}
}
public ActionResult GetMyOpenActionItems([DataSourceRequest]DataSourceRequest request, string tabName)
{
try
{
ViewBag.ActiveTabName = tabName;
IEnumerable<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]);
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// TODO record the error
throw ex;
}
}
public ActionResult GetDocuments([DataSourceRequest]DataSourceRequest request, string tabName)
{
ViewBag.ActiveTabName = tabName;
//IEnumerable<IssuesViewModel> data = ldDMO.GetLotDispositions();
IEnumerable<IssuesViewModel> data = ldDMO.GetDocuments();
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetWorkRequests([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ldDMO.GetWorkRequests();
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetChangeControlList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<ChangeControlList> data = ldDMO.GetChangeControls(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetAuditList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<AuditList> data = ldDMO.GetAuditList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetCorrectiveActionList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<CorrectiveAction> data = ldDMO.GetCorrectiveActionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetMRBList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ldDMO.GetMRBList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetLotDispositionList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ldDMO.GetLotDispositionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetECNList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ldDMO.GetECNList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
return Json(data.ToDataSourceResult(request));
}
public ActionResult GetTrainingList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<Training> data = trainingDMO.GetAllTrainings();
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="dataType"></param>
/// <returns></returns>
public ActionResult MyECNsTECNs(string dataType)
{
ViewBag.ActiveTabName = dataType;
return View();
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ecnDMO.GetECN_TECNPendingApprovals(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
ViewBag.ViewOption = "Pending Approvals";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption;
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetMyExpiredTECNs([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiredTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7);
ViewBag.ViewOption = "Expired TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption;
return Json(data.ToDataSourceResult(request));
}
public ActionResult GetAllTECNs([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ecnDMO.GetAllTECNs();
ViewBag.ViewOption = "All TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption;
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyConvertedTECNsToECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7);
ViewBag.ViewOption = "Converted TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption;
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public ActionResult GetMyExpiringTECNs([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiringTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7);
ViewBag.ViewOption = "Expiring TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption;
return Json(data.ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="workRequestID"></param>
/// <returns></returns>
public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request, int workRequestID)
{
LotTravelerDMO LotTravDMO = new LotTravelerDMO();
return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab)
{
if (Session[GlobalVars.SESSION_USERID] != null)
{
int returnValue = MiscDMO.EnableOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), delegatedTo, startDate, endDate);
if (returnValue == 3) // the delegator is already a delegator to someone else
{
return Content("3");
}
if (startDate <= DateTime.Today)
Session[GlobalVars.OOO] = true;
NotifyDelegation(delegatedTo, startDate, endDate);
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="oooUserID"></param>
public void ExpireOOOStatus(string tab)
{
if (Session[GlobalVars.SESSION_USERID] != null)
{
MiscDMO.ExpireOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()));
Session[GlobalVars.OOO] = false;
}
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="issue"></param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue)
{
GlobalVars.DocumentType dType;
Enum.TryParse(issue.DocumentType, out dType);
if (dType == GlobalVars.DocumentType.MRB)
mrbDMO.DeleteMRB(issue.IssueID);
else if (dType == GlobalVars.DocumentType.LotDisposition)
ldDMO.DeleteLotDisposition(issue.IssueID);
else if (dType == GlobalVars.DocumentType.ECN)
ecnDMO.DeleteDocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "ECN");
return Json(new[] { issue }.ToDataSourceResult(request, ModelState));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
#region testing purpose
public ActionResult Edit()
{
return View(DemoHelper.Instance.ListOfModels[0]);
}
[HttpPost]
public ActionResult Edit(TestModel editTest)
{
DemoHelper.Instance.ListOfModels[0] = editTest;
return RedirectToAction("Index");
}
public static void Test()
{
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
foreach (string colorString in colorStrings)
{
GlobalVars.Colors colorValue;
if (Enum.TryParse(colorString, true, out colorValue))
if (Enum.IsDefined(typeof(GlobalVars.Colors), colorValue) | colorValue.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
else
Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
else
Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
}
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
/// <param name="delegateTo"></param>
/// <param name="step"></param>
/// <param name="docType"></param>
/// <param name="ecnTypeString"></param>
public void DelegateDocumentApproval(int issueID, int delegateTo, string ecnTypeString, string title)
{
var email = "";
int delegateFrom = (int)Session[GlobalVars.SESSION_USERID];
try
{
email = wfDMO.DelegateDocumentApproval(issueID, delegateFrom, delegateTo);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString , OperationType = "Delegation", Comments = "Delegated from - " + delegateFrom + " to " + delegateTo });
}
catch (Exception e)
{
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n DelegateApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString });
throw new Exception(e.Message);
}
string emailTemplate = "DelegateApproval.txt";
string userEmail = string.Empty;
string subject;
string senderName = ecnTypeString;
subject = ecnTypeString + " Delegation" + " - Email would be sent to " + email + " for Number " + issueID + ", - " + title; ;
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[4];
emailparams[0] = issueID.ToString();
emailparams[1] = issueID.ToString();
emailparams[2] = GlobalVars.hostURL;
emailparams[3] = ecnTypeString;
userEmail = email;
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
try
{
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Delegated to Approver: " + email });
}
catch { }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public JsonResult GetAllUsersList()
{
UserAccountDMO userDMO = new UserAccountDMO();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult SaveAllDocumentsFilter(string data)
{
Session["AllDocumentsFilterData"] = data;
return new EmptyResult();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult LoadAllDocumentsFilter()
{
return Json(Session["AllDocumentsFilterData"], JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult SaveSWRFilter(string data)
{
Session["SWRFilterData"] = data;
return new EmptyResult();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult LoadSWRFilter()
{
return Json(Session["SWRFilterData"], JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult SavePCRBFilter(string data)
{
Session["PCRBFilterData"] = data;
return new EmptyResult();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult LoadPCRBFilter()
{
return Json(Session["PCRBFilterData"], JsonRequestBehavior.AllowGet);
}
public ActionResult PartsRequestList()
{
ViewBag.CanDeletePR = Session[GlobalVars.CAN_CREATE_PARTS_REQUEST];
return View();
}
public ActionResult GetPartsRequestList([DataSourceRequest]DataSourceRequest request)
{
IEnumerable<PartsRequestList> data = prDMO.GetPartsRequestList();
return Json(data.ToDataSourceResult(request));
}
public ActionResult GetMyPartsRequestsList([DataSourceRequest]DataSourceRequest request, string tabName)
{
try
{
ViewBag.ActiveTabName = tabName;
var data = prDMO.GetMyPartsRequests((int)Session[GlobalVars.SESSION_USERID]);
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// TODO record the error
throw ex;
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr)
{
try
{
if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false)
throw new Exception("Permission denied");
prDMO.DeleteDocument(pr.PRNumber, (int)Session[GlobalVars.SESSION_USERID]);
return Json(new[] { pr }.ToDataSourceResult(request, ModelState));
}
catch (Exception ex)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message);
}
}
public void NotifyDelegation(int delegatedUser, DateTime startDate, DateTime endDate)
{
LoginModel delegateFrom = originalUserDMO.GetUserByID((int)Session[GlobalVars.SESSION_USERID]);
LoginModel delegateTo = originalUserDMO.GetUserByID(delegatedUser);
List<string> emailList = new List<string>();
emailList.Add(delegateFrom.Email);
emailList.Add(delegateTo.Email);
string emailTemplate = "DelegationOn.txt";
string userEmail = string.Empty;
string subject = "Mesa Approval Delegation Notification";
string senderName = "Mesa Approval";
foreach (string email in emailList)
{
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[5];
emailparams[0] = delegateFrom.FullName;
emailparams[1] = delegateTo.FullName;
emailparams[2] = startDate.ToString("yyyy-MM-dd");
emailparams[3] = endDate.ToString("yyyy-MM-dd");
userEmail = email;
//#if(DEBUG)
// userEmail = GlobalVars.SENDER_EMAIL;
//#endif
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
}
try
{
//EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail });
}
catch { }
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,753 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter]
public class PartsRequestController : Controller
{
PartsRequestDMO prDMO = new PartsRequestDMO();
UserAccountDMO userDMO = new UserAccountDMO();
WorkflowDMO wfDMO = new WorkflowDMO();
const int WorkflowNumber = 1;
public PartsRequestController()
{
ViewBag.ShowReAssignApprovers = false;
}
protected ActionResult HandleValidationError(string msg)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Json(new { result = "Invalid", detail = msg });
}
protected ActionResult HandleAPIException(int issueID, Exception ex, string additionalKeys = "")
{
HandleException(issueID, ex, additionalKeys);
Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
return Json(new { result = "Error", issueID = issueID, detail = ex.Message });
}
protected void HandleException(int issueID, Exception ex, string additionalKeys = "")
{
var st = new System.Diagnostics.StackTrace();
var sf = st.GetFrame(1);
String controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", "");
String method = sf.GetMethod().Name;
string detailedException = String.Format(
"Exception for issue # {0}\r\n" +
"Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" +
"=====\r\n",
issueID,
controller,
method,
User?.Identity?.Name,
additionalKeys);
Exception x = ex;
while (x != null)
{
detailedException += x.ToString();
detailedException += "\r\n=====\r\n";
x = x.InnerException;
}
Functions.WriteEvent(detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog()
{
IssueID = issueID,
UserID = @User.Identity.Name,
DocumentType = controller,
OperationType = "Error",
Comments = detailedException
});
}
// GET: PartsRequest
public ActionResult Index()
{
return View();
}
public ActionResult Edit(int issueID)
{
var pr = new PartsRequest();
try
{
pr = prDMO.Get(issueID);
if (pr == null)
{
ViewBag.ErrorDescription = "Document does not exist";
return View("Error");
}
else if (pr.CurrentStep < 0)
{
ViewBag.ErrorDescription = "Document is deleted";
return View("Error");
}
else if (pr.CurrentStep >= 1)
{
return RedirectToAction("EditApproval", new { issueID = issueID });
}
else
{
if (pr.OriginatorID != (int)Session[GlobalVars.SESSION_USERID])
{
if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false)
{
return RedirectToAction("ReadOnly", new { issueID = issueID });
}
}
ViewBag.UserList = userDMO.GetAllUsers();
return View(pr);
}
}
catch (Exception e)
{
HandleException(issueID, e);
return View("Error");
}
}
[HttpPost]
public ActionResult Edit(PartsRequest pr)
{
try
{
var pr_srv = prDMO.Get(pr.PRNumber);
if (pr_srv == null)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist");
}
if (pr_srv.CurrentStep < 0)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document is deleted");
}
if (pr_srv.CurrentStep >= 1)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Parts Request is not editable");
}
prDMO.Update(pr);
return Content("");
}
catch (Exception e)
{
return HandleAPIException(pr.PRNumber, e);
}
}
public ActionResult EditApproval(int issueID)
{
var pr = new PartsRequest();
try
{
int myUserID = (int)Session[GlobalVars.SESSION_USERID];
pr = prDMO.Get(issueID);
if (pr == null)
{
ViewBag.ErrorDescription = "Document does not exist";
return View("Error");
}
if (pr.CurrentStep < 0)
{
ViewBag.ErrorDescription = "Document is deleted";
return View("Error");
}
var wfStep = wfDMO.GetWorkflowStep((int)GlobalVars.DocumentType.PartsRequest, WorkflowNumber, pr.CurrentStep);
var userList = MiscDMO.GetPendingApproversListByDocument(issueID, Convert.ToByte(pr.CurrentStep), (int)GlobalVars.DocumentType.PartsRequest);
ViewBag.IsApprover = (userList.Count(u => u.UserID == myUserID) > 0);
if (ViewBag.IsApprover == false)
{
if (pr.OriginatorID != myUserID)
{
if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false)
{
return RedirectToAction("ReadOnly", new { issueID = issueID });
}
}
}
ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]);
ViewBag.IsOriginator = (pr.OriginatorID == myUserID);
ViewBag.AllowReject = (wfStep != null ? (wfStep.AllowReject.HasValue && wfStep.AllowReject.Value) : false);
ViewBag.ShowReAssignApprovers = ViewBag.IsAdmin || ViewBag.IsOriginator;
ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator;
ViewBag.UserList = userDMO.GetAllUsers();
return View(pr);
}
catch (Exception e)
{
HandleException(issueID, e);
return View("Error");
}
}
public ActionResult ReadOnly(int issueID)
{
var pr = new PartsRequest();
try
{
int myUserID = (int)Session[GlobalVars.SESSION_USERID];
pr = prDMO.Get(issueID);
if (pr == null)
{
ViewBag.ErrorDescription = "Document does not exist";
return View("Error");
}
if (pr.CurrentStep < 0)
{
ViewBag.ErrorDescription = "Document is deleted";
return View("Error");
}
ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]);
ViewBag.IsOriginator = (pr.OriginatorID == myUserID);
ViewBag.UserList = userDMO.GetAllUsers();
return View(pr);
}
catch (Exception e)
{
HandleException(issueID, e);
return View("Error");
}
}
public ActionResult Create()
{
var pr = new PartsRequest();
try
{
pr.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
if (!CanCreatePartsRequest(pr.OriginatorID) && Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false)
throw new Exception("User does not have permission to create Parts Request");
prDMO.Insert(pr);
return RedirectToAction("Edit", new { issueID = pr.PRNumber });
}
catch (Exception e)
{
return HandleAPIException(pr.PRNumber, e);
}
}
public static bool CanCreatePartsRequest(int userID)
{
var adminDMO = new AdminDMO();
var role = adminDMO.GetSubRoles().Where(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (role != null)
{
var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase));
if (subrole != null)
{
var users = adminDMO.GetAllUsersBySubRole(subrole.SubRoleID);
if (users.Count(u => u.UserID == userID) > 0)
{
return true;
}
}
}
return false;
}
public ActionResult Attachment_Read([DataSourceRequest]DataSourceRequest request, int prNumber)
{
try
{
return Json(prDMO.GetAttachments(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return HandleAPIException(prNumber, ex);
}
}
[HttpPost]
public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int prNumber)
{
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = System.IO.Path.GetFileName(file.FileName);
string prFolderPath = Functions.GetAttachmentFolder() + "PartsRequest\\" + prNumber.ToString();
var di = new System.IO.DirectoryInfo(prFolderPath);
if (!di.Exists)
di.Create();
var physicalPath = System.IO.Path.Combine(prFolderPath, fileName);
file.SaveAs(physicalPath);
var attach = new PartsRequestAttachment()
{
PRNumber = prNumber,
FileName = fileName,
UserID = (int)Session[GlobalVars.SESSION_USERID],
};
prDMO.InsertAttachment(attach);
}
}
return Content("");
}
public FileResult DownloadFile(string attachmentID, string prNumber)
{
string fileName = prDMO.GetFileName(attachmentID);
string folderPath = Functions.GetAttachmentFolder() + "PartsRequest\\" + prNumber.ToString();
var sDocument = System.IO.Path.Combine(folderPath, fileName);
var FDir_AppData = Functions.GetAttachmentFolder();
if (!sDocument.StartsWith(FDir_AppData))
{
// Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(sDocument))
return null;
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
[HttpPost]
public ActionResult DeleteAttachment(int attachmentID, string fileName, int prNumber)
{
try
{
if (ModelState.IsValid)
{
prDMO.DeleteAttachment(attachmentID);
var physicalPath = System.IO.Path.Combine(Functions.GetAttachmentFolder() + @"PartsRequest\" + prNumber.ToString(), fileName);
if (System.IO.File.Exists(physicalPath))
{
System.IO.File.Delete(physicalPath);
}
}
return Content("");
}
catch (Exception e)
{
return HandleAPIException(prNumber, e, "AttachmentID=" + attachmentID.ToString());
}
}
[HttpPost]
public ActionResult Submit(int prNumber)
{
try
{
int myUserID = (int)Session[GlobalVars.SESSION_USERID];
var pr = prDMO.Get(prNumber);
if (pr == null)
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist");
if (String.IsNullOrWhiteSpace(pr.Title))
return HandleValidationError("Title is required");
if (pr.RequestorID <= 0)
return HandleValidationError("Requestor is required");
if (pr.TechLeadID <= 0)
return HandleValidationError("Tech Lead is required");
prDMO.Submit(prNumber, myUserID);
var approvers = MiscDMO.GetApprovalsByDocument(prNumber, (int)GlobalVars.DocumentType.PartsRequest);
if (approvers.Count(a => a.Step.HasValue && a.Step.Value == 1 && a.UserID == myUserID) > 0)
{
// Auto-Approve if the user is an approver for workflow step 1
var c = Approve(prNumber, 1, "Auto-Approve");
if (c != null && c is ContentResult)
{
var result = ((ContentResult)c).Content;
if (!String.Equals(result, "OK"))
throw new Exception(result);
}
if (c != null && c is JsonResult)
return c;
}
else
{
// Do step 1 notification
NotifyApprovers(prNumber, 1);
}
if (Request.IsAjaxRequest())
{
return Content("Redirect");
}
else
{
return Content("Invalid");
}
}
catch (Exception e)
{
return HandleAPIException(prNumber, e);
}
}
public ActionResult GetApproversList([DataSourceRequest]DataSourceRequest request, int issueID, byte step)
{
try
{
return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.PartsRequest).ToDataSourceResult(request));
}
catch (Exception e)
{
return HandleAPIException(issueID, e, "Step=" + step.ToString());
}
}
public ActionResult GetAllUsersList()
{
try
{
UserAccountDMO userDMO = new UserAccountDMO();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return HandleAPIException(0, e);
}
}
[HttpPost]
public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step)
{
try
{
String email = wfDMO.ReAssignApproval(
issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest);
NotifyReAssignment(issueID, email);
return Content("OK");
}
catch (Exception e)
{
return HandleAPIException(issueID, e);
}
}
[HttpPost]
public ActionResult Approve(int prNumber, byte currentStep, string comments)
{
try
{
bool lastStep = false;
bool lastApproverInCurrentStep = false;
int myUserID = (int)Session[GlobalVars.SESSION_USERID];
var pr = prDMO.Get(prNumber);
if (pr == null)
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist");
while (true)
{
lastApproverInCurrentStep = wfDMO.Approve(
prNumber, currentStep, comments, out lastStep,
(int)Session[GlobalVars.SESSION_USERID],
(int)GlobalVars.DocumentType.PartsRequest,
WorkflowNumber);
if (!lastApproverInCurrentStep) break;
if (lastStep)
{
NotifyCompletion(prNumber);
break;
}
currentStep++;
var approvers = MiscDMO.GetApprovalsByDocument(prNumber, (int)GlobalVars.DocumentType.PartsRequest);
if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep) == 0)
return Content("No approvers found for next step, contact support!");
// only continue with approving if the next step has me as an approver also
if (approvers.Count(a => a.Step.HasValue && a.Step.Value == currentStep && a.UserID == myUserID) == 0)
{
NotifyApprovers(prNumber, currentStep);
break;
}
}
return Content("OK");
}
catch (Exception e)
{
return HandleAPIException(prNumber, e);
}
}
protected void SendEmailNotification(String subject, int prNumber, string toEmail, string emailTemplate)
{
string senderName = "Parts Request";
EmailNotification en = new EmailNotification(subject, System.Configuration.ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[5];
emailparams[0] = prNumber.ToString();
emailparams[1] = prNumber.ToString();
emailparams[2] = GlobalVars.hostURL;
emailparams[3] = "Parts Request";
emailparams[4] = Session[GlobalVars.SESSION_USERNAME].ToString();
String userEmail = toEmail;
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
}
protected void NotifyReAssignment(int prNumber, string email)
{
var pr = prDMO.Get(prNumber);
if (pr == null)
return;
SendEmailNotification(
subject: String.Format("Parts Request Re-Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title),
prNumber: prNumber,
toEmail: email,
emailTemplate: "PRReAssigned.txt");
EventLogDMO.Add(new WinEventLog()
{
IssueID = prNumber,
UserID = @User.Identity.Name,
DocumentType = "PR",
OperationType = "Email",
Comments = "ReAssigned Approver: " + email
});
}
protected void NotifyCompletion(int prNumber)
{
var pr = prDMO.Get(prNumber);
if (pr == null)
return;
var u = userDMO.GetUserByID(pr.RequestorID);
if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email)))
{
SendEmailNotification(
subject: String.Format("Parts Request Completion notice for # {0} - {1}", pr.PRNumber, pr.Title),
prNumber: prNumber,
toEmail: u.Email,
emailTemplate: "PRCompleted.txt");
EventLogDMO.Add(new WinEventLog()
{
IssueID = prNumber,
UserID = @User.Identity.Name,
DocumentType = "PR",
OperationType = "Email",
Comments = "Completed: " + u.Email
});
}
}
public void NotifyRejection(int prNumber)
{
var pr = prDMO.Get(prNumber);
if (pr == null)
return;
var u = userDMO.GetUserByID(pr.OriginatorID);
if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email)))
{
SendEmailNotification(
subject: String.Format("Parts Request Rejection notice for # {0} - {1}", pr.PRNumber, pr.Title),
prNumber: prNumber,
toEmail: u.Email,
emailTemplate: "PRReject.txt");
EventLogDMO.Add(new WinEventLog()
{
IssueID = prNumber,
UserID = @User.Identity.Name,
DocumentType = "PR",
OperationType = "Email",
Comments = "Rejected: " + u.Email
});
}
}
protected void NotifyApprovers(int prNumber, byte step)
{
try
{
string emailSentList = "";
var pr = prDMO.Get(prNumber);
if (pr == null)
throw new Exception("Invalid pr#");
List<string> emailList = MiscDMO.GetApproverEmailListByDocument(
prNumber, step, (int)GlobalVars.DocumentType.PartsRequest).Distinct().ToList();
foreach (string email in emailList)
{
try
{
SendEmailNotification(
subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title),
prNumber: prNumber,
toEmail: email,
emailTemplate: "PRAssigned.txt");
}
catch (Exception ex)
{
HandleException(prNumber, ex, "email=" + email);
}
emailSentList += email + ",";
}
try
{
EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, UserID = @User.Identity.Name, DocumentType = "PR", OperationType = "Email",
Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList });
}
catch { }
}
catch (Exception e)
{
HandleException(prNumber, e, "Step=" + step.ToString());
}
}
[HttpPost]
public ActionResult Reject(int prNumber, byte currentStep, string comments)
{
try
{
if (Session[GlobalVars.SESSION_USERID] != null)
{
wfDMO.Reject(prNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.PartsRequest);
NotifyRejection(prNumber);
}
else
{
Response.Redirect("~/Account/Login");
}
return Content("OK");
}
catch (Exception e)
{
return HandleAPIException(prNumber, e);
}
}
public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int prNumber)
{
return Json(prDMO.GetApprovalLogHistory(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
protected void NotifyAssignment(int prNumber, string email)
{
var pr = prDMO.Get(prNumber);
if (pr == null)
return;
SendEmailNotification(
subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title),
prNumber: prNumber,
toEmail: email,
emailTemplate: "PRAssigned.txt");
EventLogDMO.Add(new WinEventLog()
{
IssueID = prNumber,
UserID = @User.Identity.Name,
DocumentType = "PR",
OperationType = "Email",
Comments = "Assigned Approver: " + email
});
}
[HttpPost]
public void AddAdditionalApproval(int issueID, byte step, string userIDs)
{
var emailArray = "";
try
{
emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest);
}
catch (Exception e)
{
HandleAPIException(issueID, e);
}
string emailSentList = "";
string[] emaiList = emailArray.Split(new char[] { '~' });
foreach (string email in emaiList)
{
if (email.Length > 0)
{
NotifyAssignment(issueID, email);
emailSentList += email + ",";
}
}
try
{
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "PR",
OperationType = "Email", Comments = "Additional Approver: " + emailSentList });
}
catch { }
}
}
}

View File

@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.ViewModels;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
public class ReportsController : Controller
{
public const String specialNullString = "~NULL~";
// GET: Export
public ActionResult Index()
{
UserAccountDMO userDMO = new UserAccountDMO();
ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]);
return View();
}
public ActionResult Report(String id, String docType = "")
{
if (String.IsNullOrEmpty(id))
return RedirectToAction("Index");
UserAccountDMO userDMO = new UserAccountDMO();
if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]))
return View("UnAuthorizedAccess");
var m = new ReportViewModel();
var reports = GetReportList(docType);
foreach (var report in reports)
{
if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase))
{
m.ReportID = report.ReportID;
m.ReportName = report.Name;
m.Description = report.Description;
m.DocType = docType;
var c = SetupSSRSHelperClient();
m.Parameters = c.GetReportParameters(report.FullPath).Select(parm =>
{
var r = new ReportParameterViewModel();
r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt);
r.Prompt = parm.Prompt;
r.Name = parm.Name;
r.HtmlID = "parm_" + parm.Name;
if (parm.MultiValue.HasValue && parm.MultiValue.Value)
r.ControlType = ParameterControlTypes.Multiselect;
else if ((parm.ValidValues != null) && (parm.ValidValues.Length > 0))
r.ControlType = ParameterControlTypes.Dropdown;
else if (parm.DataType.Equals("DateTime", StringComparison.OrdinalIgnoreCase))
r.ControlType = ParameterControlTypes.DatePicker;
else
r.ControlType = ParameterControlTypes.Textbox;
r.SelectList = null;
if (parm.ValidValues != null)
{
r.SelectList = parm.ValidValues.Select(vv => {
return new SelectListItem()
{
Text = vv.Value,
Value = (vv.Key == null ? specialNullString : vv.Key),
Selected = (parm.DefaultValues != null && parm.DefaultValues.Contains(vv.Key))
};
}).ToList();
}
r.DefaultValue = "";
if (parm.DefaultValues != null && parm.DefaultValues.Length > 0)
r.DefaultValue = parm.DefaultValues[0];
return r;
}).ToArray();
}
}
return View(m);
}
public SSRSHelper.SSRSClient SetupSSRSHelperClient()
{
var useCfgForBindings = false;
if (String.Equals(System.Configuration.ConfigurationManager.AppSettings["SSRSBindingsByConfiguration"], "true", StringComparison.OrdinalIgnoreCase))
useCfgForBindings = true;
var c = new SSRSHelper.SSRSClient(
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSBaseURL"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSDomain"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSUsername"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSPassword"]),
useCfgForBindings);
c.Initialize();
return c;
}
private IEnumerable<SSRSHelper.ReportInfo> GetReportList(String docType)
{
String folderName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSFolder"]);
if (folderName.EndsWith("/"))
folderName = folderName.TrimEnd('/');
if (!String.IsNullOrWhiteSpace(docType))
folderName = folderName + "/" + docType;
var c = SetupSSRSHelperClient();
return c.ListReports(folderName);
}
public ActionResult GetReports(String docType)
{
var reports = GetReportList(docType);
return Json(new { Data =
reports.Select(r => new ReportViewModel()
{
ReportName = r.Name ?? "",
Description = r.Description ?? "",
ReportID = r.ReportID ?? "",
DocType = docType
})
},
JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult ExportReport(String DocType, String ReportID)
{
var c = SetupSSRSHelperClient();
var reports = GetReportList(DocType);
var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (report == null)
return Content("Invalid report ID");
var reportParms = c.GetReportParameters(report.FullPath);
var parms = new SSRSHelper.ReportParameterCollection();
parms.Add("DocType", DocType);
parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID]));
parms.Add("BaseURL", GlobalVars.hostURL);
foreach (var rp in reportParms)
{
if (rp.MultiValue.HasValue && rp.MultiValue.Value)
{
foreach (String v in Request.Params.GetValues("parm_" + rp.Name))
{
parms.Add(rp.Name, v);
}
}
else
{
String value = null;
if (Request.Params.AllKeys.Contains("parm_" + rp.Name))
value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault();
if (value == specialNullString)
value = null;
if ((rp.AllowBlank.HasValue == false || rp.AllowBlank.Value == false) && value == "")
value = null;
if (value == null)
{
if (rp.Nullable.HasValue == false || rp.Nullable.Value == false)
{
if (rp.DefaultValues != null && rp.DefaultValues.Length > 0)
value = rp.DefaultValues[0];
if (value == null)
continue;
}
}
parms.Add(rp.Name, value);
}
}
var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML");
try
{
var b2 = c.FreezeExcelHeaders(b);
return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
}
catch
{
}
return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
}
protected String MakeFilename(String reportName)
{
String r = "";
var invalidChars = System.IO.Path.GetInvalidFileNameChars();
foreach (char c in reportName)
{
if (invalidChars.Contains(c))
r += '_';
else
r += c;
}
return r;
}
}
}

View File

@ -0,0 +1,506 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Fab2ApprovalSystem.Misc;
using System.Configuration;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
public class TrainingController : Controller
{
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
ECN_DMO ecnDMO = new ECN_DMO();
// GET: Training
public ActionResult Index()
{
return View();
}
//public int Create(int ecnId, List<int> groupIds)
public int Create(int ecnId)
{
ECN_DMO ecnDMO = new ECN_DMO();
//Delete old training if exists
int oldTrainingId = trainingDMO.GetTrainingId(ecnId);
if (oldTrainingId != null && oldTrainingId != 0)
{
trainingDMO.DeleteTraining(oldTrainingId);
}
int trainingId = trainingDMO.Create(ecnId);
List<int> TrainingGroups = new List<int>();
TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
string ECNTitle = ecnDMO.GetECN(ecnId).Title;
List<int> Trainees = new List<int>();
foreach (var group in TrainingGroups)
{
Trainees.AddRange(trainingDMO.GetTrainees(group));
}
Trainees = (from a in Trainees select a).Distinct().ToList();
foreach (var trainee in Trainees)
{
int assignmentId = trainingDMO.CreateAssignment(trainingId, trainee);
NotifyTrainee(trainee, assignmentId, ecnId, ECNTitle);
}
return trainingId;
}
public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId)
{
//Get ECN
ECN ecn = ecnDMO.GetECN(ecnId);
//Get User
LoginModel user = userDMO.GetUserByID(traineeId);
//Get Training
Training training = trainingDMO.GetTraining(trainingId);
if (ecn != null)
{
if(user != null)
{
if(training != null)
{
if(training.CompletedDate == null && training.DeletedDate == null)
{
//Add user to training
int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId);
NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title);
return Content("Success");
}
else
{
return Content("Selected training has either been deleted or has completed.");
}
}
else
{
return Content("Invalid training id.");
}
}
else
{
return Content("invalid userId");
}
}
else
{
return Content("ECN invalid");
}
}
public ActionResult DeleteTrainingByECN(int ECNNumber)
{
int trainingId = trainingDMO.GetTrainingId(ECNNumber);
if (trainingId != null && trainingId != 0)
{
trainingDMO.DeleteTraining(trainingId);
}
return RedirectToAction("ViewTrainings");
}
public ActionResult DeleteTrainingByID(int trainingId)
{
if (trainingId != null && trainingId != 0)
{
trainingDMO.DeleteTraining(trainingId);
}
return RedirectToAction("ViewTrainings");
}
public void NotifyTrainee(int userId, int assignmentId, int ecnId, string title)
{
try
{
string emailSentList = "";
//ECN ecn = ecnDMO.GetECN(ecnNumber);
//List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
string recipient = userDMO.GetUserEmailByID(userId.ToString());
string emailTemplate = "ECNTrainingAssigned.txt";
string userEmail = string.Empty;
string subject = string.Empty;
string senderName = "ECN Training";
subject = "ECN# " + ecnId + " - Training Assignment Notice - " + title;
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
//string emailparams = "";
userEmail = recipient;
string[] emailparams = new string[4];
emailparams[0] = assignmentId.ToString();
emailparams[1] = ecnId.ToString();
emailparams[2] = GlobalVars.hostURL;
//#if(DEBUG)
//string SenderEmail = "MesaFabApproval@infineon.com";
//userEmail = "jonathan.ouellette@infineon.com";
//#endif
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
//en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams);
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
}
}
public ActionResult ViewTrainingPartial(int trainingID, int userID)
{
List<TrainingAssignment> TrainingData = trainingDMO.GetTrainingAssignmentsByUser(trainingID, userID);
if (trainingID > 0)
{
ViewBag.ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
}
return PartialView(TrainingData);
}
public ActionResult ViewTrainingDocsPartial(int trainingAssignmentId)
{
ViewBag.trainingAssignmentId = trainingAssignmentId;
//IEnumerable<TrainingDocAck> attachments = ecnDMO.GetECNAttachments(ecnNumber);
IEnumerable<TrainingDocAck> attachments = trainingDMO.GetAssignedDocs(trainingAssignmentId);
return PartialView(attachments);
}
public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID)
{
//Check to see if acknowledgement is valid(Security Feature to protect data integrity)
if (trainingDMO.CheckValidDocAck(trainingDocAckID))
{
trainingDMO.AcknowledgeDocument(trainingDocAckID);
bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(trainingAssignmentID);
if (isFinishedTrainingAssignment)
{
try
{
trainingDMO.UpdateAssignmentStatus(trainingAssignmentID);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID);
if (isFinishedTraining)
{
int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
string exception = e.ToString();
return Content(exception);
}
}
}
return Content("Marked Succesfully.");
}
public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID)
{
try
{
trainingDMO.UpdateAssignmentStatus(trainingAssignmentID);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID);
if (isFinishedTraining)
{
int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
string exception = e.ToString();
return Content(exception, "application/json");
}
return Json(new { test = "Succesfully saved" });
}
//public ActionResult ViewTrainings()
//{
// IEnumerable<Training> trainings = trainingDMO.GetTrainings();
// return View(trainings);
//}
public ActionResult TrainingReports()
{
return View();
}
public ActionResult TrainingReportsView(int? filterType, string filterValue)
{
ViewBag.TrainingGroups = adminDMO.GetTrainingGroups();
IEnumerable<Training> trainingList = trainingDMO.GetAllTrainings();
//Group Filter
if (filterType == 1 && filterValue != "")
{
ViewBag.GroupFilter = filterValue;
List<Training> filteredTraining = new List<Training>();
foreach (var item in trainingList)
{
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN);
foreach (int id in assignedTrainingGroups)
{
if (filterValue == id.ToString())
{
filteredTraining.Add(item);
}
}
}
trainingList = filteredTraining;
return PartialView(trainingList);
}
//Status Filter
if (filterType == 2 && filterValue != "")
{
List<Training> filteredTraining = new List<Training>();
switch (filterValue)
{
case "1":
//Completed
filteredTraining = (from a in trainingList where a.Status == true && a.Deleted != true select a).ToList();
break;
case "2":
//In Progress
filteredTraining = (from a in trainingList where a.Status != true && a.Deleted != true select a).ToList();
break;
case "3":
//Cancelled
filteredTraining = (from a in trainingList where a.Deleted == true select a).ToList();
break;
}
trainingList = filteredTraining;
return PartialView(trainingList);
}
//Default return all.
else
{
return PartialView(trainingList);
}
}
public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter)
{
bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status;
int ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
string ECNTitle = ecnDMO.GetECN(ECNNumber).Title;
ViewBag.TrainingGroups = adminDMO.GetTrainingGroups();
ViewBag.TrainingStatus = trainingStatus;
ViewBag.ECNNumber = ECNNumber;
ViewBag.ECNTitle = ECNTitle;
ViewBag.trainingID = trainingID;
IEnumerable<TrainingAssignment> trainingAssignments = trainingDMO.GetAllTrainingAssignments(trainingID);
//Calculate Percent Complete:
float percentComplete = 0;
float assignmentCount = trainingAssignments.Count();
float totalCompleted = 0;
foreach (var assignment in trainingAssignments)
{
if (assignment.status == true)
{
totalCompleted++;
}
}
percentComplete = (totalCompleted / assignmentCount) * 100;
ViewBag.PercentComplete = percentComplete.ToString("0.00") + "%";
if (groupFilter != "" && groupFilter != null)
{
ViewBag.GroupFilter = groupFilter;
List<TrainingAssignment> groupFilteredTraining = new List<TrainingAssignment>();
List<int> groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter));
foreach (var assignment in trainingAssignments)
{
if(trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID))
{
groupFilteredTraining.Add(assignment);
}
}
trainingAssignments = groupFilteredTraining;
}
if (statusFilter != "" && statusFilter != null)
{
List<TrainingAssignment> filteredTraining = new List<TrainingAssignment>();
switch (statusFilter)
{
case "1":
//Completed
filteredTraining = (from a in trainingAssignments where a.status == true && a.Deleted != true select a).ToList();
break;
case "2":
//In Progress
filteredTraining = (from a in trainingAssignments where a.status != true && a.Deleted != true select a).ToList();
break;
case "3":
//Cancelled
filteredTraining = (from a in trainingAssignments where a.Deleted == true select a).ToList();
break;
default:
filteredTraining = (from a in trainingAssignments select a).ToList();
break;
}
trainingAssignments = filteredTraining;
//return PartialView(trainingList);
}
return PartialView(trainingAssignments);
}
public ActionResult ViewTrainingAssignments(int trainingID)
{
bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status;
int ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
string ECNTitle = ecnDMO.GetECN(ECNNumber).Title;
ViewBag.TrainingStatus = trainingStatus;
ViewBag.ECNNumber = ECNNumber;
ViewBag.ECNTitle = ECNTitle;
ViewBag.TrainingId = trainingID;
ViewBag.AllUsers = userDMO.GetAllUsers();
IEnumerable<TrainingAssignment> trainingAssignments = trainingDMO.GetTrainingAssignments(trainingID);
return View(trainingAssignments);
}
/// <summary>
/// Method to return all the training assignments for a specified user
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public ActionResult ViewMyTrainingAssignments()
{
int userID = (int)Session[GlobalVars.SESSION_USERID];
List<TrainingAssignment> assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID);
List<ECNTrainingAssignments> ViewData = new List<ECNTrainingAssignments>();
foreach (var assignment in assignments)
{
Training training = trainingDMO.GetTraining(assignment.TrainingID);
if (training != null)
{
int ecnID = training.ECN;
ViewData.Add(new ECNTrainingAssignments
{
TrainingAssignmentID = assignment.ID,
ECN_ID = ecnID,
TrainingID = assignment.TrainingID,
DateAssigned = assignment.DateAssigned,
DateCompleted = assignment.DateCompleted,
Status = assignment.status
});
}
}
return View(ViewData);
}
/// <summary>
/// Method to return all assigned documents for a specified training assignment
/// </summary>
/// <param name="assignmentID"></param>
/// <returns></returns>
public ActionResult ViewMyTrainingAssignment(int assignmentID, int ECNNumber)
{
ViewBag.ECNNumber = ECNNumber;
ViewBag.AssignmentID = assignmentID;
ViewBag.IsCompleted = trainingDMO.GetAssignment(assignmentID).status;
return View(trainingDMO.GetAssignedDocs(assignmentID));
}
public ActionResult ViewTrainings()
{
IEnumerable<Training> AllTrainings = trainingDMO.GetTrainings();
return View(AllTrainings);
}
public ActionResult ViewAllTrainings()
{
return View();
}
public ActionResult DeleteAssignment(int assignmentId)
{
trainingDMO.DeleteTrainingAssignment(assignmentId);
trainingDMO.DeleteTrainingDocAck(assignmentId);
//Below checks and updates the training status
//TO-DO Put this in its own method.
bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(assignmentId);
if (isFinishedTrainingAssignment)
{
try
{
trainingDMO.UpdateAssignmentStatus(assignmentId);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(assignmentId);
if (isFinishedTraining)
{
int TrainingID = trainingDMO.GetTrainingIdByAssignment(assignmentId);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
string exception = e.ToString();
return Content(exception, "application/json");
}
}
return Json(new { test = "Succesfully saved" });
}
public ActionResult ManuallyExecuteECNTraining(int ecnId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
//Get ECN
ECN ecn = ecnDMO.GetECN(ecnId);
if (ecn != null)
{
Create(ecnId);
return Content("Success");
}
else
{
return Content("Invalid ECN");
}
}
else
{
return Content("Not Autthorized");
}
}
//public ActionResult ViewAllTraining()
//{
// return View();
//}
//public ActionResult GetTrainings([DataSourceRequest] DataSourceRequest request)
//{
// return Json();
//}
}
}

View File

@ -0,0 +1,99 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
namespace Fab2ApprovalSystem.Controllers
{
public class WorkflowController : Controller
{
//
//
// GET: /Workflow/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Workflow/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Workflow/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Workflow/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Workflow/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Workflow/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Workflow/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}