/// <summary> /// To be called by the daily agent /// </summary> public static void UpdateCompanyExpirations(DateTime dateToConsider, StageBitzDB dataContext) { FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); ProjectBL projectBL = new ProjectBL(dataContext); #region SuspendPaymentFailureCompanies int companyGracePeriodStatus = Utils.GetCodeIdByCodeValue("CompanyStatus", "GRACEPERIOD"); int companyPaymentFailedStatus = Utils.GetCodeIdByCodeValue("CompanyStatus", "SUSPENDEDFORPAYMENTFAILED"); int companyActiveStatus = Utils.GetCodeIdByCodeValue("CompanyStatus", "ACTIVE"); int suspendedForNoPaymentPackageStatus = Utils.GetCodeIdByCodeValue("CompanyStatus", "SUSPENDEDFORNOPAYMENTPACKAGE"); int suspendForNoPaymentOptions = Utils.GetCodeIdByCodeValue("CompanyStatus", "SUSPENDEDFORNOPAYMENTOPTIONS"); var companies = from c in dataContext.Companies where (c.CompanyStatusCodeId == companyGracePeriodStatus || c.CompanyStatusCodeId == companyActiveStatus) && c.ExpirationDate != null && dateToConsider >= c.ExpirationDate select c; foreach (Data.Company company in companies) { if (company.CompanyStatusCodeId == companyActiveStatus) { //Get the current Company package to check. CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(company.CompanyId, dateToConsider); DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider, company.CompanyId); // suspend payment package not setup companies after free trial. if (companyPaymentPackage == null) { company.CompanyStatusCodeId = suspendedForNoPaymentPackageStatus; } else { decimal totalAmount = financeBL.CalculateALLPackageAmountsByPeriod(companyPaymentPackage.ProjectPaymentPackageTypeId, companyPaymentPackage.InventoryPaymentPackageTypeId, companyPaymentPackage.PaymentDurationCodeId); //Check if it is a Free package. if (!companyPaymentPackage.PaymentMethodCodeId.HasValue && ((discountCodeUsage != null && discountCodeUsage.DiscountCode.Discount != 100) || (discountCodeUsage == null && totalAmount != 0))) { company.CompanyStatusCodeId = suspendForNoPaymentOptions; SuspendProjectsForCompany(company.CompanyId, dataContext); } } } //For Grace period companies, if it exceeded the grace period change it to Payment Failed. else if (companyBL.IsCompanyInPaymentFailedGracePeriod(company.CompanyId)) { company.CompanyStatusCodeId = companyPaymentFailedStatus; company.LastUpdatedByUserId = 0; company.LastUpdatedDate = Utils.Now; } company.ExpirationDate = null; } #endregion }
/// <summary> /// Updates the pricing plan and payment summary when closing free trial. /// </summary> /// <param name="companyId">The company identifier.</param> /// <param name="userId">The user identifier.</param> /// <param name="dataContext">The data context.</param> public static void UpdatePricingPlanAndPaymentSummaryClosingFreeTrial(int companyId, int userId, StageBitzDB dataContext) { //if this is the last free trial project which is going to be closed we should end the free trial also take the start date of the selected package to Today //usually a company will have one free trial project, but when clearing finance a company can have more free trial projects, //so closing one free trial project doesn't end the free trial of that company. ProjectBL projectBL = new ProjectBL(dataContext); FinanceBL financeBL = new FinanceBL(dataContext); if (projectBL.GetFreeTrialProjectsNotInClosedStatus(companyId, Utils.Today).Count() == 1) { CompanyPaymentPackage currentPricingPlan = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(companyId); if (currentPricingPlan != null) { currentPricingPlan.StartDate = Utils.Today; } DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(Utils.Today, companyId); UpdatePaymentSummaryForFreeTrialCompany(companyId, discountCodeUsage, null, userId, dataContext); dataContext.SaveChanges(); } }
/// <summary> /// Gets the payment package summaries. /// </summary> /// <param name="paymentSummaryDetail">The payment summary detail.</param> /// <param name="dateToConsider">The date to consider.</param> /// <param name="dataContext">The data context.</param> /// <returns></returns> public static List <CompanyPaymentSummary> GetPaymentPackageSummaries(PaymentSummaryDetails paymentSummaryDetail, DateTime dateToConsider, StageBitzDB dataContext) { int anualDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL"); int invoiceMethodCodeId = Utils.GetCodeIdByCodeValue("PaymentMethod", "INVOICE"); List <CompanyPaymentSummary> summaryList = new List <CompanyPaymentSummary>(); DateTime nextCycleStartDate = Utils.Today; decimal totalDue = 0; decimal educationalDiscount = decimal.Parse(Utils.GetSystemValue("EducationalDiscount")); FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); CompanyPaymentSummary existingCompanyPackageSummary = dataContext.CompanyPaymentSummaries.Where(cps => cps.CompanyId == paymentSummaryDetail.CompanyId).OrderByDescending(cps => cps.CompanyPaymentSummaryId).FirstOrDefault(); CompanyPaymentPackage currentCompanyPaymentPackage = financeBL.GetPaymentPackageForCompanyByDay(dateToConsider, paymentSummaryDetail.CompanyId); if (existingCompanyPackageSummary != null && companyBL.IsFreeTrialCompany(paymentSummaryDetail.CompanyId)) //check whether there is an upgrade/downgrade during the freetrial { existingCompanyPackageSummary = null; } if (existingCompanyPackageSummary == null || currentCompanyPaymentPackage == null) { //This is for the very first time from UI. So return the amount based on promotional and educational discount amount. totalDue = financeBL.CalculateALLPackageAmountsByPeriod(paymentSummaryDetail.ProjectPaymentPackageTypeId, paymentSummaryDetail.InventoryPaymentPackageTypeId, paymentSummaryDetail.PaymentDurationTypeCodeId); if (paymentSummaryDetail.IsEducationPackage) { totalDue = totalDue * (100 - educationalDiscount) / 100; } else if (paymentSummaryDetail.DiscountCodeUsageToApply != null) { DateTime endDate = paymentSummaryDetail.PaymentDurationTypeCodeId == anualDurationCodeId?paymentSummaryDetail.PackageStartDate.AddYears(1) : paymentSummaryDetail.PackageStartDate.AddMonths(1); totalDue = financeBL.GetDiscountedAmount(paymentSummaryDetail.CompanyId, totalDue, paymentSummaryDetail.PaymentDurationTypeCodeId, paymentSummaryDetail.DiscountCodeUsageToApply, paymentSummaryDetail.PackageStartDate, endDate); } nextCycleStartDate = paymentSummaryDetail.PaymentDurationTypeCodeId == anualDurationCodeId?paymentSummaryDetail.PackageStartDate.AddYears(1) : paymentSummaryDetail.PackageStartDate.AddMonths(1); summaryList.Add(CreateCompanyPaymentSummary(totalDue, nextCycleStartDate, paymentSummaryDetail, paymentSummaryDetail.DiscountCodeUsageToApply, paymentSummaryDetail.PackageStartDate, nextCycleStartDate, (paymentSummaryDetail.PaymentMethodCodeId != null && paymentSummaryDetail.PaymentMethodCodeId == invoiceMethodCodeId), paymentSummaryDetail.PaymentMethodCodeId, paymentSummaryDetail.CompanyPaymentPackage)); } else { //This happens when a user upgrades or daily agent makes repeat payments at the end of the Payment Cycle. DateTime endDate = existingCompanyPackageSummary.NextPaymentCycleStartingDate; int dateDifference = 0; InventoryPaymentPackageDetails currentInventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(currentCompanyPaymentPackage.InventoryPaymentPackageTypeId); InventoryPaymentPackageDetails newInventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(paymentSummaryDetail.InventoryPaymentPackageTypeId); ProjectPaymentPackageDetails currentProjectPaymentPackageDetails = Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(currentCompanyPaymentPackage.ProjectPaymentPackageTypeId); ProjectPaymentPackageDetails newProjectPaymentPackageDetails = Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(paymentSummaryDetail.ProjectPaymentPackageTypeId); decimal currentTotalAmount, newTotalAmount; //Just Get the Amounts from tables if (currentCompanyPaymentPackage.PaymentDurationCodeId == anualDurationCodeId) { currentTotalAmount = currentInventoryPaymentPackageDetails.AnualAmount + currentProjectPaymentPackageDetails.AnualAmount; newTotalAmount = newInventoryPaymentPackageDetails.AnualAmount + newProjectPaymentPackageDetails.AnualAmount; } else { currentTotalAmount = currentInventoryPaymentPackageDetails.Amount + currentProjectPaymentPackageDetails.Amount; newTotalAmount = newInventoryPaymentPackageDetails.Amount + newProjectPaymentPackageDetails.Amount; } if (dateToConsider < endDate && paymentSummaryDetail.HasPackageChanged) //this happens only when a user upgrades during the payment cycle { dateDifference = (int)(endDate - dateToConsider).TotalDays; totalDue = GetProrataAmount(paymentSummaryDetail, currentCompanyPaymentPackage, existingCompanyPackageSummary.DiscountCodeUsage, newTotalAmount, currentTotalAmount, endDate, dateDifference); summaryList.Add(CreateCompanyPaymentSummary(totalDue, endDate, paymentSummaryDetail, paymentSummaryDetail.DiscountCodeUsageToApply, dateToConsider, endDate, (paymentSummaryDetail.PaymentMethodCodeId != null && paymentSummaryDetail.PaymentMethodCodeId == invoiceMethodCodeId), paymentSummaryDetail.PaymentMethodCodeId, paymentSummaryDetail.CompanyPaymentPackage)); } else { //this get executed by a user when changing the package during Agent down or on package virtual end date or during a gap filling execution // currentCompanyPaymentPackage will always be the existing package. DateTime startDate, tempNextCycleDate = endDate; while (tempNextCycleDate <= dateToConsider) { if (tempNextCycleDate == dateToConsider && paymentSummaryDetail.IsUserAction) { break; } //Find the next Package Start Date based on the duration startDate = tempNextCycleDate; tempNextCycleDate = currentCompanyPaymentPackage.PaymentDurationCodeId == anualDurationCodeId?tempNextCycleDate.AddYears(1) : tempNextCycleDate.AddMonths(1); decimal recordTotalAmount = currentTotalAmount; DiscountCodeUsage discountCodeUsage = null; //Get the relavent education or Discount if (currentCompanyPaymentPackage.IsEducationalPackage) { recordTotalAmount = recordTotalAmount * (100 - educationalDiscount) / 100; } else { //Get the DiscountCode Usage for the Day discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(startDate, currentCompanyPaymentPackage.CompanyId); if (discountCodeUsage != null) { recordTotalAmount = financeBL.GetDiscountedAmount(currentCompanyPaymentPackage.CompanyId, recordTotalAmount, currentCompanyPaymentPackage.PaymentDurationCodeId, discountCodeUsage, startDate, tempNextCycleDate); } } if (paymentSummaryDetail.PaymentMethodCodeId != null) { //this will set is monthly agent processed to true for the past records when gap filling if the user has selected the invoice option. summaryList.Add(CreateCompanyPaymentSummary(recordTotalAmount, tempNextCycleDate, paymentSummaryDetail, discountCodeUsage, startDate, tempNextCycleDate, (paymentSummaryDetail.PaymentMethodCodeId == invoiceMethodCodeId), paymentSummaryDetail.PaymentMethodCodeId, currentCompanyPaymentPackage)); } else { summaryList.Add(CreateCompanyPaymentSummary(recordTotalAmount, tempNextCycleDate, paymentSummaryDetail, discountCodeUsage, startDate, tempNextCycleDate, (currentCompanyPaymentPackage.PaymentMethodCodeId != null && currentCompanyPaymentPackage.PaymentMethodCodeId == invoiceMethodCodeId), currentCompanyPaymentPackage.PaymentMethodCodeId, currentCompanyPaymentPackage)); } } if (tempNextCycleDate == dateToConsider && paymentSummaryDetail.IsUserAction) //if the user do any pricing plan change on the same summmnary end date, this will calculate amounts according to the new selections { startDate = tempNextCycleDate; tempNextCycleDate = paymentSummaryDetail.PaymentDurationTypeCodeId == anualDurationCodeId?tempNextCycleDate.AddYears(1) : tempNextCycleDate.AddMonths(1); decimal recordTotalAmount = newTotalAmount; if (paymentSummaryDetail.PaymentDurationTypeCodeId == anualDurationCodeId) { recordTotalAmount = newInventoryPaymentPackageDetails.AnualAmount + newProjectPaymentPackageDetails.AnualAmount; } else { recordTotalAmount = newInventoryPaymentPackageDetails.Amount + newProjectPaymentPackageDetails.Amount; } //Get the relevant education or Discount if (paymentSummaryDetail.IsEducationPackage) { recordTotalAmount = recordTotalAmount * (100 - educationalDiscount) / 100; } else if (paymentSummaryDetail.DiscountCodeUsageToApply != null) { recordTotalAmount = financeBL.GetDiscountedAmount(paymentSummaryDetail.CompanyId, recordTotalAmount, paymentSummaryDetail.PaymentDurationTypeCodeId, paymentSummaryDetail.DiscountCodeUsageToApply, startDate, tempNextCycleDate); } summaryList.Add(CreateCompanyPaymentSummary(recordTotalAmount, tempNextCycleDate, paymentSummaryDetail, paymentSummaryDetail.DiscountCodeUsageToApply, startDate, tempNextCycleDate, paymentSummaryDetail.PaymentMethodCodeId != null && paymentSummaryDetail.PaymentMethodCodeId == invoiceMethodCodeId, paymentSummaryDetail.PaymentMethodCodeId, paymentSummaryDetail.CompanyPaymentPackage)); } if (paymentSummaryDetail.HasPackageChanged && dateToConsider > endDate) // user upgrade after the yearly cycle (Calculcate Pro rata) { dateDifference = (int)(tempNextCycleDate - dateToConsider).TotalDays; totalDue = GetProrataAmount(paymentSummaryDetail, currentCompanyPaymentPackage, summaryList.Count() > 0 ? summaryList.Last().DiscountCodeUsage : null, newTotalAmount, currentTotalAmount, tempNextCycleDate, dateDifference); summaryList.Add(CreateCompanyPaymentSummary(totalDue, tempNextCycleDate, paymentSummaryDetail, paymentSummaryDetail.DiscountCodeUsageToApply, dateToConsider, tempNextCycleDate, paymentSummaryDetail.PaymentMethodCodeId != null && paymentSummaryDetail.PaymentMethodCodeId == invoiceMethodCodeId, paymentSummaryDetail.PaymentMethodCodeId, paymentSummaryDetail.CompanyPaymentPackage)); } } } return(summaryList); }
/// <summary> /// To be called by the daily agent /// </summary> public static void UpdateProjectExpirations(DateTime dateToConsider, StageBitzDB dataContext) { //Get project status code ids int freeTrialCodeId = Utils.GetCodeByValue("ProjectStatus", "FREETRIAL").CodeId; int activeCodeId = Utils.GetCodeByValue("ProjectStatus", "ACTIVE").CodeId; int gracePeriodCodeId = Utils.GetCodeByValue("ProjectStatus", "GRACEPERIOD").CodeId; int paymentFailedCodeId = Utils.GetCodeByValue("ProjectStatus", "PAYMENTFAILED").CodeId; int suspendedCodeId = Utils.GetCodeByValue("ProjectStatus", "SUSPENDED").CodeId; int freeTrialOptInCodeId = Utils.GetCodeByValue("ProjectType", "FREETRIALOPTIN").CodeId; int freeTrialTypeCodeId = Utils.GetCodeByValue("ProjectType", "FREETRIAL").CodeId; FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); int companyPrimaryAdminCodeID = Utils.GetCodeByValue("CompanyUserTypeCode", "ADMIN").CodeId; int freeTrialProjectTypeCodeId = Utils.GetCodeByValue("ProjectType", "FREETRIAL").CodeId; string userWebUrl = Utils.GetSystemValue("SBUserWebURL"); string supportEmail = Utils.GetSystemValue("FeedbackEmail"); #region Free Trial ending pre-notice email //Get the free trial projects that are about to expire in 7 days, and notify them via email var freeTrialProjects = from p in dataContext.Projects where (p.ProjectStatusCodeId == freeTrialCodeId && p.ProjectTypeCodeId == freeTrialProjectTypeCodeId) && p.ExpirationDate != null select new { Project = p, PaymentsSpecified = (dataContext.CreditCardTokens .Where(tk => tk.RelatedTableName == "Company" && tk.RelatedId == p.CompanyId && tk.IsActive == true) .FirstOrDefault() != null) }; foreach (var projectInfo in freeTrialProjects) { StageBitz.Data.Project p = projectInfo.Project; int datediff = (p.ExpirationDate.Value.Date - dateToConsider).Days; if (datediff <= 7 && datediff >= 0) { string freeTrialGraceEmailType = "PROJECTFREETRIALGRACE"; //Check if the free trial expiration pre-notice has already been sent Email preNoticeEmail = dataContext.Emails.Where(em => em.EmailType == freeTrialGraceEmailType && em.RelatedId == p.ProjectId).FirstOrDefault(); if (preNoticeEmail == null) { Data.User companyPrimaryAdmin = //p.Company.CompanyUsers.Where(cu => cu.IsActive == true && cu.CompanyUserTypeCodeId == companyPrimaryAdminCodeID).FirstOrDefault().User; (from cu in p.Company.CompanyUsers join cur in dataContext.CompanyUserRoles on cu.CompanyUserId equals cur.CompanyUserId where cu.IsActive && cur.CompanyUserTypeCodeId == companyPrimaryAdminCodeID && cur.IsActive select cu).FirstOrDefault().User; string companyBillingUrl = string.Format("{0}/Company/CompanyFinancialDetails.aspx?companyid={1}", userWebUrl, p.CompanyId); string createProjectUrl = string.Format("{0}/Project/AddNewProject.aspx?companyid={1}", userWebUrl, p.CompanyId); EmailSender.SendProjectExpirationNoticeToCompanyAdmin(freeTrialGraceEmailType, p.ProjectId, companyPrimaryAdmin.Email1, companyPrimaryAdmin.FirstName, p.ProjectName, Utils.GetLongDateHtmlString(p.ExpirationDate.Value), companyBillingUrl, createProjectUrl, supportEmail); } } } #endregion #region Project Status Updates // this excute after project ExpirationDate is exceded. eg:- if the agent is down for 7 days, project status should be suspended. var projects = from p in dataContext.Projects where (p.ProjectStatusCodeId == freeTrialCodeId || p.ProjectStatusCodeId == gracePeriodCodeId || p.ProjectStatusCodeId == suspendedCodeId) && p.ExpirationDate != null && dateToConsider >= p.ExpirationDate select new { Project = p, PaymentsSpecified = (dataContext.CreditCardTokens .Where(tk => tk.RelatedTableName == "Company" && tk.RelatedId == p.CompanyId && tk.IsActive == true) .FirstOrDefault() != null) }; foreach (var projectInfo in projects) { StageBitz.Data.Project p = projectInfo.Project; Data.User companyPrimaryAdmin = // p.Company.CompanyUsers.Where(cu => cu.IsActive == true && cu.CompanyUserTypeCodeId == companyPrimaryAdminCodeID).FirstOrDefault().User; (from cu in p.Company.CompanyUsers join cur in dataContext.CompanyUserRoles on cu.CompanyUserId equals cur.CompanyUserId where cu.IsActive && cur.CompanyUserTypeCodeId == companyPrimaryAdminCodeID && cur.IsActive select cu).FirstOrDefault().User; string emailTemplateType = string.Empty; //Next expiration date is 7 days from current expiration date DateTime nextExpirationDate = p.ExpirationDate.Value.Date.AddDays(7); if (p.ProjectStatusCodeId == freeTrialCodeId) { //Get the current Company package to check. CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(p.CompanyId, dateToConsider); DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider, p.CompanyId); //There are only two possibilities. Either user has given his permission or nothing has done. //Check whether user has given the approval to continue the Free trial project. if (p.ProjectTypeCodeId == freeTrialOptInCodeId) { // He has optin not to continue if (companyPaymentPackage == null) { p.ProjectStatusCodeId = suspendedCodeId; } // He has optin to continue, with zero project package else if ((companyPaymentPackage != null && Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(companyPaymentPackage.ProjectPaymentPackageTypeId).ProjectCount == 0) || (!companyPaymentPackage.PaymentMethodCodeId.HasValue && (discountCodeUsage == null || discountCodeUsage.DiscountCode.Discount != 100))) { p.ProjectStatusCodeId = suspendedCodeId; } else { p.ProjectStatusCodeId = activeCodeId; } } else { p.ProjectStatusCodeId = suspendedCodeId; emailTemplateType = "PROJECTFREETRIALSUSPENDED"; } p.ExpirationDate = null; p.LastUpdatedDate = Utils.Now; p.LastUpdatedByUserId = 0; } else if (p.ProjectStatusCodeId == gracePeriodCodeId) { p.ProjectStatusCodeId = paymentFailedCodeId; p.LastUpdatedDate = Utils.Now; p.LastUpdatedByUserId = 0; } else if (p.ProjectStatusCodeId == suspendedCodeId && (p.ProjectTypeCodeId == freeTrialOptInCodeId || p.ProjectTypeCodeId == freeTrialTypeCodeId)) { // if free trial project is manually suspended during free trial, set ExpirationDate to null at the end of free trial period. p.ExpirationDate = null; } //Send the email notice if required if (emailTemplateType != string.Empty) { string companyBillingUrl = string.Format("{0}/Company/CompanyFinancialDetails.aspx?companyid={1}", userWebUrl, p.CompanyId); string createProjectUrl = string.Format("{0}/Project/AddNewProject.aspx?companyid={1}", userWebUrl, p.CompanyId); string expirationDate = string.Empty; if (p.ExpirationDate != null) { expirationDate = Utils.GetLongDateHtmlString(p.ExpirationDate.Value); } string pricingPlanURL = string.Format("{0}/Company/CompanyPricingPlans.aspx?companyId={1}", userWebUrl, p.CompanyId); EmailSender.SendProjectExpirationNoticeToCompanyAdmin(emailTemplateType, p.ProjectId, companyPrimaryAdmin.Email1, companyPrimaryAdmin.FirstName, p.ProjectName, expirationDate, companyBillingUrl, createProjectUrl, supportEmail, pricingPlanURL); } } #endregion }
/// <summary> /// Suspends the no payment option companies. /// </summary> /// <param name="dateToConsider">The date to consider.</param> public static void SuspendNoPaymentOptionCompanies(DateTime dateToConsider) { using (StageBitzDB dataContext = new StageBitzDB()) { FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); //Change the status to SuspendForNoPaymentOption if there are No option being selected. //Get all the No Payment option companies and check if they have to pay a certain amount before a certain period. //Send them an email, If they have a due amount to pay 2 weeks ahead (PBI 11444). int companyActiveStatusCodeId = Utils.GetCodeIdByCodeValue("CompanyStatus", "ACTIVE"); List <CompanyPaymentPackage> companyPaymentPackages = (from cpp in dataContext.CompanyPaymentPackages where cpp.Company.CompanyStatusCodeId == companyActiveStatusCodeId && cpp.PaymentMethodCodeId == null && cpp.StartDate <= dateToConsider && (cpp.EndDate > dateToConsider || cpp.EndDate == null) select cpp).Distinct().ToList(); foreach (CompanyPaymentPackage cpp in companyPaymentPackages) { int companyId = cpp.CompanyId; decimal totalDue = financeBL.CalculateALLPackageAmountsByPeriod(cpp.ProjectPaymentPackageTypeId, cpp.InventoryPaymentPackageTypeId, cpp.PaymentDurationCodeId); if (totalDue > 0) { DiscountCodeUsage currentdiscountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider, companyId); //Get the current DiscountCodeUsage. If the discount is 100%, check whether use has been notified. If not check for 14 days ahead and record if not. if (currentdiscountCodeUsage != null && currentdiscountCodeUsage.DiscountCode.Discount == 100) { CompanyDiscountNotificatonHistory companyDiscountNotificatonHistory = companyBL.GetCompanyDiscountExpireNotifiedRecord(companyId, dataContext); bool hasNotifiedUser = (companyDiscountNotificatonHistory != null); if (!hasNotifiedUser) { //Get the DiscountCode Usage and check whether it has a 100% code DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider.AddDays(14), companyId); //If there is no 100% discount if (discountCodeUsage == null || discountCodeUsage != null && discountCodeUsage.DiscountCode.Discount != 100) { //1. Notify via email //2. Log in the table CompanyDiscountNotificatonHistory companyDiscountNotificatonHistories = new CompanyDiscountNotificatonHistory() { CompanyId = companyId, Date = Utils.Today, IsActive = true, CreatedDate = Utils.Today, CreatedByUserId = 0, LastUpdatedDate = Utils.Today, LastUpdatedByUserId = 0 }; dataContext.CompanyDiscountNotificatonHistories.AddObject(companyDiscountNotificatonHistories); } } } else if (currentdiscountCodeUsage == null || currentdiscountCodeUsage != null && currentdiscountCodeUsage.DiscountCode.Discount != 100) { //Means We have to suspend the company SuspendProjectsForCompany(companyId, dataContext); } } } dataContext.SaveChanges(); } }