public bool SubscriptionWithinTrafficLimit(ApplicationUser user, ApplicationDbContext DbContext) { if (CommonAccount.FreeTrialActive(user)) { return(true); } bool subscriptionWithinTrafficLimit = true; int promoClaimsThisMonth = FindClaimsForCurrentMonth(user); switch (user.SubscriptionPlan) { case SubscriptionOptions.FreeAccount: //0-25 Claims a month subscriptionWithinTrafficLimit = promoClaimsThisMonth <= SubscriptionOptions.MaxFreeAccountClaims; break; case SubscriptionOptions.Bronze: //Up to 500 Claims a month subscriptionWithinTrafficLimit = promoClaimsThisMonth <= SubscriptionOptions.MaxBronzeAccountClaims; break; case SubscriptionOptions.Silver: //Up to 2000 Claims a month subscriptionWithinTrafficLimit = promoClaimsThisMonth <= SubscriptionOptions.MaxSilverAccountClaims; break; case SubscriptionOptions.Gold: //Unlimited Claims a month subscriptionWithinTrafficLimit = true; break; } if (subscriptionWithinTrafficLimit && user.MonthlyPromotionLimitReached == true) { // Once a user upgrades a plan OR a new month starts, reset their promo limit flag user.MonthlyPromotionLimitReached = false; DbContext.SaveChanges(); } else if (subscriptionWithinTrafficLimit == false && user.MonthlyPromotionLimitReached == false) { // 1st traffic limit violation that has not been set in the DB should come in here... // This flag will be cleared after a new month or an upgrade of a plan user.MonthlyPromotionLimitReached = true; DbContext.SaveChanges(); } return(subscriptionWithinTrafficLimit); }
//Default account private void SeedDefaultAccount() { var masterUser = _context.Users.Where(m => m.Email == masterUserEmail).Single(); var masterCity = _context.Cities.Where(m => m.Name == "Sacramento").Single(); var masterPartition = _context.Partitions.Where(m => m.Name == PARTITION_01_NAME).Single(); var account = new CommonAccount { Name = "Master", OwnerUserId = masterUser.Id, CityId = masterCity.Id, Features = AccountFeatures.Info, Number = 50000, PartitionId = masterPartition.Id, State = "CA", }; //TODO: Finish creating the rest of this. Bassically everything in CommonAccountService.CreateAccount }
/// <summary> /// Update User CommonAccount Profile /// </summary> /// <param name="commonAccount"></param> /// <param name="createdById"></param> /// <returns></returns> public async Task <ServiceResponse <CommonAccount> > UpdateSettingAccount(CommonAccount commonAccount, Guid createdById) { var result = new ServiceResponse <CommonAccount>(); try { using (var scope = _commonCtx.Database.BeginTransaction()) { _commonCtx.CommonAccounts.Update(commonAccount); await _commonCtx.SaveChangesAsync(); //update CommonAccountSettings table var accountSettingDetail = await _commonCtx.CommonAccountSettings.SingleOrDefaultAsync(a => a.Id == commonAccount.Id); accountSettingDetail.UpdateUserId = createdById; accountSettingDetail.UpdateUtc = DateTime.UtcNow; _commonCtx.CommonAccountSettings.Update(accountSettingDetail); await _commonCtx.SaveChangesAsync(); //update accounts table from selected partition var accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString)); var AccountsDetail = await accountCtx.Accounts.SingleOrDefaultAsync(a => a.Id == commonAccount.Id); AccountsDetail.Name = commonAccount.Name; AccountsDetail.UpdateUserId = createdById; AccountsDetail.UpdateUtc = DateTime.UtcNow; accountCtx.Accounts.Update(AccountsDetail); await accountCtx.SaveChangesAsync(); scope.Commit(); } } catch (Exception ex) { _logger.Error(ex, "Error updating an Account"); throw ex; } return(result); }
public async Task <IActionResult> Create(AccountViewModel model) { if (ModelState.IsValid) { var account = new CommonAccount() { Name = model.Name.Trim(), CityId = model.CityId, PartitionId = model.PartitionId, Partition = await CommonContext.Partitions.SingleAsync(m => m.Id == model.PartitionId), StorageBucketName = model.StorageBucketName, CitationWorkflow = model.CitationWorkflow, Features = model.Features }; if (Convert.ToString(model.OwnerId) != "00000000-0000-0000-0000-000000000000") { account.OwnerUserId = model.OwnerId; } var NameAlreadyExists = await CommonContext.CommonAccounts.AnyAsync(q => q.Name.ToLower() == model.Name.Trim().ToLower()); if (NameAlreadyExists) { // This isn't a security risk because we've verified the Name already exists ModelState.AddModelError(string.Empty, "Name already exists."); } else { var result = await _commonAccountSvc.CreateAccount(account, User.GetLoggedInUserId().Value, model.AccViolationType, model.CitationCounter); //Purge common accounts cache await _cache.RemoveAsync(WebCacheKey.CommonAccounts); return(RedirectToAction("Index")); } } await PopulateDropDownAccount(model); return(View(model)); }
private async Task <AccountInfoViewModel> GetSampleAccountInfoViewModel(CommonAccount account, Guid?eventId) { var model = new AccountInfoViewModel() { Account = account }; var _accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(account.Partition.ConnectionString)); var events = _accountCtx.Events.ForAccount(account.Id).AsNoTracking(); if (eventId.HasValue) { events = events.Where(m => m.Id == eventId.Value); } model.Events = Mapper.Map <List <AccountEvent> >(await events.OrderByDescending(m => m.CreateUtc).ToListAsync()); return(model); }
public async Task <IActionResult> Edit(AccountViewModel model) { if (ModelState.IsValid) { if (Convert.ToString(model.OwnerId) != "00000000-0000-0000-0000-000000000000") { var account = new CommonAccount() { Name = model.Name.Trim(), Id = model.Id, PartitionId = model.PartitionId, OwnerUserId = model.OwnerId, StorageBucketName = model.StorageBucketName, CitationWorkflow = model.CitationWorkflow, Features = model.Features }; var NameAlreadyExists = await CommonContext.CommonAccounts.AnyAsync(q => q.Name.ToLower() == model.Name.Trim().ToLower() && q.Id != model.Id); if (NameAlreadyExists) { // This isn't a security risk because we've verified the Name already exists ModelState.AddModelError(string.Empty, "Name already exists."); } else { var result = await _commonAccountSvc.UpdateAccount(account, User.GetLoggedInUserId().Value, model.AccountNumber, model.AccViolationType); return(RedirectToAction("Index")); } } else { ModelState.AddModelError(string.Empty, "You must be select the owner."); } } await PopulateAllFields(model); return(View(model)); }
private String GetDashboardMessage(ApplicationUser user) { if (CommonAccount.FreeTrialActive(user)) { return(GetFreeTrialMessage(CommonAccount.DaysSinceAccountSignup(user.AccountCreationDate))); } String dashboardMessage = String.Empty; if (user.AccountSuspended) { dashboardMessage = "Account suspended, make a payment on your account here"; } else if (user.MonthlyPromotionLimitReached) { dashboardMessage = "Account promotion limit reached, upgrade account here"; } else { dashboardMessage = "You rock, view account here"; } return(dashboardMessage); }
/// <summary> /// Create Charge with customer /// </summary> /// <param name="creditCard"></param> /// <returns></returns> public async Task <StripeCharge> ChargeCardAsync(CreditCardModel creditCard, Citation citation, CommonAccount account, ChargeTypeEnum chargeType) { Check.NotNull(creditCard, nameof(creditCard)); var metaData = new Dictionary <string, string>(); metaData["Account"] = account.Name; metaData["AccountNumber"] = account.Number.ToString(); metaData["CitationNumber"] = citation.CitationNumber.ToString(); metaData["Type"] = chargeType.GetDescription(); // Token is created using Checkout or Elements! // Get the payment token submitted by the form: var token = creditCard.SourceToken; // Using ASP.NET MVC var options = new StripeChargeCreateOptions { Amount = creditCard.Amount, Currency = "usd", Description = chargeType.GetDescription(), SourceTokenOrExistingSourceId = token, Metadata = metaData }; var service = new StripeChargeService(); StripeCharge charge = await service.CreateAsync(options); return(charge); }
/// <summary> /// populate all violations in the account context for selected partition. /// </summary> public async Task PopulateViolationsForAccount(CommonAccount commonAccount, Guid createdById) { var AllViolationType = await _commonCtx.CommonViolationTypes.AsNoTracking().Where(m => m.Disabled == false).ToListAsync(); var AllViolationCategory = await _commonCtx.CommonViolationCategories.AsNoTracking().Where(m => m.Disabled == false).ToListAsync(); var AllViolation = await _commonCtx.CommonViolations.AsNoTracking().Where(m => m.Disabled == false).ToListAsync(); //Go through each account and add this CommonViolation to Violation foreach (var violationType in AllViolationType) { using (var accountContext = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString))) { var created = DateTime.UtcNow; var violationTypes = Mapper.Map <ViolationType>(violationType); violationTypes.AccountId = commonAccount.Id; violationTypes.CreateUtc = created; //Setting created and UpdatedUtc to the exact same value will let us know if this record has every been changed. violationTypes.UpdateUtc = created; violationTypes.CommonViolationTypeId = violationType.Id; accountContext.ViolationTypes.Add(violationTypes); await accountContext.SaveChangesAsync(); await PurgeAccountViolation(commonAccount.Id); } } // add entries in violation category in the account context for this account foreach (var ViolationCategory in AllViolationCategory) { using (var accountContext = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString))) { var created = DateTime.UtcNow; var accountViolationType = await accountContext.ViolationTypes.AsNoTracking().Where(m => m.AccountId == commonAccount.Id && m.CommonViolationTypeId == ViolationCategory.TypeId).SingleOrDefaultAsync(); if (accountViolationType != null) { var violationCategory = Mapper.Map <ViolationCategory>(ViolationCategory); violationCategory.TypeId = accountViolationType.Id; violationCategory.AccountId = commonAccount.Id; violationCategory.CreateUtc = created; //Setting created and UpdatedUtc to the exact same value will let us know if this record has every been changed. violationCategory.UpdateUtc = created; violationCategory.CommonCategoryId = ViolationCategory.Id; accountContext.ViolationCategorys.Add(violationCategory); await accountContext.SaveChangesAsync(); await PurgeAccountViolation(commonAccount.Id); } } } // add entries in violations in the account context for this account foreach (var Violation in AllViolation) { using (var accountContext = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString))) { var created = DateTime.UtcNow; var accountViolationCategory = await accountContext.ViolationCategorys.AsNoTracking().Where(m => m.AccountId == commonAccount.Id && m.CommonCategoryId == Violation.CategoryId).SingleOrDefaultAsync(); if (accountViolationCategory != null) { var violation = Mapper.Map <Violation>(Violation); violation.CategoryId = accountViolationCategory.Id; violation.AccountId = commonAccount.Id; violation.CreateUtc = created; //Setting created and UpdatedUtc to the exact same value will let us know if this record has every been changed. violation.UpdateUtc = created; violation.CommonViolationId = Violation.Id; violation.CustomActions = Violation.Actions; violation.CustomRequiredFields = Violation.RequiredFields; accountContext.Violations.Add(violation); await accountContext.SaveChangesAsync(); await PurgeAccountViolation(commonAccount.Id); } } } }
/// <summary> /// Update an existing Account in the Common and Account partitions. /// Also update a user in the Account Partition. /// </summary> /// <param name="commonAccount"></param> /// <param name="createdById"></param> /// <returns></returns> public async Task <ServiceResponse <CommonAccount> > UpdateAccount(CommonAccount commonAccount, Guid createdById, int AccountNumber, List <AccountViolationType> AccViolationType) { var result = new ServiceResponse <CommonAccount>(); try { using (var scope = _commonCtx.Database.BeginTransaction()) { //update common account table var accountDetail = await _commonCtx.CommonAccounts.Include(m => m.Partition).Include(m => m.Settings).SingleOrDefaultAsync(a => a.Id == commonAccount.Id); var accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(accountDetail.Partition.ConnectionString)); accountDetail.UpdateUserId = createdById; accountDetail.UpdateUtc = DateTime.Now; accountDetail.Name = commonAccount.Name; accountDetail.OwnerUserId = commonAccount.OwnerUserId; accountDetail.StorageBucketName = commonAccount.StorageBucketName; accountDetail.CitationWorkflow = commonAccount.CitationWorkflow; accountDetail.Features = commonAccount.Features; _commonCtx.CommonAccounts.Update(accountDetail); await _commonCtx.SaveChangesAsync(); //update accounts table from selected partition var AccountsDetail = await accountCtx.Accounts.SingleOrDefaultAsync(a => a.Id == commonAccount.Id); AccountsDetail.Name = commonAccount.Name; AccountsDetail.UpdateUserId = createdById; AccountsDetail.UpdateUtc = DateTime.UtcNow; accountCtx.Accounts.Update(AccountsDetail); await accountCtx.SaveChangesAsync(); //update user accounts table if (commonAccount.OwnerUserId != null) { //Check to see if the owner exists in the User Account Table. var userAccount = await _commonCtx.UserAccounts.SingleOrDefaultAsync(a => a.AccountId == commonAccount.Id && a.UserId == commonAccount.OwnerUserId); if (userAccount == null) { CommonUserAccount NewuserAccount = new CommonUserAccount(); NewuserAccount.CreateUserId = createdById; NewuserAccount.AccountId = commonAccount.Id; NewuserAccount.UpdateUserId = createdById; NewuserAccount.UserId = commonAccount.OwnerUserId; NewuserAccount.Permissions = (AccountPermissions)Enum.GetValues(typeof(AccountPermissions)).Cast <int>().Sum(); _commonCtx.UserAccounts.Add(NewuserAccount); await _commonCtx.SaveChangesAsync(); var commonUser = await _commonCtx.Users.SingleAsync(m => m.Id == commonAccount.OwnerUserId); //Add any new users to acconts await SaveAccountUser(commonUser, createdById); } } //Remove the current violation types var AccountViolationType = await _commonCtx.CommonAccountViolationTypes.Where(av => av.AccountId == commonAccount.Id).ToListAsync(); _commonCtx.CommonAccountViolationTypes.RemoveRange(AccountViolationType); await _commonCtx.SaveChangesAsync(); //Add new violatoin types from the page foreach (var Types in AccViolationType) { if (Types.IsCheckedViolation == true) { CommonAccountViolationType AcntViolationType = new CommonAccountViolationType(); AcntViolationType.CreateUserId = createdById; AcntViolationType.AccountId = commonAccount.Id; AcntViolationType.UpdateUserId = createdById; AcntViolationType.ViolationTypeId = Types.TypeId; _commonCtx.CommonAccountViolationTypes.Add(AcntViolationType); await _commonCtx.SaveChangesAsync(); } } scope.Commit(); //Purge common accounts cache var cacheKey = WebCacheKey.CommonAccount(accountDetail.Number); await _cache.RemoveAsync(cacheKey); } } catch (Exception ex) { _logger.Error(ex, "Error updating an Account"); throw ex; } return(result); }
/// <summary> /// Creates a new Account in the Common and Account partitions. /// Also creates a user in the Account Partition if one doesn't exist. /// </summary> /// <param name="commonAccount"></param> /// <param name="user"></param> /// <param name="createdById"></param> /// <returns></returns> public async Task <ServiceResponse <CommonAccount> > CreateAccount(CommonAccount commonAccount, Guid createdById, List <AccountViolationType> AccViolationType, long CitationCounter) { var result = new ServiceResponse <CommonAccount>(); try { using (var scope = _commonCtx.Database.BeginTransaction()) { //Get the correct account database based on the partition that was chosen for the account. var accountCtx = ContextsUtility.CreateAccountContext(Cryptography.Decrypt(commonAccount.Partition.ConnectionString)); if (accountCtx == null) { _logger.Error($"Account context does not exists for partition: {Cryptography.Decrypt(commonAccount.Partition.ConnectionString)}"); throw new Exception("Account context does not exists"); } //Generate a random account number commonAccount.Number = await GetNextAccountNumberAsync(); commonAccount.CreateUserId = createdById; commonAccount.UpdateUserId = createdById; //Create empty account settings commonAccount.Settings = new CommonAccountSettings { }; commonAccount.Settings.CreateUserId = createdById; commonAccount.Settings.UpdateUserId = createdById; _commonCtx.CommonAccounts.Add(commonAccount); await _commonCtx.SaveChangesAsync(); //Update the count on the partition to let us know how many account reside on one database. commonAccount.Partition.Occupancy = commonAccount.Partition.Occupancy + 1; _commonCtx.Partitions.Update(commonAccount.Partition); //If a Owner is selected, create a user account assosication. if (commonAccount.OwnerUserId != null) { CommonUserAccount userAccount = new CommonUserAccount(); userAccount.CreateUserId = createdById; userAccount.AccountId = commonAccount.Id; userAccount.UpdateUserId = createdById; userAccount.UserId = commonAccount.OwnerUserId; userAccount.Permissions = (AccountPermissions)Enum.GetValues(typeof(AccountPermissions)).Cast <int>().Sum(); _commonCtx.UserAccounts.Add(userAccount); await _commonCtx.SaveChangesAsync(); var commonUser = await _commonCtx.Users.SingleAsync(m => m.Id == commonAccount.OwnerUserId); //Add any new users to acconts await SaveAccountUser(commonUser, createdById); } //Add Account in account context //The Ids for the Account in AccountContext and CommonAccount in CommonContext are going to be exactly the same. accountCtx.Accounts.Add(new Account { Id = commonAccount.Id, Name = commonAccount.Name, CreateUserId = createdById, UpdateUserId = createdById }); await accountCtx.SaveChangesAsync(); foreach (var Type in AccViolationType) { if (Type.IsCheckedViolation == true) { CommonAccountViolationType AccountViolationType = new CommonAccountViolationType(); AccountViolationType.CreateUserId = createdById; AccountViolationType.AccountId = commonAccount.Id; AccountViolationType.UpdateUserId = createdById; AccountViolationType.ViolationTypeId = Type.TypeId; _commonCtx.CommonAccountViolationTypes.Add(AccountViolationType); } } await _commonCtx.SaveChangesAsync(); await _violationSvc.PopulateViolationsForAccount(commonAccount, createdById); Counter count = new Counter() { AccountId = commonAccount.Id, Name = "Citations", NextValue = CitationCounter, CreateUserId = commonAccount.OwnerUserId.Value, UpdateUserId = commonAccount.OwnerUserId.Value }; accountCtx.Counters.Add(count); await accountCtx.SaveChangesAsync(); scope.Commit(); } } catch (Exception ex) { _logger.Error(ex, "Error creating new Account"); throw ex; } return(result); }