Exemple #1
0
        public void CalculatethePackageAmountByPeriodTest()
        {
            FinanceBL financeBL = new FinanceBL(DataContext);

            // Get mega project package
            List <ProjectPaymentPackageDetails> projectPackageDetails = Utils.GetSystemProjectPackageDetails();
            ProjectPaymentPackageDetails        projectMegaPackage    = projectPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            // Get mega inventory package
            List <InventoryPaymentPackageDetails> inventoryPackageDetails = Utils.GetSystemInventoryPackageDetails();
            InventoryPaymentPackageDetails        inventoryMegaPackage    = inventoryPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            // get discount code usage
            DiscountCodeUsage discountCodeUsage = new DiscountCodeUsageMock(DataContext).GetDiscountCodeUsage(true, null);

            DataContext.SaveChanges();

            // get code ids
            int monthlyPaymentDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "MONTHLY");
            int annualPaymentDurationCodeId  = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");
            int projectPackageTypeId         = Utils.GetCodeIdByCodeValue("PaymentPackageType", "PROJECT");
            int inventoryPackageTypeId       = Utils.GetCodeIdByCodeValue("PaymentPackageType", "INVENTORY");

            // validate
            decimal?amount = financeBL.CalculatethePackageAmountByPeriod(inventoryPackageTypeId, inventoryMegaPackage.PackageTypeId, monthlyPaymentDurationCodeId);

            Assert.IsTrue(inventoryMegaPackage.Amount == amount);
            amount = financeBL.CalculatethePackageAmountByPeriod(inventoryPackageTypeId, inventoryMegaPackage.PackageTypeId, annualPaymentDurationCodeId);
            Assert.IsTrue(inventoryMegaPackage.AnualAmount == amount);
            amount = financeBL.CalculatethePackageAmountByPeriod(projectPackageTypeId, projectMegaPackage.PackageTypeId, monthlyPaymentDurationCodeId);
            Assert.IsTrue(projectMegaPackage.Amount == amount);
            amount = financeBL.CalculatethePackageAmountByPeriod(projectPackageTypeId, projectMegaPackage.PackageTypeId, annualPaymentDurationCodeId);
            Assert.IsTrue(projectMegaPackage.AnualAmount == amount);
        }
Exemple #2
0
        /// <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
        }
Exemple #3
0
        /// <summary>
        /// Determines whether free trial status included for the given date.
        /// </summary>
        /// <param name="companyId">The company identifier.</param>
        /// <param name="dateToConsider">The date to consider.</param>
        /// <returns></returns>
        public bool IsFreeTrialStatusIncludedFortheDay(int companyId, DateTime dateToConsider)
        {
            // this will return whether the company is in free trial including the last hour of the free trial day. At the last day after 11 pm the free trial gets over. Is Free Trial Company returns false.
            // But we need to return true during this period. The additional checking is done for this matter.
            FinanceBL financeBL      = new FinanceBL(DataContext);
            var       currentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(companyId);

            return(this.IsFreeTrialCompany(companyId) || currentPackage != null && (this.IsFreeTrialEndedCompany(companyId) && currentPackage.StartDate == dateToConsider.AddDays(1)));
        }
