public async Task <IActionResult> OnGetAsync(string indexForm) { WebAppUser user = await _userHandler.GetUserAsync(HttpContext.User); bool isViewer = await _userHandler.IsViewer(user, indexForm); bool OwnerRight = await _userHandler.IsRightAsync(user, RightsType.ViewOwn, indexForm); bool GroupRight = await _userHandler.IsRightAsync(user, RightsType.ViewGroup, indexForm); if (!isViewer & !OwnerRight & !GroupRight) { return(Forbid()); } MtdForm = await _context.MtdForm.FindAsync(indexForm); if (MtdForm == null) { return(NotFound()); } ViewData["IdForm"] = indexForm; return(Page()); }
public async Task <IActionResult> Register(RegisterViewModel vm) { if (ModelState.IsValid) { if (vm.Password == vm.RepeatedPassword) { if (await _userManager.FindByNameAsync(vm.Username) == null || _userManager.FindByEmailAsync(vm.Email) == null) { var NewUser = new WebAppUser() { FirstName = vm.FirstName, LastName = vm.LastName, UserName = vm.Username, Email = vm.Email, DateOfBirth = vm.DateOfBirth }; await _userManager.CreateAsync(NewUser, vm.Password); _context.SaveChangesAsync().Wait(); return(RedirectToAction("Login", "Auth")); } } } return(View()); }
public async Task <IActionResult> OnPostDeleteAsync() { IFormCollection requestForm = await Request.ReadFormAsync(); string idStore = requestForm["store-delete-id"]; MtdStore mtdStore = await _context.MtdStore.FindAsync(idStore); if (mtdStore == null) { return(NotFound()); } WebAppUser webAppUser = await _userHandler.GetUserAsync(HttpContext.User); bool isEraser = await _userHandler.IsEraser(webAppUser, mtdStore.MtdForm, mtdStore.Id); if (!isEraser) { return(Ok(403)); } _context.MtdStore.Remove(mtdStore); await _context.SaveChangesAsync(); return(Ok()); }
public async Task <IActionResult> PostWaitListSetAsync() { IFormCollection requestForm = await Request.ReadFormAsync(); string idForm = requestForm["id-form-waitlist"]; WebAppUser user = await _userManager.GetUserAsync(HttpContext.User); MtdFilter mtdFilter = await _context.MtdFilter.Where(x => x.IdUser == user.Id && x.MtdForm == idForm).FirstOrDefaultAsync(); if (mtdFilter == null) { mtdFilter = new MtdFilter { IdUser = user.Id, MtdForm = idForm, PageSize = 10, SearchText = "", SearchNumber = "", Page = 1, WaitList = 1, }; await _context.MtdFilter.AddAsync(mtdFilter); await _context.SaveChangesAsync(); return(Ok()); } mtdFilter.WaitList = mtdFilter.WaitList == 0 ? 1 : 0; _context.MtdFilter.Update(mtdFilter); await _context.SaveChangesAsync(); return(Ok()); }
public async Task <bool> IsApproverAsync(WebAppUser user) { bool isComplete = await IsComplete(); bool isApprovalForm = await IsApprovalFormAsync(); if (!isApprovalForm || isComplete) { return(false); } MtdApprovalStage mtdApprovalStage = await GetCurrentStageAsync(); MtdStore store = await GetStoreAsync(); bool forOwner = false; if (store.MtdStoreOwner != null) { MtdApprovalStage firstStage = await GetFirstStageAsync(); if (firstStage != null) { forOwner = (store.MtdStoreOwner.UserId.Equals(user.Id) && mtdApprovalStage.Id.Equals(firstStage.Id)); } } if (mtdApprovalStage != null && (mtdApprovalStage.UserId.Equals(user.Id) || forOwner)) { return(true); } return(false); }
public async Task <IActionResult> PostPageSize(string idForm, int number) { int temp = number; if (temp > 50) { temp = 50; } WebAppUser user = await _userManager.GetUserAsync(User); MtdFilter filter = await _context.MtdFilter.FirstOrDefaultAsync(x => x.IdUser == user.Id && x.MtdForm == idForm); if (filter == null) { filter = new MtdFilter { SearchNumber = "", SearchText = "" }; await _context.MtdFilter.AddAsync(filter); await _context.SaveChangesAsync(); } filter.PageSize = number; _context.MtdFilter.Update(filter); await _context.SaveChangesAsync(); return(Ok()); }
public IActionResult PostUser([FromBody] UserPostModel model) { if (model == null || string.IsNullOrEmpty(model.FirstName) || string.IsNullOrEmpty(model.LastName) || string.IsNullOrEmpty(model.LoginName) || string.IsNullOrEmpty(model.Password)) { return(new BadRequestObjectResult("invalid data")); } var existing = dataContext.WebAppUsers.FirstOrDefault(u => u.LoginName.Equals(model.LoginName)); if (existing != null) { return(new BadRequestObjectResult("user already existing")); } var newUser = new WebAppUser { LoginName = model.LoginName, FirstName = model.FirstName, LastName = model.LastName, Password = model.Password }; dataContext.WebAppUsers.Add(newUser); dataContext.SaveChanges(); return(new OkObjectResult(newUser)); }
public async Task <IActionResult> OnPostRejectAsync() { string storeId = Request.Form["id-store"]; bool completeOk = bool.TryParse(Request.Form["checkbox-complete"], out bool completeCheck); bool stageOk = int.TryParse(Request.Form["next-stage"], out int stageId); if (!stageOk || !completeOk) { return(NotFound()); } WebAppUser webAppUser = await _userHandler.GetUserAsync(HttpContext.User); ApprovalHandler approvalHandler = new ApprovalHandler(_context, storeId); bool isFirstStage = await approvalHandler.IsFirstStageAsync(); bool isApprover = await approvalHandler.IsApproverAsync(webAppUser); if (!isApprover || isFirstStage) { return(NotFound()); } bool isOk = await approvalHandler.ActionReject(completeCheck, stageId, webAppUser); if (isOk) { await SendEmailReject(approvalHandler); } return(Ok()); }
public FilterHandler(OrderMakerContext orderMakerContext, string idForm, WebAppUser user, UserHandler userHandler) { _context = orderMakerContext; _user = user; _userHandler = userHandler; IdForm = idForm; queryMtdStore = _context.MtdStore; }
private async Task InitIdentityAsync(IServiceScope scope) { RoleManager <WebAppRole> roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <WebAppRole> >(); UserManager <WebAppUser> userManager = scope.ServiceProvider.GetRequiredService <UserManager <WebAppUser> >(); bool exists = await roleManager.Roles.Where(x => x.NormalizedName == "ADMIN").AnyAsync(); if (exists) { return; } var roleAdmin = new WebAppRole { Name = "Admin", NormalizedName = "ADMIN", Title = "Administrator", Seq = 30 }; var roleUser = new WebAppRole { Name = "User", NormalizedName = "USER", Title = "User", Seq = 20 }; var roleGuest = new WebAppRole { Name = "Guest", NormalizedName = "GUEST", Title = "Guest", Seq = 10 }; await roleManager.CreateAsync(roleAdmin); await roleManager.CreateAsync(roleUser); await roleManager.CreateAsync(roleGuest); WebAppUser webAppUser = new WebAppUser { Email = "*****@*****.**", EmailConfirmed = true, Title = "Administrator", UserName = "******", }; await userManager.CreateAsync(webAppUser, "Admin&890"); await userManager.AddToRoleAsync(webAppUser, "Admin"); }
private async Task <bool> SendEmailApprove(ApprovalHandler approvalHandler) { string ownerId = await approvalHandler.GetOwnerID(); WebAppUser userCurrent = await _userHandler.GetUserAsync(HttpContext.User); WebAppUser userOwner = _userHandler.Users.Where(x => x.Id == ownerId).FirstOrDefault(); string storeId = await approvalHandler.GetStoreID(); MtdForm mtdForm = await approvalHandler.GetFormAsync(); MtdApprovalStage stageNext = await approvalHandler.GetNextStageAsync(); if (stageNext != null) { WebAppUser userNext = _userHandler.Users.Where(x => x.Id == stageNext.UserId).FirstOrDefault(); BlankEmail blankEmail = new BlankEmail { Subject = _localizer["Approval event"], Email = userNext.Email, Header = _localizer["Approval required"], Content = new List <string> { $"<strong>{_localizer["Document"]} - {mtdForm.Name}</strong>", $"{_localizer["User"]} {userCurrent.Title} {_localizer["approved the document at"]} {DateTime.Now}", $"{_localizer["Click on the link to view the document that required to approve."]}", $"<a href='http://{HttpContext.Request.Host}/workplace/store/details?id={storeId}'>{_localizer["Document link"]}</a>" } }; await _emailSender.SendEmailBlankAsync(blankEmail); } bool IsFirstStage = await approvalHandler.IsFirstStageAsync(); if (!IsFirstStage) { BlankEmail blankEmail = new BlankEmail { Subject = _localizer["Approval event"], Email = userOwner.Email, Header = _localizer["Approval process event"], Content = new List <string> { $"<strong>{_localizer["Document"]} - {mtdForm.Name}</strong>", $"{_localizer["User"]} {userCurrent.Title} {_localizer["approved the document at"]} {DateTime.Now}", $"{_localizer["Click on the link to view the document."]}", $"<a href='http://{HttpContext.Request.Host}/workplace/store/details?id={storeId}'>{_localizer["Document link"]}</a>" } }; await _emailSender.SendEmailBlankAsync(blankEmail); } return(true); }
public async Task <IActionResult> OnGetAsync(string searchText) { WebAppUser user = await _userHandler.GetUserAsync(HttpContext.User); List <string> formIds = await _userHandler.GetFormIdsAsync(user, RightsType.View, RightsType.ViewGroup, RightsType.ViewOwn); List <MtdForm> forms = await _context.MtdForm.Where(x => formIds.Contains(x.Id)).ToListAsync(); foreach (var form in forms) { bool isExists = await _context.MtdFilter.Where(x => x.MtdForm == form.Id && x.IdUser == user.Id).AnyAsync(); if (!isExists) { MtdFilter mtdFilter = new MtdFilter { MtdForm = form.Id, IdUser = user.Id, Page = 1, PageSize = 10, SearchText = "", ShowDate = 1, WaitList = 0, SearchNumber = "", ShowNumber = 1 }; await _context.MtdFilter.AddAsync(mtdFilter); await _context.SaveChangesAsync(); } } IQueryable <MtdForm> query = _context.MtdForm .Include(x => x.MtdCategoryNavigation) .Include(x => x.MtdFormHeader) .Include(x => x.MtdFormDesk) .Where(x => formIds.Contains(x.Id)); if (searchText != null) { query = query.Where(x => x.Name.Contains(searchText)); SearchText = searchText; } Forms = await query.ToListAsync(); return(Page()); }
public async Task <IViewComponentResult> InvokeAsync(MtdStore store, FormType type = FormType.Details) { if (store == null) { return(View()); } WebAppUser webAppUser = await _userHandler.GetUserAsync(HttpContext.User); if (type == FormType.Create) { store.MtdFormNavigation.MtdFormHeader = await _context.MtdFormHeader.FindAsync(store.MtdForm); store.MtdFormNavigation.ParentNavigation = await _context.MtdForm.FindAsync(store.MtdFormNavigation.Parent); List <MtdFormPart> mtdFormParts = new List <MtdFormPart>(); IList <MtdFormPart> parts = await GetPartsAsync(store.MtdForm); foreach (MtdFormPart formPart in parts) { bool isCreator = await _userHandler.IsCreatorPartAsync(webAppUser, formPart.Id); if (isCreator) { mtdFormParts.Add(formPart); } } IList <MtdFormPartField> mtdFormPartFields = await GetFieldsAsync(mtdFormParts); DataSet dataSetForCreate = new DataSet() { Store = store, Parts = mtdFormParts, Fields = mtdFormPartFields, Stack = new List <MtdStoreStack>() }; return(View("Create", dataSetForCreate)); } DataContainer dataContainer = new DataContainer { Owner = await CreateDataSetAsync(store, type), Parent = await CreateDataSetAsync(store.ParentNavigation) }; return(View(type.ToString(), dataContainer)); }
private async Task LoadSharedKeyAndQrCodeUriAsync(WebAppUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
public async Task <IActionResult> PostPageMove() { /* number * 1 - First Page; 2 - back; 3 - forward; */ IFormCollection requestForm = await Request.ReadFormAsync(); string idForm = requestForm["formId"]; string formValue = requestForm["formValue"]; int number = int.Parse(formValue); WebAppUser user = await _userManager.GetUserAsync(User); MtdFilter filter = await _context.MtdFilter.FirstOrDefaultAsync(x => x.IdUser == user.Id && x.MtdForm == idForm); if (filter == null) { filter = new MtdFilter { SearchNumber = "", SearchText = "" }; await _context.MtdFilter.AddAsync(filter); await _context.SaveChangesAsync(); } int page = filter.Page; switch (number) { case 2: { if (page > 1) { page--; } break; } case 3: { page++; break; } default: { page = 1; break; } } ; filter.Page = page < 0 ? page = 1 : page; _context.MtdFilter.Update(filter); await _context.SaveChangesAsync(); return(Ok()); }
public async Task <object> Register([FromBody] RegisterDto model) { var v = new Validate() { Key = 0, Message = new List <string>() }; if (ModelState.IsValid) { var user = new WebAppUser { UserName = model.Email, Email = model.Email, Name = model.Name, AvatarUrl = model.AvatarUrl, }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(GenerateJwtToken(model.Email, user)); } else { v.Key = 999; v.Message = result.Errors.Select(x => x.Description).ToList(); return(Json(v)); } } else { foreach (var x in ModelState) { foreach (var erro in x.Value.Errors) { v.Key = 999; v.Message.Add(erro.ErrorMessage); } } } return(Json(v)); }
public async Task <IActionResult> OnPostSetOwnerAsync() { IFormCollection requestForm = await Request.ReadFormAsync(); string idStore = requestForm["setowner-id-store"]; string idUser = requestForm["setowner-id-user"]; WebAppUser webAppUser = await _userHandler.FindByIdAsync(idUser); if (webAppUser != null) { MtdStoreOwner mtdStoreOwner = await _context.MtdStoreOwner.Include(x => x.IdNavigation).FirstOrDefaultAsync(x => x.Id == idStore); if (mtdStoreOwner == null) { string idForm = mtdStoreOwner.IdNavigation.MtdForm; bool IsInstllerOwner = await _userHandler.IsInstallerOwner(webAppUser, idForm, mtdStoreOwner.Id); if (!IsInstllerOwner) { return(Forbid()); } mtdStoreOwner = new MtdStoreOwner { Id = idStore, UserId = webAppUser.Id, UserName = webAppUser.Title }; await _context.MtdStoreOwner.AddAsync(mtdStoreOwner); await _context.SaveChangesAsync(); return(Ok()); } mtdStoreOwner.UserId = webAppUser.Id; mtdStoreOwner.UserName = webAppUser.Title; _context.Entry(mtdStoreOwner).State = EntityState.Modified; await _context.SaveChangesAsync(); } return(Ok()); }
public async Task <IActionResult> PostSearchTextAsync() { IFormCollection requestForm = await Request.ReadFormAsync(); string form = requestForm["indexForm"]; string value = requestForm["indexSearchText"]; WebAppUser user = await _userManager.GetUserAsync(User); MtdFilter filter = await _context.MtdFilter.FirstOrDefaultAsync(x => x.IdUser == user.Id& x.MtdForm == form); bool old = true; if (filter == null) { old = false; filter = new MtdFilter { IdUser = user.Id, MtdForm = form }; } filter.SearchNumber = ""; filter.SearchText = value; filter.Page = 1; if (old) { _context.MtdFilter.Update(filter); } else { await _context.MtdFilter.AddAsync(filter); } try { await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex.InnerException; } return(Ok()); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new WebAppUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
public async Task <IActionResult> OnPostApproveAsync() { string storeId = Request.Form["id-store"]; WebAppUser webAppUser = await _userHandler.GetUserAsync(HttpContext.User); ApprovalHandler approvalHandler = new ApprovalHandler(_context, storeId); bool isApprover = await approvalHandler.IsApproverAsync(webAppUser); if (!isApprover) { return(NotFound()); } bool isOk = await approvalHandler.ActionApprove(webAppUser); if (isOk) { await SendEmailApprove(approvalHandler); } return(Ok()); }
public async Task <ApprovalStatus> GetStatusAsync(WebAppUser appUser) { ApprovalStatus status = ApprovalStatus.Start; MtdApprovalStage stage = await GetCurrentStageAsync(); if (stage == null) { return(status); } bool isComplete = await IsComplete(); int result = await GetResultAsync(); bool isFirst = await IsFirstStageAsync(); bool isApprover = await IsApproverAsync(appUser); status = DefineStatus(isComplete, result, isFirst, isApprover); return(status); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new WebAppUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private object GenerateJwtToken(string email, WebAppUser user) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"])); var token = new JwtSecurityToken( _configuration["JwtIssuer"], _configuration["JwtIssuer"], claims, expires: expires, signingCredentials: creds ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task <IActionResult> CreateUser(UserModel model) { if (ModelState.IsValid) { var user = new WebAppUser { UserName = model.UserName, Email = model.Email }; var result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(BuildToken(model)); } else { return(BadRequest("Username or password invalid")); } } else { return(BadRequest(ModelState)); } }
public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { return(RedirectToPage("./Lockout")); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; ProviderDisplayName = info.ProviderDisplayName; if (!info.Principal.HasClaim(c => c.Type == ClaimTypes.Name)) { ErrorMessage = "Missing username claim"; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } string userName = info.Principal.FindFirst(ClaimTypes.Name).Value; var user = new WebAppUser { UserName = userName }; var userRes = await _userManager.CreateAsync(user); if (userRes.Succeeded) { userRes = await _userManager.AddLoginAsync(user, info); if (userRes.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider); return(RedirectToPage("./Manage/Index")); } } foreach (var error in userRes.Errors) { ModelState.AddModelError(string.Empty, error.Description); } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); } }
public static async Task <List <ApprovalStore> > GetStoreStatusAsync(OrderMakerContext context, IList <string> storeIds, WebAppUser appUser) { List <ApprovalStore> result = new List <ApprovalStore>(); IList <MtdStoreApproval> mtdStoreApprovals = await context.MtdStoreApproval .Include(x => x.MdApproveStageNavigation) .Where(x => storeIds.Contains(x.Id)) .ToListAsync(); List <string> approvalIds = mtdStoreApprovals.Select(x => x.MdApproveStageNavigation.MtdApproval).ToList(); IList <MtdApprovalStage> stages = await context.MtdApprovalStage .Where(x => approvalIds.Contains(x.MtdApproval)) .OrderBy(x => x.Stage).ToListAsync(); foreach (string storeId in storeIds) { ApprovalStore approvalStore = new ApprovalStore { StoreId = storeId }; MtdStoreApproval sa = mtdStoreApprovals.Where(x => x.Id == storeId).FirstOrDefault(); if (sa == null) { approvalStore.Status = ApprovalStatus.Start; } else { bool isComplete = sa.Complete == 1 ? true : false; int approved = sa.Result; string approvalId = sa.MdApproveStageNavigation.MtdApproval; int currentId = sa.MtdApproveStage; int firstId = stages.Where(x => x.MtdApproval == approvalId) .OrderBy(x => x.Stage).Select(x => x.Id).FirstOrDefault(); bool isFirst = currentId == firstId ? true : false; bool isApprover = sa.MdApproveStageNavigation.UserId == appUser.Id ? true : false; approvalStore.Status = DefineStatus(isComplete, approved, isFirst, isApprover); } result.Add(approvalStore); } return(result); }
public async Task <bool> ActionReject(bool complete, int idStage, WebAppUser webAppUser) { MtdStore mtdStore = await GetStoreAsync(); if (mtdStore.MtdStoreApproval != null && mtdStore.MtdStoreApproval.Complete == 1) { return(false); } MtdApproval mtdApproval = await GetApproval(); MtdApprovalStage currentStage = await GetCurrentStageAsync(); MtdApprovalStage prevStage; if (!complete) { prevStage = mtdApproval.MtdApprovalStage.Where(x => x.Id == idStage).FirstOrDefault(); } else { prevStage = await GetCurrentStageAsync(); } if (prevStage == null) { return(false); } var allStages = await GetStagesAsync(); var blockPartsStage = allStages.Where(x => x.Stage < prevStage.Stage).FirstOrDefault(); MtdStoreApproval storeApproval = new MtdStoreApproval { Id = mtdStore.Id, MtdApproveStage = prevStage.Id, PartsApproved = blockPartsStage == null ? "&" : blockPartsStage.BlockParts, Complete = complete ? (sbyte)1 : (sbyte)0, Result = -1, }; if (mtdStore.MtdStoreApproval == null) { await _context.MtdStoreApproval.AddAsync(storeApproval); } else { try { _context.MtdStoreApproval.Update(storeApproval); } catch (Exception e) { throw e; } } MtdLogApproval mtdLogApproval = new MtdLogApproval() { MtdStore = mtdStore.Id, Result = -1, Stage = currentStage.Stage, Timecr = DateTime.Now, UserId = webAppUser.Id }; await _context.MtdLogApproval.AddAsync(mtdLogApproval); try { await _context.SaveChangesAsync(); } catch { return(false); } return(true); }
public static async Task <List <string> > GetWaitStoreIds(OrderMakerContext context, WebAppUser user, string formId) { List <string> approvalIds = await context.MtdApproval.Where(x => x.MtdForm == formId).Select(x => x.Id).ToListAsync(); List <int> stagesUser = await context.MtdApprovalStage.Where(x => approvalIds.Contains(x.MtdApproval) && x.UserId == user.Id).Select(x => x.Id).ToListAsync(); return(await context.MtdStoreApproval.Where(x => x.Complete == 0 && stagesUser.Contains(x.MtdApproveStage)).Select(x => x.Id).ToListAsync()); }
public async Task <bool> ActionApprove(WebAppUser webAppUser) { MtdStore mtdStore = await GetStoreAsync(); if (mtdStore.MtdStoreApproval != null && mtdStore.MtdStoreApproval.Complete == 1) { return(false); } MtdApprovalStage currentStage = await GetCurrentStageAsync(); MtdApprovalStage nextStage = await GetNextStageAsync(); sbyte complete = 0; if (nextStage == null) { complete = 1; nextStage = await GetLastStageAsync(); } ; MtdStoreApproval storeApproval = new MtdStoreApproval { Id = mtdStore.Id, MtdApproveStage = nextStage.Id, PartsApproved = currentStage.BlockParts, Complete = complete, Result = 1, }; if (mtdStore.MtdStoreApproval == null) { await _context.MtdStoreApproval.AddAsync(storeApproval); } else { _context.MtdStoreApproval.Update(storeApproval); } MtdLogApproval mtdLogApproval = new MtdLogApproval() { MtdStore = mtdStore.Id, Result = 1, Stage = currentStage.Id, Timecr = DateTime.Now, UserId = webAppUser.Id }; await _context.MtdLogApproval.AddAsync(mtdLogApproval); try { await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex.InnerException; } return(true); }
private async Task <DataSet> CreateDataSetAsync(MtdStore store, FormType type = FormType.Details) { if (store == null) { return(null); } WebAppUser webAppUser = await _userHandler.GetUserAsync(HttpContext.User); List <MtdFormPart> mtdFormParts = new List <MtdFormPart>(); IList <MtdFormPart> parts = await GetPartsAsync(store.MtdForm); bool isReviewer = await _userHandler.IsReviewer(webAppUser, store.MtdForm); ApprovalHandler approvalHandler = new ApprovalHandler(_context, store.Id); List <string> blockedParts = new List <string>(); if (!isReviewer) { blockedParts = await approvalHandler.GetBlockedPartsIds(); } foreach (MtdFormPart formPart in parts) { if (type == FormType.Edit) { bool isEditor = await _userHandler.IsEditorPartAsync(webAppUser, formPart.Id); if (isEditor && !blockedParts.Contains(formPart.Id)) { mtdFormParts.Add(formPart); } } else { bool isViewer = await _userHandler.IsViewerPartAsync(webAppUser, formPart.Id); if (isViewer) { mtdFormParts.Add(formPart); } } } IList <MtdFormPartField> mtdFormPartFields = await GetFieldsAsync(mtdFormParts); var mtdStore = await _context.MtdStore .Include(m => m.ParentNavigation) .Include(m => m.MtdFormNavigation) .ThenInclude(m => m.MtdFormHeader) .Include(m => m.MtdFormNavigation) .ThenInclude(m => m.ParentNavigation) .FirstOrDefaultAsync(m => m.Id == store.Id); IList <long> ids = await _context.MtdStoreStack.Where(x => x.MtdStore == mtdStore.Id).Select(x => x.Id).ToListAsync(); IList <MtdStoreStack> stack = await _context.MtdStoreStack .Include(m => m.MtdStoreStackText) .Include(m => m.MtdStoreStackDecimal) .Include(m => m.MtdStoreStackFile) .Include(m => m.MtdStoreStackDate) .Include(m => m.MtdStoreStackInt) .Include(m => m.MtdStoreLink) .Where(x => ids.Contains(x.Id)) .ToListAsync(); DataSet result = new DataSet() { Store = mtdStore, Parts = mtdFormParts, Fields = mtdFormPartFields, Stack = stack, }; return(result); }