public async Task <Result> Update(UpdateResultDto resultDto) { var result = await _context.Results.FirstOrDefaultAsync(r => r.Player.Name == resultDto.Name && r.Category.Type == resultDto.Category); if (result == null) { // Add function that creates instead of having it nested in an Update function - repository pattern var newResult = new Result { Id = Guid.NewGuid(), Category = await _context.Categories.FirstOrDefaultAsync(c => c.Type == resultDto.Category), Player = await _context.Players.FirstOrDefaultAsync(p => p.Name == resultDto.Name), Score = resultDto.Score, Updated = DateTime.Now }; result = newResult; await _context.Results.AddAsync(result); } else { if (resultDto.Score > result.Score) { result.Score = resultDto.Score; result.Updated = DateTime.Now; } _context.Results.Update(result); } await _context.SaveChangesAsync(); return(result); }
// Returns a single resultDto from UpdatePlayerResultDto private UpdateResultDto GetResultFromUpdatePlayerResultDto(UpdatePlayerResultDto result) { var updateResultDto = new UpdateResultDto { Name = result.Name, Category = result.Category, Score = result.Score }; return(updateResultDto); }
public async Task <ITroubleCodeRecommendationDto> SaveAsync(ITroubleCodeRecommendationDto update) { UpdateResultDto result; try { // Check Update. if (update == null) { throw new NullReferenceException("Update can NOT be NULL."); } // Create Parameter. var param = new { User.UserGuid, update.TroubleCodeRecommendationId, update.TroubleCodeRecommendationText, update.ActiveInd }; // Execute Update. var recommendationId = (await Conn.QueryAsync <int>("Scan.usp_SaveTroubleCodeRecommendation", param, null, null, CommandType.StoredProcedure)).First(); // Set Result. result = new UpdateResultDto(true, "Recommendation Updated."); // Load Request. update = await GetByIdAsync(recommendationId.ToString()); } catch (Exception e) { // Log Error. Logger.LogException(e); // Set Error Result. result = new UpdateResultDto(false, e.Message); } // Set Result. if (update == null) { update = new TroubleCodeRecommendationDto(); } update.UpdateResult = result; // Return. return(update); }
public IAccountDto Save(IAccountDto account) { AccountEntityModel update; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Limit Discount Percentage. if (account.DiscountPercentage > 100) { account.DiscountPercentage = 100; } // Check for New Account. if (account.AccountGuid == Guid.Empty) { // Verify Access for Add. if (!UserHasRoles(ApplicationRoles.AccountCreate)) { // No Ability to Add. account.UpdateResult = new UpdateResultDto(false, "You do not have access to create a record."); return(account); } // Get Entity. update = Mapper.Map <AccountEntityModel>(account); // Allow Set Discount. if (!UserHasRoles(ApplicationRoles.PaymentCreate)) { update.DiscountPercentage = 0; } // Set Creation. update.CreatedByUserGuid = User.UserGuid; update.CreatedDt = DateTimeOffset.UtcNow; if (!UserHasRoles(ApplicationRoles.AccountShowAll)) { update.AccountUsers = new List <UserAccountEntityModel> { new UserAccountEntityModel { UserGuid = User.UserGuid, CreatedByUserGuid = User.UserGuid, CreatedDt = DateTimeOffset.UtcNow } }; } Db.Accounts.Add(update); // Create Result. result = new UpdateResultDto(true, "Account Created Successfully."); } else { // Verify Access to Edit. if ((!AllowedAccounts?.Any(a => a.AccountGuid == account.AccountGuid) ?? true) || !UserHasRoles(ApplicationRoles.AccountEdit)) { // No Ability to Edit. account.UpdateResult = new UpdateResultDto(false, "You do not have access to modify this record."); return(account); } // Load Account for Update. update = AllowedAccounts.FirstOrDefault(a => a.AccountGuid == account.AccountGuid); // Check Account. if (update != null) { // Update Account Fields. update.Name = account.Name; update.Address1 = account.Address1; update.Address2 = account.Address2; update.City = account.City; update.State = Db.States.FirstOrDefault(s => s.Abbreviation == account.State); update.Zip = account.Zip; update.Phone = account.Phone; update.Fax = account.Fax; update.EmployeeGuid = account.EmployeeGuid; // Check Active. if (account.ActiveInd) { update.ActiveInd = account.ActiveInd; } // Check Payment Create Permission. if (UserHasRoles(ApplicationRoles.PaymentCreate)) { update.DiscountPercentage = account.DiscountPercentage; } // Set Update. update.UpdatedByUserGuid = User.UserGuid; update.UpdatedDt = DateTimeOffset.UtcNow; Db.Entry(update).State = EntityState.Modified; // Create Result. result = new UpdateResultDto(true, "Account Updated Successfully."); } } // Save. Db.SaveChanges(); // Load Account. account = GetById(update?.AccountGuid.ToString() ?? account.AccountGuid.ToString()); // Set Update Results. account.UpdateResult = result; return(account); }
public IReleaseNoteDto Save(IReleaseNoteDto releaseNote) { ReleaseNoteEntityModel update; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Check for New Release Note. if (releaseNote.ReleaseNoteId == 0) { // Get Entity. update = Mapper.Map <ReleaseNoteEntityModel>(releaseNote); // Set Created. update.CreatedByUserGuid = User.UserGuid; update.CreatedDt = DateTimeOffset.UtcNow; foreach (var releaseNoteRoleEntityModel in update.ReleaseNoteRoles ?? new List <ReleaseNoteRoleEntityModel>()) { releaseNoteRoleEntityModel.CreatedByUserGuid = User.UserGuid; } // Add Entity. Db.ReleaseNotes.Add(update); // Set Result. result = new UpdateResultDto(true, "Release Note Created Successfully."); } else { // Load Release Note for Update. update = Db.ReleaseNotes.FirstOrDefault(s => s.ReleaseNoteId == releaseNote.ReleaseNoteId); // Check Release Note. if (update != null) { // Update Release Note Fields. update.ReleaseNote = releaseNote.ReleaseNote; update.Summary = releaseNote.Summary; update.DevelopmentId = releaseNote.DevelopmentId; update.Version = releaseNote.Version; update.ReleaseNoteRoles.Clear(); update.ReleaseNoteRoles = releaseNote.ImpactedRoleGuids?.Select(x => new ReleaseNoteRoleEntityModel() { ReleaseNoteId = releaseNote.ReleaseNoteId, RoleGuid = x, CreatedByUserGuid = User.UserGuid }) .ToList(); // Set Updated. update.UpdatedByUserGuid = User.UserGuid; update.UpdatedDt = DateTimeOffset.UtcNow; // Update Entry. Db.Entry(update).State = EntityState.Modified; // Set Result. result = new UpdateResultDto(true, "Release Note Updated Successfully."); } } // Save. Db.SaveChanges(); // Load Release Note. releaseNote = GetById(update?.ReleaseNoteId.ToString() ?? releaseNote.ReleaseNoteId.ToString()); // Set Update Result. releaseNote.UpdateResult = result; return(releaseNote); }
public IReportDto Save(IReportDto update) { UpdateResultDto result; var requestId = update?.RequestId ?? 0; try { // Check Update. if (update == null) { throw new NullReferenceException("Update can NOT be NULL."); } // Create Decisions. var decisions = new DataTable(); decisions.Columns.Add("DecisionId", typeof(int)); decisions.Columns.Add("DecisionText", typeof(string)); decisions.Columns.Add("DecisionTextSeverity", typeof(int)); // Load Decisions. foreach (var decision in update.DecisionSelections) { if (decision.DecisionSelected) { decisions.Rows.Add(decision.DecisionId, decision.DecisionText, (int)decision.DecisionTextSeverity); } } // Create Recommendations. var recommendations = new DataTable(); recommendations.Columns.Add("ReportOrderTroubleCodeId", typeof(long)); recommendations.Columns.Add("ControllerId", typeof(int)); recommendations.Columns.Add("ControllerIdOrig", typeof(int)); recommendations.Columns.Add("ControllerName", typeof(string)); recommendations.Columns.Add("ControllerNameOrig", typeof(string)); recommendations.Columns.Add("TroubleCodeId", typeof(int)); recommendations.Columns.Add("TroubleCodeIdOrig", typeof(int)); recommendations.Columns.Add("TroubleCode", typeof(string)); recommendations.Columns.Add("TroubleCodeOrig", typeof(string)); recommendations.Columns.Add("TroubleCodeDescription", typeof(string)); recommendations.Columns.Add("TroubleCodeDescriptionOrig", typeof(string)); recommendations.Columns.Add("ResultTroubleCodeId", typeof(long)); recommendations.Columns.Add("InformCustomerInd", typeof(bool)); recommendations.Columns.Add("AccidentRelatedInd", typeof(bool)); recommendations.Columns.Add("ExcludeFromReportInd", typeof(bool)); recommendations.Columns.Add("CodeClearedInd", typeof(bool)); recommendations.Columns.Add("TroubleCodeNoteText", typeof(string)); recommendations.Columns.Add("TroubleCodeRecommendationId", typeof(int)); recommendations.Columns.Add("TroubleCodeRecommendationText", typeof(string)); recommendations.Columns.Add("RecommendationTextSeverity", typeof(int)); // Load Recommendations. foreach (var recommendation in update.TroubleCodeRecommendations .Where(r => r.Recommendations.Any(c => c.CurrentRequestInd))) { recommendations.Rows.Add (recommendation.ReportOrderTroubleCodeId, recommendation.ControllerId, recommendation.ControllerIdOrig, recommendation.ControllerName, recommendation.ControllerNameOrig, recommendation.TroubleCodeId, recommendation.TroubleCodeIdOrig, recommendation.TroubleCode, recommendation.TroubleCodeOrig, recommendation.TroubleCodeDescription, recommendation.TroubleCodeDescriptionOrig, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.ResultTroubleCodeId, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.InformCustomerInd, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.AccidentRelatedInd, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.ExcludeFromReportInd, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.CodeClearedInd, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.TroubleCodeNoteText, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.TroubleCodeRecommendationId, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.TroubleCodeRecommendationText, recommendation.Recommendations.First(s => s.CurrentRequestInd)?.RecommendationTextSeverity ?? 0); } // Create Vehicle Make Tools. var vehicleMakeTools = new DataTable(); vehicleMakeTools.Columns.Add("VehicleMakeToolId", typeof(int)); vehicleMakeTools.Columns.Add("ToolVersion", typeof(string)); // Load Vehicle Make Tools. foreach (var item in update.VehicleMakeTools.Where(x => x.CheckedInd)) { vehicleMakeTools.Rows.Add(item.VehicleMakeToolId, item.ToolVersion); } // Create Parameter. var param = new { update.RequestId, update.RequestTypeId, update.RequestCategoryId, update.AirProToolId, update.ReportFooterHTML, update.ReportHeaderHTML, update.TechnicianNotes, update.CompleteReport, update.CancelReport, update.CancelNotes, update.CancelReasonTypeId, update.ResponsibleTechUserId, update.ReportVersion, WorkTypeIds = JsonConvert.SerializeObject(update.WorkTypeSelections.Where(t => t.WorkTypeSelected).Select(t => t.WorkTypeId).ToArray()), ResultIds = JsonConvert.SerializeObject(update.DiagnosticResultSelections.Where(r => r.AssignedToRequestInd).Select(r => r.ResultId).ToArray()), SelectedResultIds = JsonConvert.SerializeObject(update.DiagnosticResultSelections.Where(r => r.SelectedForReportInd).Select(r => r.ResultId).ToArray()), ReviewedRuleIds = JsonConvert.SerializeObject(update.ValidationRules.Where(r => r.ResultAcknowledgedInd).Select(r => r.ValidationRuleId).ToArray()), Recommendations = recommendations, Decisions = decisions, User.UserGuid, ReportVehicleMakeTools = vehicleMakeTools }; // Execute Update. requestId = Conn.Query <int>("Scan.usp_SaveReport", param, null, true, null, CommandType.StoredProcedure).First(); // Set Result. result = new UpdateResultDto(true, "Scan Report Updated."); } catch (Exception e) { // Log Error. Logger.LogException(e); // Set Error Result. result = new UpdateResultDto(false, e.Message); } // Load Request. update = GetById(requestId.ToString()); // Set Result. update.UpdateResult = result; return(update); }
public async Task <IDecisionDto> SaveAsync(IDecisionDto update) { UpdateResultDto result; try { // Check Update. if (update == null) { throw new NullReferenceException("Update can NOT be NULL."); } // Create Vehicle Makes. var vehicleMakes = update.VehicleMakes.Where(m => m.SelectedInd) .Select(m => new { TypeId = m.VehicleMakeId, TypePreSelectedInd = m.PreSelectedInd }).GetSettingsTable(); // Create Request Types. var requestTypes = update.RequestTypes.Where(t => t.SelectedInd) .Select(t => new { TypeId = t.RequestTypeId, TypePreSelectedInd = t.PreSelectedInd }).GetSettingsTable(); // Create Request Categories. var requestCategories = update.RequestCategories.Where(c => c.SelectedInd) .Select(c => new { TypeId = c.RequestCategoryId, TypePreSelectedInd = c.PreSelectedInd }).GetSettingsTable(); // Create Parameter. var param = new { User.UserGuid, update.DecisionId, update.DecisionText, DefaultTextSeverity = (int)update.DefaultTextSeverity, update.ActiveInd, VehicleMakes = vehicleMakes, RequestTypes = requestTypes, RequestCategories = requestCategories }; // Execute Update. var decisionId = (await Conn.QueryAsync <int>("Scan.usp_SaveDecision", param, null, null, CommandType.StoredProcedure)).First(); // Set Result. result = new UpdateResultDto(true, "Decision Updated."); // Load Request. update = await GetByIdAsync(decisionId.ToString()); } catch (Exception e) { // Log Error. Logger.LogException(e); // Set Error Result. result = new UpdateResultDto(false, e.Message); } // Set Result. if (update == null) { update = new DecisionDto(); } update.UpdateResult = result; // Return. return(update); }
public IGroupDto Save(IGroupDto group) { GroupEntityModel update; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Check for New Group. if (group.GroupGuid == Guid.Empty) { // Verify Access for Add. if (!UserHasRoles(ApplicationRoles.GroupCreate)) { // No Ability to Add. group.UpdateResult = new UpdateResultDto(false, "You do not have access to create a record."); return(group); } // Get Entity. update = Mapper.Map <GroupEntityModel>(group); // Set Creation. update.CreatedByUserGuid = User.UserGuid; foreach (var role in update.Roles) { role.CreatedByUserGuid = User.UserGuid; } // Create Default Membership. var userGroup = new UserGroupEntityModel() { UserGuid = User.UserGuid, Group = update, CreatedByUserGuid = User.UserGuid }; Db.Entry(userGroup).State = EntityState.Added; // Add Entity. Db.Entry(update).State = EntityState.Added; // Set Result. result = new UpdateResultDto(true, "Group Created Successfully."); } else { // Verify Access to Edit. if ((!AllowedGroups?.Any(g => g.GroupGuid == group.GroupGuid) ?? true) || !UserHasRoles(ApplicationRoles.GroupEdit)) { // No Ability to Edit. group.UpdateResult = new UpdateResultDto(false, "You do not have access to modify this record."); return(group); } // Load Group for Update.s update = AllowedGroups.FirstOrDefault(g => g.GroupGuid == group.GroupGuid); // Check Group. if (update != null) { // Update Group. update.Name = group.Name; update.Description = group.Description; update.UpdatedByUserGuid = User.UserGuid; update.UpdatedDt = DateTimeOffset.UtcNow; // Parse Roles for Update/Delete. foreach (var role in update.Roles.ToList()) { // Update Existing Record. if (group.Roles?.Any(r => r.Key == role.RoleGuid) ?? false) { role.UpdatedByUserGuid = User.UserGuid; role.UpdatedDt = DateTimeOffset.UtcNow; } else // Delete Existing Record. { Db.GroupRoles.Remove(role); } } // Parse Roles for Add. if (group.Roles != null) { var existing = update.Roles.Select(r => r.RoleGuid).ToList(); foreach (var role in group.Roles.Where(r => !existing.Contains(r.Key))) { // Add New Role. var groupRole = new GroupRoleEntityModel() { Group = update, RoleGuid = role.Key, CreatedByUserGuid = User.UserGuid }; update.Roles.Add(groupRole); } } // Update Entry. Db.Entry(update).State = EntityState.Modified; // Set Result. result = new UpdateResultDto(true, "Group Updated Successfully."); } } // Save. Db.SaveChanges(); // Update User Roles. Db.Database.ExecuteSqlCommand("Access.usp_UserGroupRoleSync"); // Load Group. group = GetById(update?.GroupGuid.ToString() ?? group.GroupGuid.ToString()); // Set Update Result. group.UpdateResult = result; return(group); }
public IUserDto Save(IUserDto user) { UserEntityModel update; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Verify Groups. var allowedGroups = new GroupService(Settings).AllowedGroups.Select(g => g.GroupGuid); if (user.GroupMemberships?.Any(g => !allowedGroups.Contains(g)) ?? false) { // No Group Access. user.UpdateResult = new UpdateResultDto(false, "You do not have access to assign selected Group(s)."); return(user); } // Verify Shops. var allowedShops = new ShopService(Settings).AllowedShops.Select(s => s.ShopGuid); if (user.ShopMemberships?.Any(s => !allowedShops.Contains(s)) ?? false) { // No Shop Access. user.UpdateResult = new UpdateResultDto(false, "You do not have access to assign selected Shop(s)."); return(user); } // Verify Accounts. var allowedAccounts = new AccountService(Settings).AllowedAccounts.Select(a => a.AccountGuid); if (user.AccountMemberships?.Any(a => !allowedAccounts.Contains(a)) ?? false) { // No Account Access. user.UpdateResult = new UpdateResultDto(false, "You do not have access to assign selected Account(s)."); return(user); } // Check for New User. if (user.UserGuid == Guid.Empty) { // Verify Access for Add. if (!UserHasRoles(ApplicationRoles.UserCreate)) { // No Ability to Add. user.UpdateResult = new UpdateResultDto(false, "You do not have access to create a record."); return(user); } // Check Duplicate Address. if (Db.Users.Any(u => u.Email == user.Email)) { // Duplicate Account. user.UpdateResult = new UpdateResultDto(false, "An Account with this Email already Exists."); return(user); } // Get Entity. update = Mapper.Map <UserEntityModel>(user); // Verify Employee Assignment. if (!UserHasRoles(ApplicationRoles.AirProEmployeeAssign)) { update.EmployeeInd = false; } // Set Created. update.CreatedByUserGuid = User.UserGuid; update.CreatedDt = DateTimeOffset.UtcNow; // Generate Security Stamp. update.LockoutEnabled = true; update.SecurityStamp = Guid.NewGuid().ToString(); // Set Creations. foreach (var account in update.UserAccounts ?? new List <UserAccountEntityModel>()) { account.CreatedByUserGuid = User.UserGuid; } foreach (var shop in update.UserShops ?? new List <UserShopEntityModel>()) { shop.CreatedByUserGuid = User.UserGuid; } foreach (var group in update.UserGroups ?? new List <UserGroupEntityModel>()) { group.CreatedByUserGuid = User.UserGuid; } // Add Entity. Db.Users.Add(update); // Set Result. result = new UpdateResultDto(true, "User Created Successfully."); } else { // Verify Access to Edit. if ((!AllowedUsers?.Any(u => u.Id == user.UserGuid) ?? true) || !UserHasRoles(ApplicationRoles.UserEdit)) { // No Ability to Edit. user.UpdateResult = new UpdateResultDto(false, "You do not have access to modify this record."); return(user); } // Load User for Update. update = AllowedUsers.Include(x => x.EmployeeShops).Include(x => x.EmployeeAccounts).FirstOrDefault(u => u.Id == user.UserGuid); // Check User. if (update != null) { // Verify Employee Assignment. if (UserHasRoles(ApplicationRoles.AirProEmployeeAssign)) { if (update.EmployeeInd != user.EmployeeInd && !update.EmployeeShops.Any(x => x.ActiveInd) && !update.EmployeeAccounts.Any(x => x.ActiveInd)) { update.EmployeeInd = user.EmployeeInd; } } // Update User Info. if (update.FirstName != user.FirstName) { update.FirstName = user.FirstName; } if (update.LastName != user.LastName) { update.LastName = user.LastName; } if (update.JobTitle != user.JobTitle) { update.JobTitle = user.JobTitle; } if (update.ContactNumber != user.ContactNumber) { update.ContactNumber = user.ContactNumber; } if (update.TimeZoneInfoId != user.TimeZoneInfoId) { update.TimeZoneInfoId = user.TimeZoneInfoId; } // Check Password. if (user.PasswordHash != null && update.PasswordHash != user.PasswordHash) { update.PasswordHash = user.PasswordHash; update.SecurityStamp = Guid.NewGuid().ToString(); } // Check Email. if (user.Email != update.Email) { // Update Email. update.Email = user.Email; update.UserName = user.Email; update.EmailConfirmed = false; } // Check Phone. if (user.PhoneNumber != update.PhoneNumber) { // Update Phone. update.PhoneNumber = user.PhoneNumber; update.PhoneNumberConfirmed = false; } // Lock/Unlock Account. update.LockoutEndDateUtc = user.AccountLocked ? DateTime.MaxValue : new DateTime?(); // Reset Two-Factor. if (!update.EmailConfirmed && !update.PhoneNumberConfirmed) { update.TwoFactorEnabled = false; } else { update.TwoFactorEnabled = user.TwoFactorEnabled; } // Update Notifications. if (update.ShopReportNotification != user.ShopReportNotification) { update.ShopReportNotification = user.ShopReportNotification; } if (update.ShopBillingNotification != user.ShopBillingNotification) { update.ShopBillingNotification = user.ShopBillingNotification; } if (update.ShopStatementNotification != user.ShopStatementNotification) { update.ShopStatementNotification = user.ShopStatementNotification; } // Set Updated. update.UpdatedByUserGuid = User.UserGuid; update.UpdatedDt = DateTimeOffset.UtcNow; // Parse Accounts for Updates/Deletes. foreach (var account in update.UserAccounts.ToList()) { // Update Existing Records. if (user.AccountMemberships?.Contains(account.AccountGuid) ?? false) { account.UpdatedByUserGuid = User.UserGuid; account.UpdatedDt = DateTimeOffset.UtcNow; } else if (allowedAccounts.Contains(account.AccountGuid))// Delete Existing Record. { Db.UserAccounts.Remove(account); } } // Parse Accounts for Add. if (user.AccountMemberships != null) { var accounts = update.UserAccounts.Select(a => a.AccountGuid).ToList(); foreach (var account in user.AccountMemberships.Where(a => !accounts.Contains(a))) { // Add New Account. var add = new UserAccountEntityModel() { User = update, AccountGuid = account, CreatedByUserGuid = User.UserGuid }; update.UserAccounts.Add(add); } } // Parse Shops for Updates/Deletes. foreach (var shop in update.UserShops.ToList()) { // Update Existing Records. if (user.ShopMemberships?.Contains(shop.ShopGuid) ?? false) { shop.UpdatedByUserGuid = User.UserGuid; shop.UpdatedDt = DateTimeOffset.UtcNow; } else if (allowedShops.Contains(shop.ShopGuid))// Delete Existing Record. { Db.UserShops.Remove(shop); } } // Parse Shops for Add. if (user.ShopMemberships != null) { var shops = update.UserShops.Select(s => s.ShopGuid).ToList(); foreach (var shop in user.ShopMemberships.Where(s => !shops.Contains(s))) { // Add New Shop. var add = new UserShopEntityModel() { User = update, ShopGuid = shop, CreatedByUserGuid = User.UserGuid }; update.UserShops.Add(add); } } // Parse Groups for Updates/Deletes. foreach (var group in update.UserGroups.ToList()) { // Update Existing Records. if (user.GroupMemberships?.Contains(group.GroupGuid) ?? false) { group.UpdatedByUserGuid = User.UserGuid; group.UpdatedDt = DateTimeOffset.UtcNow; } else if (allowedGroups.Contains(group.GroupGuid))// Delete Existing Record. { Db.UserGroups.Remove(group); } } // Parse Groups for Add. if (user.GroupMemberships != null) { var groups = update.UserGroups.Select(g => g.GroupGuid).ToList(); foreach (var group in user.GroupMemberships.Where(g => !groups.Contains(g))) { // Add New Group. var add = new UserGroupEntityModel() { User = update, GroupGuid = group, CreatedByUserGuid = User.UserGuid }; update.UserGroups.Add(add); } } // Set Result. result = new UpdateResultDto(true, "User Updated Successfully."); } } // Save Changes. Db.SaveChanges(); // Update User Roles. Db.Database.ExecuteSqlCommand("Access.usp_UserGroupRoleSync"); // Load Account Record. Db.Entry(update).Reload(); // Load User. user = Mapper.Map <UserDto>(update); // Set Result. user.UpdateResult = result; return(user); }
public IAirProToolDto Save(IAirProToolDto tool) { AirProToolEntityModel toolEntity; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Check for New Tool. if (!tool.ToolId.HasValue) { // Verify Access for Add. if (!UserHasRoles(ApplicationRoles.InventoryDeviceCreate)) { // No Ability to Add. tool.UpdateResult = new UpdateResultDto(false, "You do not have access to create a record."); return(tool); } // Get Entity. toolEntity = Mapper.Map <AirProToolEntityModel>(tool); // Generate Tool Key. toolEntity.ToolKey = Guid.NewGuid(); // Get Memberships. var toolAccounts = tool.AccountAssignments.Select(a => new AirProToolAccountEntityModel { Tool = toolEntity, AccountGuid = a, CreatedByUserGuid = User.UserGuid }); var toolShops = tool.ShopAssignments.Select(s => new AirProToolShopEntityModel { Tool = toolEntity, ShopGuid = s.Key, CreatedByUserGuid = User.UserGuid }); // Set Creation. toolEntity.CreatedByUserGuid = User.UserGuid; toolEntity.CreatedDt = DateTimeOffset.UtcNow; // Add Entities. Db.AirProTools.Add(toolEntity); Db.AirProToolAccounts.AddRange(toolAccounts); Db.AirProToolShops.AddRange(toolShops); // Create Result. result = new UpdateResultDto(true, "Tool Created Successfully."); } else { var canDeviceEdit = UserHasRoles(ApplicationRoles.InventoryDeviceEdit); var canAssignmentEdit = UserHasRoles(ApplicationRoles.InventoryAssignmentEdit); var canDepositEdit = UserHasRoles(ApplicationRoles.InventoryDepositEdit); var canSubscriptionEdit = UserHasRoles(ApplicationRoles.InventorySubscriptionEdit); // Verify Access to Edit. if (!canDeviceEdit && !canAssignmentEdit && !canSubscriptionEdit && !canDepositEdit) { // No Ability to Edit. tool.UpdateResult = new UpdateResultDto(false, "You do not have access to modify this record."); return(tool); } // Load Tool for Update. toolEntity = Db.AirProTools.FirstOrDefault(t => t.ToolId == tool.ToolId); // Check Tool. if (toolEntity != null) { if (canDeviceEdit) { // Update Tool Fields. toolEntity.ToolPassword = tool.ToolPassword; toolEntity.SelfScanEnabledInd = tool.SelfScanEnabledInd; toolEntity.Type = tool.Type; toolEntity.AutoEnginuityNum = tool.AutoEnginuityNum; toolEntity.AutoEnginuityVersion = tool.AutoEnginuityVersion; toolEntity.CarDaqNum = tool.CarDaqNum; toolEntity.DGNum = tool.DGNum; toolEntity.TeamViewerId = tool.TeamViewerId; toolEntity.TeamViewerPassword = tool.TeamViewerPassword; toolEntity.WindowsVersion = tool.WindowsVersion; toolEntity.TabletModel = tool.TabletModel; toolEntity.HubModel = tool.HubModel; toolEntity.IPV6DisabledInd = tool.IPV6DisabledInd; toolEntity.OneDriveSyncEnabledInd = tool.OneDriveSyncEnabledInd; toolEntity.UpdatesServiceInd = tool.UpdatesServiceInd; toolEntity.MeteredConnectionInd = tool.MeteredConnectionInd; toolEntity.OBD2YConnector = tool.OBD2YConnector; toolEntity.AELatestCode = tool.AELatestCode; toolEntity.ChargerStyle = tool.ChargerStyle; toolEntity.TabletSerialNumber = tool.TabletSerialNumber; toolEntity.WifiCard = tool.WifiCard; toolEntity.WifiHardwareId = tool.WifiHardwareId; toolEntity.WifiDriverDate = tool.WifiDriverDate; toolEntity.WifiDriverVersion = tool.WifiDriverVersion; toolEntity.WifiMacAddress = tool.WifiMacAddress; toolEntity.ImageVersion = tool.ImageVersion; toolEntity.CellularActiveInd = tool.CellularActiveInd; toolEntity.CellularProvider = tool.CellularProvider; toolEntity.CellularIMEI = tool.CellularIMEI; toolEntity.J2534Brand = tool.J2534Brand; toolEntity.J2534Model = tool.J2534Model; toolEntity.J2534Serial = tool.J2534Serial; } if (canSubscriptionEdit) { toolEntity.HondaVersion = tool.HondaVersion; toolEntity.FJDSVersion = tool.FJDSVersion; toolEntity.TechstreamVersion = tool.TechstreamVersion; SetSubscription(tool, toolEntity); } if (canDepositEdit) { SetDeposits(tool, toolEntity); } // Set Update. toolEntity.UpdatedByUserGuid = User.UserGuid; toolEntity.UpdatedDt = DateTimeOffset.UtcNow; Db.Entry(toolEntity).State = EntityState.Modified; if (canAssignmentEdit) { SetShopsAndUpdate(tool, toolEntity); SetAccountsAndUpdate(tool, toolEntity); } // Create Result. result = new UpdateResultDto(true, "Tool Updated Successfully."); } } // Save. Db.SaveChanges(); // Set Update Results. tool.UpdateResult = result; return(tool); }
public IShopDto Save(IShopDto shop) { try { IShopDto update; UpdateResultDto result = new UpdateResultDto(false, "Unknown Error Occured."); // Verify CCC Shop Id. if (!string.IsNullOrEmpty(shop.CCCShopId)) { if (Db.Shops?.Any(s => s.CCCShopId == shop.CCCShopId && (shop.ShopGuid == Guid.Empty || shop.ShopGuid != s.ShopGuid)) ?? false) { // Duplicate CCC Shop Id. shop.UpdateResult = new UpdateResultDto(false, "CCC Shop ID already Exists for another Shop."); return(shop); } } // Limit Discount Percentage. if (shop.DiscountPercentage > 100) { shop.DiscountPercentage = 100; } // Check for New Shop. if (shop.ShopGuid == Guid.Empty) { // Verify Access for Add. var accountService = new AccountService(Settings); if (!UserHasRoles(ApplicationRoles.ShopCreate) || !accountService.AllowedAccounts.Any(a => a.AccountGuid == shop.AccountGuid)) { // No Ability to Add to Account. shop.UpdateResult = new UpdateResultDto(false, "You do not have access to create a record."); return(shop); } // Set Update. update = shop; // Set Result. result = new UpdateResultDto(true, "Shop Created Successfully."); } else { // Verify Access to Edit. if (!UserHasRoles(ApplicationRoles.ShopEdit) || (!AllowedShops?.Any(s => s.ShopGuid == shop.ShopGuid) ?? true)) { // No Ability to Edit. shop.UpdateResult = new UpdateResultDto(false, "You do not have access to modify this record."); return(shop); } // Load Shop for Update. update = GetById(shop.ShopGuid.ToString()); // Check Shop. if (update != null) { var activeIndCache = update.ActiveInd; var estimatePlanIdCache = update.EstimatePlanId; var discountPercentageCache = update.DiscountPercentage; var pricingPlanIdCache = update.PricingPlanId; // Set Update. update = shop; // Check Active. if (!shop.ActiveInd) { update.ActiveInd = activeIndCache; } // Check Estimate Plan Permission. if (!UserHasRoles(ApplicationRoles.EstimatePlanView)) { update.EstimatePlanId = estimatePlanIdCache; } // Check Payment Create Permission. if (!UserHasRoles(ApplicationRoles.PaymentCreate)) { update.DiscountPercentage = discountPercentageCache; update.PricingPlanId = pricingPlanIdCache; } // Set Result. result = new UpdateResultDto(true, "Shop Updated Successfully."); } } // Load Insurance Company Pricing Plans. var insuranceCompaniesPricingPlans = new DataTable(); insuranceCompaniesPricingPlans.Columns.Add("ShopGuid", typeof(Guid)); insuranceCompaniesPricingPlans.Columns.Add("InsuranceCompanyId", typeof(int)); insuranceCompaniesPricingPlans.Columns.Add("PricingPlanId", typeof(int)); foreach (var item in update?.ShopInsuranceCompanyPricingPlans ?? new List <IShopInsuranceCompanyPlanDto>()) { insuranceCompaniesPricingPlans.Rows.Add(item.ShopGuid, item.InsuranceCompanyId, item.PlanId); } // Load Insurance Company Estimate Plans. var insuranceCompaniesEstimatePlans = new DataTable(); insuranceCompaniesEstimatePlans.Columns.Add("ShopGuid", typeof(Guid)); insuranceCompaniesEstimatePlans.Columns.Add("InsuranceCompanyId", typeof(int)); insuranceCompaniesEstimatePlans.Columns.Add("EstimatePlanId", typeof(int)); foreach (var item in update?.ShopInsuranceCompanyEstimatePlans ?? new List <IShopInsuranceCompanyPlanDto>()) { insuranceCompaniesEstimatePlans.Rows.Add(item.ShopGuid, item.InsuranceCompanyId, item.PlanId); } // Load Vehicle Make Pricing Plans. var vehicleMakesPricingPlans = new DataTable(); vehicleMakesPricingPlans.Columns.Add("ShopGuid", typeof(Guid)); vehicleMakesPricingPlans.Columns.Add("VehicleMakeId", typeof(int)); vehicleMakesPricingPlans.Columns.Add("PricingPlanId", typeof(int)); foreach (var item in update?.ShopVehicleMakesPricingPlans ?? new List <IShopVehicleMakesPricingDto>()) { vehicleMakesPricingPlans.Rows.Add(item.ShopGuid, item.VehicleMakeId, item.PricingPlanId); } // Load Shop Contacts. var shopContacts = new DataTable(); shopContacts.Columns.Add("ShopContactGuid", typeof(Guid)); shopContacts.Columns.Add("ShopGuid", typeof(Guid)); shopContacts.Columns.Add("FirstName", typeof(string)); shopContacts.Columns.Add("LastName", typeof(string)); shopContacts.Columns.Add("PhoneNumber", typeof(string)); foreach (var item in update?.ShopContacts.Where(x => !(string.IsNullOrWhiteSpace(x.FirstName) && string.IsNullOrWhiteSpace(x.LastName) && string.IsNullOrWhiteSpace(x.PhoneNumber))).ToList() ?? new List <IShopContactDto>()) { shopContacts.Rows.Add(item.ShopContactGuid, item.ShopGuid, item.FirstName, item.LastName, item.PhoneNumber); } // Create Parameter. var param = new DynamicParameters(new { update.Name, update.AccountGuid, update.Address1, update.Address2, update.City, update.State, update.Zip, update.Phone, update.Fax, update.Notes, update.CCCShopId, update.AverageVehiclesPerMonth, update.AllowAutoRepairClose, update.AllowScanAnalysis, update.AllowDemoScan, update.DefaultInsuranceCompanyId, update.AllowSelfScanAssessment, update.PricingPlanId, update.ShopFixedPriceInd, update.FirstScanCost, update.AdditionalScanCost, update.AutomaticRepairCloseDays, update.HideFromReports, update.CurrencyId, update.BillingCycleId, update.AllowScanAnalysisAutoClose, update.SendToMitchellInd, update.AllowAllRepairAutoClose, update.DisableShopStatementNotification, update.DisableShopBillingNotification, update.ActiveInd, update.EstimatePlanId, update.DiscountPercentage, update.AllowSelfScan, User.UserGuid, ShopContacts = shopContacts, ShopInsurancePlansPricingPlans = insuranceCompaniesPricingPlans.AsTableValuedParameter(), ShopInsurancePlansEstimatePlans = insuranceCompaniesEstimatePlans, ShopVehicleMakesPricing = vehicleMakesPricingPlans, InsuranceCompanyIds = JsonConvert.SerializeObject(update.ShopInsuranceCompanies?.Select(t => t).ToArray() ?? new int[] {}), VehicleMakeIds = JsonConvert.SerializeObject(update.ShopVehicleMakes?.Select(r => r).ToArray() ?? new int[] { }), RequestTypeIds = JsonConvert.SerializeObject(update.ShopRequestTypes?.Select(t => t).ToArray() ?? new int[] { }), update.EmployeeGuid, update.AutomaticInvoicesInd }); // Add Output Parameter. param.Add(nameof(update.ShopGuid), update.ShopGuid, DbType.Guid, ParameterDirection.InputOutput); // Execute Update. Conn.Execute("Access.usp_SaveShop", param, commandType: CommandType.StoredProcedure); var shopGuid = param.Get <Guid>(nameof(update.ShopGuid)); // Load Shop. shop = GetById(shopGuid.ToString()); // Set Update Result. shop.UpdateResult = result; } catch (Exception e) { // Log Exception. Logger.LogException(e); // Set Update Result. shop.UpdateResult = new UpdateResultDto(false, e.Message); } // Done. return(shop); }