Exemple #4
0
        /// <summary>
        /// Creates the payment summaries.
        /// This will create payment summaries/Invoice Requests for the repeat payments to be charged at the end of the cycle
        /// </summary>
        /// <param name="dateToConsider">The date to consider.</param>
        public static void CreatePaymentSummaries(DateTime dateToConsider)
        {
            using (StageBitzDB dataContext = new StageBitzDB())
            {
                FinanceBL financeBL = new FinanceBL(dataContext);
                CompanyBL companyBL = new CompanyBL(dataContext);

                //This will get all the CompanyPaymentPackages that needs to be Charged for considering cycle
                List <CompanyPaymentPackage> companyPaymentPackages = (from cpp in dataContext.CompanyPaymentPackages
                                                                       join cps in dataContext.CompanyPaymentSummaries on cpp.CompanyId equals cps.CompanyId
                                                                       where cps.IsImmidiateFutureRecordCreated == false &&
                                                                       cpp.StartDate <= dateToConsider && (cpp.EndDate > dateToConsider || cpp.EndDate == null) &&
                                                                       cps.NextPaymentCycleStartingDate <= dateToConsider
                                                                       select cpp).Distinct().ToList();

                foreach (CompanyPaymentPackage companyPaymentPackage in companyPaymentPackages)
                {
                    Data.Company company = companyPaymentPackage.Company;

                    PaymentSummaryDetails paymentSummaryDetails = new PaymentSummaryDetails()
                    {
                        CompanyPaymentPackage = companyPaymentPackage,
                        CompanyId             = companyPaymentPackage.CompanyId,
                        ShouldProcess         = !(companyBL.IsCompanySuspended(companyPaymentPackage.CompanyId) || companyBL.HasCompanySuspendedbySBAdmin(companyPaymentPackage.CompanyId)),
                        UserId                        = 0,
                        PackageStartDate              = companyPaymentPackage.StartDate,
                        PaymentMethodCodeId           = companyPaymentPackage.PaymentMethodCodeId,
                        HasPackageChanged             = false,
                        ProjectPaymentPackageTypeId   = companyPaymentPackage.ProjectPaymentPackageTypeId,
                        InventoryPaymentPackageTypeId = companyPaymentPackage.InventoryPaymentPackageTypeId,
                        IsEducationPackage            = companyPaymentPackage.IsEducationalPackage,
                        PaymentDurationTypeCodeId     = companyPaymentPackage.PaymentDurationCodeId,
                        DiscountCodeUsageToApply      = financeBL.GetLatestDiscountCodeUsage(companyPaymentPackage.CompanyId)
                    };
                    //Get IsImmidiateFutureRecordCreated "False" Future Anual Summary records and make them as "True".(To commit as Processed)
                    var unprocessedFutureSummaries = (from cps in dataContext.CompanyPaymentSummaries
                                                      where cps.IsImmidiateFutureRecordCreated == false &&
                                                      cps.CompanyId == companyPaymentPackage.CompanyId &&
                                                      cps.ToDate <= dateToConsider
                                                      select cps).ToList();

                    foreach (CompanyPaymentSummary cps in unprocessedFutureSummaries)
                    {
                        cps.IsImmidiateFutureRecordCreated = true;
                        cps.LastUpdatedDate = Utils.Today;
                        cps.LastUpdatedBy   = 0;
                    }

                    CreateCompanyPaymentSummaries(paymentSummaryDetails, dateToConsider, dataContext);
                }

                dataContext.SaveChanges();
            }
        }
Exemple #5
0
        /// <summary>
        /// Determines whether [has edit permission for inventory staff].
        /// </summary>
        /// <param name="companyId">The company identifier.</param>
        /// <param name="userId">The user identifier.</param>
        /// <returns></returns>
        public bool HasEditPermissionForInventoryStaff(int companyId, int userId, int?locationId)
        {
            FinanceBL   financeBL   = new FinanceBL(DataContext);
            InventoryBL inventoryBL = new InventoryBL(DataContext);

            bool hasPackageSelected = financeBL.HasPackageSelectedForFreeTrailEndedCompany(companyId);

            return((Utils.IsCompanyInventoryAdmin(companyId, userId) ||
                    (!locationId.HasValue && inventoryBL.IsCompanyInventoryStaffMemberAnyLocation(companyId, userId)) ||
                    (locationId.HasValue && Utils.IsCompanyInventoryStaffMember(companyId, userId, locationId, DataContext))) &&
                   !this.HasCompanySuspendedbySBAdmin(companyId) && hasPackageSelected && !IsCompanySuspended(companyId));
        }
Exemple #6
0
        public void GetDiscountCodeTest()
        {
            FinanceBL financeBL = new FinanceBL(DataContext);

            DiscountCode userDiscount = new DiscountCodeMock(DataContext).GetDiscountCode("DisCode60", 60.00M, 5, 5);

            DataContext.DiscountCodes.AddObject(userDiscount);
            financeBL.SaveChanges();

            DiscountCode discountDB = financeBL.GetDiscountCode("DisCode60");

            Assert.AreEqual(userDiscount, discountDB);
        }
