Beispiel #1
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
        }
Beispiel #2
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)));
        }
Beispiel #3
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);
                    }
                }
            }
        }
Beispiel #4
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();
            }
        }
        /// <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
        }
Beispiel #6
0
        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);
        }