Exemple #7
0
        /// <summary>
        /// Updates the payment summary for free trial company.
        /// </summary>
        /// <param name="companyId">The company identifier.</param>
        /// <param name="discountCodeUsage">The discount code usage.</param>
        /// <param name="isCompanySuspend">The is company suspend.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="dataContext">The data context.</param>
        public static void UpdatePaymentSummaryForFreeTrialCompany(int companyId, DiscountCodeUsage discountCodeUsage, bool?isCompanySuspend, int userId, StageBitzDB dataContext)
        {
            CompanyBL companyBL = new CompanyBL(dataContext);

            if (companyBL.IsFreeTrialStatusIncludedFortheDay(companyId, Utils.Today))
            {
                if (isCompanySuspend != null)
                {
                    CompanyPaymentSummary existingCompanyPackageSummary = GetCurrentCompanyPaymentSummary(companyId, dataContext);
                    if (existingCompanyPackageSummary != null)
                    {
                        existingCompanyPackageSummary.ShouldProcess   = !isCompanySuspend.Value;
                        existingCompanyPackageSummary.LastUpdatedDate = Utils.Today;
                        existingCompanyPackageSummary.LastUpdatedBy   = userId;
                    }
                }
                else
                {
                    FinanceBL             financeBL             = new FinanceBL(dataContext);
                    CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(companyId);

                    if (companyPaymentPackage != null)
                    {
                        PaymentSummaryDetails paymentSummaryDetails = new PaymentSummaryDetails()
                        {
                            CompanyPaymentPackage = companyPaymentPackage,
                            CompanyId             = companyId,
                            ShouldProcess         = true,
                            UserId                        = userId,
                            PackageStartDate              = companyPaymentPackage.StartDate,
                            PaymentMethodCodeId           = companyPaymentPackage.PaymentMethodCodeId,
                            HasPackageChanged             = false,
                            ProjectPaymentPackageTypeId   = companyPaymentPackage.ProjectPaymentPackageTypeId,
                            InventoryPaymentPackageTypeId = companyPaymentPackage.InventoryPaymentPackageTypeId,
                            IsEducationPackage            = companyPaymentPackage.IsEducationalPackage,
                            PaymentDurationTypeCodeId     = companyPaymentPackage.PaymentDurationCodeId,
                        };

                        if (!companyPaymentPackage.IsEducationalPackage) //we should only include the discound usage to summary if the company is not educational
                        {
                            paymentSummaryDetails.DiscountCodeUsageToApply = discountCodeUsage;
                        }

                        CreateCompanyPaymentSummaries(paymentSummaryDetails, Utils.Today, dataContext);
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Gets the prorata amount.
        /// </summary>
        /// <param name="paymentSummaryDetail">The payment summary detail.</param>
        /// <param name="currentCompanyPaymentPackage">The current company payment package.</param>
        /// <param name="currentDiscountCodeUsage">The current discount code usage.</param>
        /// <param name="newtotalAmount">The newtotal amount.</param>
        /// <param name="currentTotalAmount">The current total amount.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="dateDifference">The date difference.</param>
        /// <returns></returns>
        public static decimal GetProrataAmount(PaymentSummaryDetails paymentSummaryDetail, CompanyPaymentPackage currentCompanyPaymentPackage, DiscountCodeUsage currentDiscountCodeUsage, decimal newtotalAmount, decimal currentTotalAmount, DateTime endDate, int dateDifference)
        {
            using (StageBitzDB dataContext = new StageBitzDB())
            {
                int       anualDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");
                decimal   educationalDiscount = decimal.Parse(Utils.GetSystemValue("EducationalDiscount"));
                int       datesPerCycle       = 0;
                FinanceBL financeBL           = new FinanceBL(dataContext);

                if (currentCompanyPaymentPackage.PaymentDurationCodeId == anualDurationCodeId)
                {
                    datesPerCycle = (int)(endDate - endDate.AddYears(-1)).TotalDays;
                }
                else
                {
                    datesPerCycle = (int)(endDate - endDate.AddMonths(-1)).TotalDays;
                }

                newtotalAmount     = newtotalAmount * dateDifference / datesPerCycle;
                currentTotalAmount = currentTotalAmount * dateDifference / datesPerCycle;

                if (paymentSummaryDetail.IsEducationPackage)
                {
                    newtotalAmount = newtotalAmount * (100 - educationalDiscount) / 100;
                }
                else if (paymentSummaryDetail.DiscountCodeUsageToApply != null)
                {
                    newtotalAmount = financeBL.GetDiscountedAmount(paymentSummaryDetail.CompanyId, newtotalAmount, paymentSummaryDetail.PaymentDurationTypeCodeId, paymentSummaryDetail.DiscountCodeUsageToApply, paymentSummaryDetail.PackageStartDate, endDate);
                }

                if (currentCompanyPaymentPackage.IsEducationalPackage)
                {
                    currentTotalAmount = currentTotalAmount * (100 - educationalDiscount) / 100;
                }
                else if (currentDiscountCodeUsage != null)
                {
                    currentTotalAmount = financeBL.GetDiscountedAmount(paymentSummaryDetail.CompanyId, currentTotalAmount, currentCompanyPaymentPackage.PaymentDurationCodeId, currentDiscountCodeUsage, paymentSummaryDetail.PackageStartDate, endDate);
                }

                return(newtotalAmount - currentTotalAmount);
            }
        }
Exemple #9
0
        /// <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();
            }
        }
Exemple #10
0
        public void GetDiscountCodeUsagesTest()
        {
            FinanceBL financeBL = new FinanceBL(DataContext);

            // Create 3 companies
            CompanyMock companyMock = new CompanyMock(DataContext);
            Company     company1    = companyMock.GetCompany();
            Company     company2    = companyMock.GetCompany();
            Company     company3    = companyMock.GetCompany();

            // Create 2 discount codes
            DiscountCode discount1 = new DiscountCodeMock(DataContext).GetDiscountCode("DisCode1", 60.00M, 5, 5);
            DiscountCode discount2 = new DiscountCodeMock(DataContext).GetDiscountCode("DisCode2", 50.00M, 5, 5);

            DataContext.DiscountCodes.AddObject(discount1);
            DataContext.DiscountCodes.AddObject(discount2);
            DataContext.SaveChanges();

            // Apply discount codes to compnies
            financeBL.SaveDiscountCodeUsageToCompany(discount1, 0, company1.CompanyId);
            DataContext.SaveChanges();
            financeBL.SaveDiscountCodeUsageToCompany(discount1, 0, company2.CompanyId);
            DataContext.SaveChanges();
            financeBL.SaveDiscountCodeUsageToCompany(discount2, 0, company2.CompanyId);
            DataContext.SaveChanges();
            financeBL.SaveDiscountCodeUsageToCompany(discount2, 0, company3.CompanyId);
            DataContext.SaveChanges();

            // Get Counts
            List <DiscountCodeUsage> dis1UsageWithInActive    = financeBL.GetDiscountCodeUsages(discount1.DiscountCodeID, true);
            List <DiscountCodeUsage> dis1UsageWithOutInActive = financeBL.GetDiscountCodeUsages(discount1.DiscountCodeID, false);
            List <DiscountCodeUsage> dis2UsageWithInActive    = financeBL.GetDiscountCodeUsages(discount2.DiscountCodeID, true);
            List <DiscountCodeUsage> dis2UsageWithOutInActive = financeBL.GetDiscountCodeUsages(discount2.DiscountCodeID, false);

            // Validate
            Assert.IsTrue(dis1UsageWithInActive.Count == 2);
            Assert.IsTrue(dis1UsageWithOutInActive.Count == 1);
            Assert.IsTrue(dis2UsageWithInActive.Count == 2);
            Assert.IsTrue(dis2UsageWithOutInActive.Count == 2);
        }
Exemple #11
0
        /// <summary>
        /// Returns the warning status of the project based on it's current status and expiration details.
        /// </summary>
        public static CompanyWarningInfo GetCompanyWarningStatus(int companyId, int companyStatusCodeId, DateTime?expirationDate)
        {
            using (StageBitzDB dataContext = new StageBitzDB())
            {
                CompanyBL companyBL = new CompanyBL(dataContext);
                FinanceBL financeBL = new FinanceBL(dataContext);

                string statusCode    = Utils.GetCodeByCodeId(companyStatusCodeId).Value;
                double remainingDays = (statusCode == "ACTIVE" || expirationDate == null) ? -1 : (expirationDate.Value.Date - Utils.Today).TotalDays;

                CompanyWarningStatus warningStatus = CompanyWarningStatus.NoWarning;

                if (companyBL.HasCompanySuspendedbySBAdmin(companyId))
                {
                    warningStatus = CompanyWarningStatus.SBAdminSuspended;
                }
                else if (statusCode == "GRACEPERIOD" && ProjectFinanceHandler.IsPaymentFailedInvoicesExistForCompany(companyId))
                {
                    warningStatus = CompanyWarningStatus.PaymentFailedGracePeriod;
                }
                else if (statusCode == "SUSPENDEDFORPAYMENTFAILED")
                {
                    warningStatus = CompanyWarningStatus.PaymentFailed;
                }
                else if (!financeBL.HasPackageSelectedForFreeTrailEndedCompany(companyId))
                {
                    warningStatus = CompanyWarningStatus.FreeTrailEndNoPaymentPackage;
                }
                else if (statusCode == "SUSPENDEDFORNOPAYMENTOPTIONS")
                {
                    warningStatus = CompanyWarningStatus.SuspendedForNoPaymentOptions;
                }

                return(new CompanyWarningInfo(warningStatus, (int)Math.Round(remainingDays, 0)));
            }
        }
Exemple #12
0
        public void GetDiscountedAmountTest()
        {
            FinanceBL financeBL = new FinanceBL(DataContext);
            List <ProjectPaymentPackageDetails> projectPackageDetails = Utils.GetSystemProjectPackageDetails();
            ProjectPaymentPackageDetails        projectMegaPackage    = projectPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            List <InventoryPaymentPackageDetails> inventoryPackageDetails = Utils.GetSystemInventoryPackageDetails();
            InventoryPaymentPackageDetails        inventoryMegaPackage    = inventoryPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            // Create a company
            DiscountCodeUsage discountCodeUsage = new DiscountCodeUsageMock(DataContext).GetDiscountCodeUsage(true, null);

            DataContext.SaveChanges();

            int monthlyPaymentDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "MONTHLY");
            int annualPaymentDurationCodeId  = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");

            decimal totalDue         = financeBL.CalculateALLPackageAmountsByPeriod(projectMegaPackage.PackageTypeId, inventoryMegaPackage.PackageTypeId, monthlyPaymentDurationCodeId);
            decimal discountedAmount = financeBL.GetDiscountedAmount(discountCodeUsage.CompanyId, totalDue, monthlyPaymentDurationCodeId, discountCodeUsage, Utils.Today, Utils.Today.AddMonths(1));

            Assert.IsTrue((projectMegaPackage.Amount + inventoryMegaPackage.Amount) * (discountCodeUsage.DiscountCode.Discount / 100) == discountedAmount);

            totalDue         = financeBL.CalculateALLPackageAmountsByPeriod(projectMegaPackage.PackageTypeId, inventoryMegaPackage.PackageTypeId, annualPaymentDurationCodeId);
            discountedAmount = financeBL.GetDiscountedAmount(discountCodeUsage.CompanyId, totalDue, annualPaymentDurationCodeId, discountCodeUsage, Utils.Today, Utils.Today.AddYears(1));


            decimal discountedDays   = (discountCodeUsage.EndDate - discountCodeUsage.StartDate.Value).Days;
            decimal totalDays        = (Utils.Today.AddYears(1) - Utils.Today).Days;
            decimal noDiscountedDays = totalDays - discountedDays;


            decimal testTotalAmount = (((discountedDays / totalDays) * (discountCodeUsage.DiscountCode.Discount / 100))
                                       + (noDiscountedDays / totalDays)) * (projectMegaPackage.AnualAmount + inventoryMegaPackage.AnualAmount);

            Assert.IsTrue(decimal.Round(testTotalAmount, 2) == discountedAmount);
        }
Exemple #13
0
        public void CalculateALLPackageAmountsByPeriodTest()
        {
            FinanceBL financeBL = new FinanceBL(DataContext);
            List <ProjectPaymentPackageDetails> projectPackageDetails = Utils.GetSystemProjectPackageDetails();
            ProjectPaymentPackageDetails        projectMegaPackage    = projectPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            List <InventoryPaymentPackageDetails> inventoryPackageDetails = Utils.GetSystemInventoryPackageDetails();
            InventoryPaymentPackageDetails        inventoryMegaPackage    = inventoryPackageDetails.Where(ppd => ppd.PackageName == "MEGA").FirstOrDefault();

            // Create a company
            DiscountCodeUsage discountCodeUsage = new DiscountCodeUsageMock(DataContext).GetDiscountCodeUsage(true, null);

            DataContext.SaveChanges();

            int monthlyPaymentDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "MONTHLY");
            int annualPaymentDurationCodeId  = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");

            decimal totalDue = financeBL.CalculateALLPackageAmountsByPeriod(projectMegaPackage.PackageTypeId, inventoryMegaPackage.PackageTypeId, monthlyPaymentDurationCodeId);

            Assert.IsTrue((projectMegaPackage.Amount + inventoryMegaPackage.Amount) == totalDue);

            totalDue = financeBL.CalculateALLPackageAmountsByPeriod(projectMegaPackage.PackageTypeId, inventoryMegaPackage.PackageTypeId, annualPaymentDurationCodeId);
            Assert.IsTrue((projectMegaPackage.AnualAmount + inventoryMegaPackage.AnualAmount) == totalDue);
        }
Exemple #14
0
        public void AddDiscountCodeUsageBySBAdminTest()
        {
            FinanceBL         financeBL         = new FinanceBL(DataContext);
            DiscountCodeUsage discountCodeUsage = new DiscountCodeUsageMock(DataContext).GetDiscountCodeUsage(true, null);

            // SB admin apply discount code.
            financeBL.AddDiscountCodeUsageBySBAdmin(discountCodeUsage, 0);
            int companyId = discountCodeUsage.CompanyId;

            DiscountCodeUsage discountCodeUsageDB = financeBL.GetLatestDiscountCodeUsage(companyId);

            Assert.IsNotNull(discountCodeUsageDB);
            Assert.AreEqual(discountCodeUsage, discountCodeUsageDB);

            // User replace discount code.
            DiscountCode userDiscount = new DiscountCodeMock(DataContext).GetDiscountCode("DisCode60", 60.00M, 5, 5);

            DataContext.DiscountCodes.AddObject(userDiscount);

            financeBL.SaveDiscountCodeUsageToCompany(userDiscount, 0, companyId);
            financeBL.SaveChanges();

            discountCodeUsageDB = financeBL.GetLatestDiscountCodeUsage(companyId);
            Assert.IsNotNull(discountCodeUsageDB);
            Assert.AreEqual(userDiscount, discountCodeUsageDB.DiscountCode);

            // SB admin apply discount code again
            DiscountCodeUsage discountCodeUsageNew = new DiscountCodeUsageMock(DataContext).GetDiscountCodeUsage(true, companyId);

            financeBL.AddDiscountCodeUsageBySBAdmin(discountCodeUsageNew, 0);

            discountCodeUsageDB = financeBL.GetLatestDiscountCodeUsage(companyId);
            Assert.IsNotNull(discountCodeUsageDB);
            Assert.AreEqual(discountCodeUsageNew, discountCodeUsageDB);
            Assert.AreNotEqual(discountCodeUsage, discountCodeUsageNew);
        }
        public ItemResult SyncItem(MobileItem mobileItem)
        {
            string     status         = string.Empty;
            string     message        = string.Empty;
            ItemResult itemResult     = new ItemResult();
            bool       isValidVersion = true;

            try
            {
                using (StageBitzDB dataContext = new StageBitzDB())
                {
                    isValidVersion = Helper.IsValidAppVersion(mobileItem.Version, out status);
                    if (isValidVersion)
                    {
                        if (mobileItem != null)
                        {
                            //Check if this Item has already been created in MobileItem table
                            //If not create
                            InventoryMobileItem inventoryMobileItem = dataContext.InventoryMobileItems.Where(imi => imi.MobileItemId == mobileItem.DeviceItemId).FirstOrDefault();
                            if (inventoryMobileItem == null)
                            {
                                int userId = int.Parse(Utils.DecryptStringAES(mobileItem.Token));

                                //Check if the user can Create the Item
                                CompanyBL   companyBL   = new CompanyBL(dataContext);
                                FinanceBL   financeBL   = new FinanceBL(dataContext);
                                InventoryBL inventoryBL = new InventoryBL(dataContext);

                                if (companyBL.HasEditPermissionForInventoryStaff(mobileItem.CompanyId, userId, null))
                                {
                                    //New Creation of Item
                                    if (mobileItem.ItemId == 0)
                                    {
                                        //To create items in the hidden mode, if the limits have reached.
                                        bool isFreeTrailCompany = companyBL.IsFreeTrialCompany(mobileItem.CompanyId);

                                        CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(mobileItem.CompanyId);

                                        InventoryPaymentPackageDetails inventoryPaymentPackageDetails = null;
                                        if (companyPaymentPackage != null)
                                        {
                                            inventoryPaymentPackageDetails =
                                                Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(companyPaymentPackage.InventoryPaymentPackageTypeId);
                                        }

                                        CompanyCurrentUsage companyCurrentUsage = financeBL.GetCompanyCurrentUsage(mobileItem.CompanyId, null);

                                        if (!financeBL.HasExceededInventoryLimit(isFreeTrailCompany, inventoryPaymentPackageDetails, companyCurrentUsage))
                                        {
                                            inventoryMobileItem = new InventoryMobileItem();
                                            inventoryMobileItem.MobileItemId = mobileItem.DeviceItemId;
                                            inventoryMobileItem.CreatedBy    = userId;
                                            inventoryMobileItem.CreatedDate  = Utils.Now;
                                            dataContext.InventoryMobileItems.AddObject(inventoryMobileItem);

                                            Item item = new Item();
                                            item.Name                  = mobileItem.Name;
                                            item.IsManuallyAdded       = true;
                                            item.ItemTypeId            = mobileItem.ItemTypeId;
                                            item.Quantity              = mobileItem.Quantity;
                                            item.Description           = mobileItem.Description;
                                            item.CompanyId             = mobileItem.CompanyId;
                                            item.IsActive              = true;
                                            item.CreatedByUserId       = item.LastUpdatedByUserId = userId;
                                            item.CreatedDate           = item.LastUpdatedDate = Utils.Now;
                                            item.VisibilityLevelCodeId = Utils.GetCodeIdByCodeValue("InventoryVisibilityLevel", "ABOVE_SHAREDINVENTORY");

                                            dataContext.Items.AddObject(item);
                                            dataContext.SaveChanges();
                                            itemResult.Id = item.ItemId;
                                            status        = "OK";
                                        }
                                        else
                                        {
                                            status  = "LIMITREACHED";
                                            message = "Inventory plan limit reached.";
                                        }
                                    }
                                    else
                                    {
                                        //Edit existing one
                                        Item exItem = inventoryBL.GetItem(mobileItem.ItemId);
                                        if (exItem != null && exItem.IsActive)
                                        {
                                            Code userVisibilityCode = inventoryBL.GetUserInventoryVisibilityLevel(mobileItem.CompanyId, userId, null, false);
                                            if (!inventoryBL.GetItemStatusInformationForUser(exItem, mobileItem.CompanyId, userId).IsReadOnly&& exItem.Code.SortOrder >= userVisibilityCode.SortOrder)
                                            {
                                                if (mobileItem.LastUpdateDate == exItem.LastUpdatedDate)
                                                {
                                                    exItem.Name                = mobileItem.Name;
                                                    exItem.ItemTypeId          = mobileItem.ItemTypeId;
                                                    exItem.Description         = mobileItem.Description;
                                                    exItem.Quantity            = mobileItem.Quantity;
                                                    exItem.LastUpdatedByUserId = userId;
                                                    exItem.LastUpdatedDate     = Utils.Now;
                                                    dataContext.SaveChanges();
                                                    status        = "OK";
                                                    itemResult.Id = mobileItem.ItemId;
                                                }
                                                else
                                                {
                                                    status  = "ITEMEDITED";
                                                    message = "Item already edited.";
                                                }
                                            }
                                            else
                                            {
                                                status  = "NORIGHTS";
                                                message = "Check settings with Company Administrator.";
                                            }
                                        }
                                        else
                                        {
                                            status  = "ITEMDELETED";
                                            message = "Item no longer exists.";
                                        }
                                    }
                                }
                                else
                                {
                                    status  = "NOACCESS";
                                    message = "Check settings with Company Administrator.";
                                }
                            }
                            else
                            {
                                itemResult.Id = inventoryMobileItem.ItemId;
                                status        = "ITEMEXIST";
                                message       = "Item already synced.";
                            }
                        }
                    }
                    else
                    {
                        status  = "INVALIDAPP";
                        message = "Please update App.";
                    }
                }
            }
            catch (Exception ex)
            {
                AgentErrorLog.HandleException(ex);
                status  = "ERROR";
                message = "Oops! Unkown error. Sorry...";
            }
            itemResult.MobileId = mobileItem.DeviceItemId;
            itemResult.Status   = status;
            itemResult.Message  = message;
            return(itemResult);
        }
Exemple #16
0
        /// <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();
            }
        }
Exemple #17
0
        /// <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
        }