Esempio n. 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
        }
Esempio n. 2
0
        /// <summary>
        /// Saves the payment details.
        /// </summary>
        /// <returns></returns>
        public bool SavePaymentDetails()
        {
            bool hasSaved = false;

            if (Page.IsValid && ValidateCreditCardDetails())
            {
                CompanyPaymentPackage oldPackage         = GetCompanyPaymentPackageForUpdating();
                bool isInventoryPackageOrDurationChanged = GetBL <FinanceBL>().HasInventryProjectOrDurationChanged(PricePlanDetails, oldPackage);

                SaveCompanyDetails();
                if (CompanyId > 0) // Create New Company wizard has handled after the company got crated.
                {
                    SaveCreditCardDetails();
                }

                //Save Discount if applies
                SaveCompanyPackage(oldPackage);
                SaveDiscountCode();
                if (CompanyId > 0)
                {
                    if (chkAcceptTerms.Visible)  //Mail should be send only there is a change. Since we are displaying terms and conditions only there is a change, mail should be sent if that is visible
                    {
                        SendStageBitzAdminEmail(CompanyId, isInventoryPackageOrDurationChanged);
                    }
                }

                this.GetBL <CompanyBL>().SaveChanges();

                //Save the Company Profile image and Credit card detatils for New company wizard
                if (CompanyId == 0)
                {
                    if (Media != null)
                    {
                        Media.RelatedId = NewCompany.CompanyId;
                        DataContext.DocumentMedias.AddObject(Media);
                    }
                    if (Mode == DisplayMode.CreditCard)
                    {
                        //Get the latest CompanyId and assign to the Paymentsetup control
                        pricingPlanSetupCreditCardDetails.CompanyId = NewCompany.CompanyId;
                        SaveCreditCardDetails();
                    }

                    if (chkAcceptTerms.Visible)
                    {
                        SendStageBitzAdminEmail(NewCompany.CompanyId, isInventoryPackageOrDurationChanged);
                    }

                    this.GetBL <CompanyBL>().SaveChanges();
                }

                hasSaved = true;
            }

            return(hasSaved);
        }
Esempio n. 3
0
        /// <summary>
        /// Handles the Click event of the btnConfirmFreeInventory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnConfirmFreeInventory_Click(object sender, EventArgs e)
        {
            popupFreeInventoryOnly.HidePopup();

            if (!IsCompanyValidToSave())
            {
                return;
            }

            CompanyPaymentPackage oldCompanyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
            bool isInventoryPackageOrDurationChanged       = GetBL <FinanceBL>().HasInventryProjectOrDurationChanged(PricePlanDetails, oldCompanyPaymentPackage);

            //Handling concurrency (another admin changed the package concurrently)
            if (oldCompanyPaymentPackage != null && oldCompanyPaymentPackage.LastUpdateDate > OriginalLastUpdatedDate)
            {
                StageBitzException.ThrowException(new ConcurrencyException(ExceptionOrigin.CompanyPaymentPackage, CompanyId));
            }
            else
            {
                if (CompanyId == 0)
                {
                    //Add to the Context
                    DataContext.Companies.AddObject(NewCompany);
                }
                this.GetBL <FinanceBL>().SaveCompanyPackage(UserID, oldCompanyPaymentPackage, PricePlanDetails, false);
                //First check whether the applied Discount is valid. Because it can be either deleted, some one else being used, etc..
                if (PricePlanDetails.DiscountCode != null)
                {
                    string errorMsg = string.Empty;
                    bool   isValid  = GetBL <FinanceBL>().IsDiscountCodeValidToUse(PricePlanDetails.DiscountCode.Code, CompanyId, out errorMsg, PricePlanDetails.DiscountCode == null ? null : PricePlanDetails.DiscountCode);
                    if (isValid)
                    {
                        SaveDiscountCode();
                    }
                }
                this.GetBL <CompanyBL>().SaveChanges();
                var    globalizationSection = WebConfigurationManager.GetSection("system.web/globalization") as GlobalizationSection;
                string cultureName          = globalizationSection.Culture;
                string authText             = string.Format("They have selected {0} Inventory level and {1} Project level.", Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(PricePlanDetails.InventoryPaymentPackageTypeId).PackageDisplayName, Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(PricePlanDetails.ProjectPaymentPackageTypeId).PackageDisplayName);

                if (chkAcceptTermsFreeInventory.Visible)
                {
                    this.GetBL <FinanceBL>().SendStageBitzAdminEmail(CompanyId == 0 ? NewCompany.CompanyId : CompanyId, UserID, PricePlanDetails, cultureName, string.Empty, authText, isInventoryPackageOrDurationChanged);
                }
                //Save the Company Profile image
                if (CompanyId == 0 && Media != null)
                {
                    Media.RelatedId = NewCompany.CompanyId;
                    DataContext.DocumentMedias.AddObject(Media);
                    this.GetBL <CompanyBL>().SaveChanges();
                }
            }
            btnChangesSaved.CommandArgument = "FreeInventory";
            popupSaveChangesConfirm.ShowPopup();
        }
Esempio n. 4
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);
                    }
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Saves the company package.
        /// </summary>
        /// <param name="oldCompanyPaymentPackage">The old company payment package.</param>
        private void SaveCompanyPackage(CompanyPaymentPackage oldCompanyPaymentPackage)
        {
            PricePlanDetails.CompanyId = this.CompanyId;
            if (Mode == DisplayMode.CreditCard)
            {
                PricePlanDetails.Position            = string.Empty;
                PricePlanDetails.PaymentMethodCodeId = CreditCardPaymentCode.CodeId;
            }
            else if (Mode == DisplayMode.Invoice)
            {
                PricePlanDetails.Position            = txtPosition.Text.Trim();
                PricePlanDetails.PaymentMethodCodeId = InvoicePaymentCode.CodeId;
            }

            this.GetBL <FinanceBL>().SaveCompanyPackage(UserID, oldCompanyPaymentPackage, PricePlanDetails, false);
        }
Esempio n. 6
0
        /// <summary>
        /// Loads the data.
        /// </summary>
        public void LoadData()
        {
            CompanyPaymentPackage companyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);

            if (companyPaymentPackage != null)
            {
                //This does not get NULL. 0 values as default
                CompanyCurrentUsage   companyCurrentUsage = this.GetBL <FinanceBL>().GetCompanyCurrentUsage(CompanyId, null);
                CompanyPaymentPackage futurePackage       = this.GetBL <FinanceBL>().GetLatestRequestForTheCompany(CompanyId);

                ProjectPaymentPackageDetails   projectPackageDetails          = Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(companyPaymentPackage.ProjectPaymentPackageTypeId);
                InventoryPaymentPackageDetails inventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(companyPaymentPackage.InventoryPaymentPackageTypeId);

                litActiveProjects.Text      = string.Concat(projectPackageDetails.ProjectCount, projectPackageDetails.ProjectCount == 1 ? " Active Project" : " Active Projects");
                litCurrentProjectCount.Text = companyCurrentUsage.ProjectCount.ToString();

                if (this.GetBL <FinanceBL>().IsEducationalCompany(companyPaymentPackage))
                {
                    litActiveUsers.Text = "Unlimited Users";
                }
                else
                {
                    litActiveUsers.Text = string.Concat(projectPackageDetails.HeadCount, projectPackageDetails.HeadCount == 1 ? " Active User" : " Active Users");
                }

                litCurrentUserCount.Text = companyCurrentUsage.UserCount.ToString();
                litInventoryItems.Text   = string.Concat(inventoryPaymentPackageDetails.ItemCount == null ? "Unlimited " : inventoryPaymentPackageDetails.ItemCount.ToString(), inventoryPaymentPackageDetails.ItemCount == 1 ? " Inventory Item" : " Inventory Items");
                litInvCurrentCount.Text  = companyCurrentUsage.InventoryCount.ToString();
                divDefaultText.Visible   = false;
            }
            else
            {
                //Show the default message
                tblPlanMonitor.Visible = false;
                if (this.GetBL <CompanyBL>().IsFreeTrialCompany(this.CompanyId))
                {
                    paraFreeTrailIndication.Visible = true;
                }
            }
            if (Request.Browser.Type.Contains("Firefox"))  //firefox has a margin issue
            {
                btnViewPricingPlan.Style.Add("margin", "0px");
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string validationGroup = this.ID + "PaymentValGroup";
                if (DisplayMode == ViewMode.CompanyBilling)
                {
                    paymentSetupDetails.Visible = true;
                    pnlExpander.Visible         = false;

                    //Check for current package
                    CompanyPaymentPackage companyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
                    if (companyPaymentPackage == null)
                    {
                        lnkSetUp.Text        = "Select Pricing plan";
                        lnkSetUp.PostBackUrl = string.Format("~/Company/CompanyPricingPlans.aspx?companyid={0}", CompanyId);
                    }
                    else if (companyPaymentPackage.PaymentMethodCodeId == Utils.GetCodeIdByCodeValue("PaymentMethod", "INVOICE"))
                    {
                        litPackageStatus.Text        = "You have paid by Invoice";
                        litPackageStatus.Visible     = true;
                        divPaymentDetailsSet.Visible = litpipePaymentDetailsNotSet.Visible = litPaymentDetailsNotSet.Visible = lnkSetUp.Visible = lnkChange.Visible = false;
                    }
                }
                else if (DisplayMode == ViewMode.PricingPlan)
                {
                    paymentSetupDetails.Visible = true;
                    pnlPopup.Visible            = false;

                    // stop firing validations when click on the hide link.
                    lnkSetUp.CausesValidation  = false;
                    lnkChange.CausesValidation = false;
                }
                else
                {
                    paymentSetupDetails.Visible = false;
                }

                SetValidationGroup(validationGroup);
            }

            popupConfirmPaymentDetails.ID = this.ID + "popupConfirmPaymentDetails";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CompanyPaymentPackage companyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
                CompanyCurrentUsage   companyCurrentUsage   = this.GetBL <FinanceBL>().GetCompanyCurrentUsage(CompanyId, null);
                txtCurrentProjectCount.Value = companyCurrentUsage.ProjectCount;
                txtCurrentUserCount.Value    = companyCurrentUsage.UserCount;
                txtInvCurrentCount.Value     = companyCurrentUsage.InventoryCount;

                if (companyPaymentPackage != null)
                {
                    //This does not get NULL. 0 values as default

                    CompanyPaymentPackage futurePackage = this.GetBL <FinanceBL>().GetLatestRequestForTheCompany(CompanyId);

                    ProjectPaymentPackageDetails   projectPackageDetails          = Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(companyPaymentPackage.ProjectPaymentPackageTypeId);
                    InventoryPaymentPackageDetails inventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(companyPaymentPackage.InventoryPaymentPackageTypeId);

                    litActiveProjects.Text = string.Concat(projectPackageDetails.ProjectCount, projectPackageDetails.ProjectCount == 1 ? " Active Project" : " Active Projects");


                    if (this.GetBL <FinanceBL>().IsEducationalCompany(companyPaymentPackage))
                    {
                        litActiveUsers.Text = "Unlimited Users";
                    }
                    else
                    {
                        litActiveUsers.Text = string.Concat(projectPackageDetails.HeadCount, projectPackageDetails.HeadCount == 1 ? " Active User" : " Active Users");
                    }


                    litInventoryItems.Text = string.Concat(inventoryPaymentPackageDetails.ItemCount == null ? "Unlimited " : inventoryPaymentPackageDetails.ItemCount.ToString(), inventoryPaymentPackageDetails.ItemCount == 1 ? " Inventory Item" : " Inventory Items");
                }
                else
                {
                    const string NoPaymentPackageMsg = "No Payment Package";
                    litActiveProjects.Text = NoPaymentPackageMsg;
                    litActiveUsers.Text    = NoPaymentPackageMsg;
                    litInventoryItems.Text = NoPaymentPackageMsg;
                }
            }
        }
Esempio n. 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();
            }
        }
        /// <summary>
        /// Loads the data.
        /// </summary>
        public void LoadData()
        {
            //Load the selected package
            CompanyPaymentPackage companyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);

            if (companyPaymentPackage != null)
            {
                CurrentInventoryPaymentPackageTypeId = companyPaymentPackage.InventoryPaymentPackageTypeId;
                CurrentProjectPaymentPackageTypeId   = companyPaymentPackage.ProjectPaymentPackageTypeId;
                ProjectPaymentPackageTypeId          = companyPaymentPackage.ProjectPaymentPackageTypeId;
                InventoryPaymentPackageTypeId        = companyPaymentPackage.InventoryPaymentPackageTypeId;
                PaymentDurationTypeCodeId            = companyPaymentPackage.PaymentDurationCodeId;

                lblDuration.Text = Utils.GetCodeByCodeId(PaymentDurationTypeCodeId).Description.ToLower(CultureInfo.InvariantCulture);
            }

            divUpgradeNotice.Visible = companyPaymentPackage != null;

            SetReadOnlyRights();
            ConfigureDuration();
            LoadAllProjectPackages();
            LoadAllInventoryPackages();
            InformParent();
        }
Esempio n. 11
0
        /// <summary>
        /// Validates the package configurations.
        /// </summary>
        /// <param name="pricePlanDetails">The price plan details.</param>
        public void ValidatePackageConfigurations(PricePlanDetails pricePlanDetails)
        {
            PricePlanDetails = pricePlanDetails;

            if (!IsCompanyValidToSave())
            {
                return;
            }

            if (PricePlanDetails.ProjectPaymentPackageTypeId > 0 && PricePlanDetails.InventoryPaymentPackageTypeId > 0 && PricePlanDetails.PaymentDurationCodeId > 0)
            {
                ProjectPaymentPackageDetails   projectPackageDetails          = Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(PricePlanDetails.ProjectPaymentPackageTypeId);
                InventoryPaymentPackageDetails inventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(PricePlanDetails.InventoryPaymentPackageTypeId);
                //Get the current usage of the company. If exceeds the package show the error message
                string errorOnUsage = this.GetBL <FinanceBL>().GettheValidityOfSelectedPlan(CompanyId, pricePlanDetails, projectPackageDetails, inventoryPaymentPackageDetails);

                this.DisplayMode = ViewMode.PricingPlanPage; //concurrent discount chaged popups come on top of pricing plan page. view mode set accordingly.
                if (errorOnUsage.Length > 0)
                {
                    //Show the error message.
                    litError.Text = errorOnUsage;
                    popupError.ShowPopup();
                }
                else
                {
                    //Assign the InMemory Company object
                    if (CompanyId == 0)
                    {
                        paymentDetails.NewCompany = NewCompany;
                        paymentDetails.Media      = Media;
                    }

                    CompanyPaymentPackage oldCompanyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);

                    DateTime packageStartDate = Utils.Today;//For Normal company, the package start date should be Today.
                    //Find the package start date
                    if (this.GetBL <CompanyBL>().IsFreeTrialCompany(CompanyId))
                    {
                        //For Free Trial Companies, Start Date should be FT end Date + 1
                        packageStartDate = this.GetBL <CompanyBL>().GetFreeTrialProjectEndDate(CompanyId).AddDays(1);
                    }
                    else
                    {
                        if (oldCompanyPaymentPackage != null)
                        {
                            if (oldCompanyPaymentPackage.PaymentDurationCodeId == Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL"))
                            {
                                if (oldCompanyPaymentPackage.ProjectPaymentPackageTypeId != PricePlanDetails.ProjectPaymentPackageTypeId || oldCompanyPaymentPackage.InventoryPaymentPackageTypeId != PricePlanDetails.InventoryPaymentPackageTypeId)
                                {
                                    packageStartDate = Utils.Today;
                                }
                                else
                                {
                                    if (oldCompanyPaymentPackage.EndDate != null)
                                    {
                                        packageStartDate = oldCompanyPaymentPackage.EndDate.Value.AddDays(1);
                                    }
                                    else
                                    {
                                        packageStartDate = oldCompanyPaymentPackage.StartDate.AddYears(1).AddDays(1);
                                    }
                                }
                            }
                            else if (oldCompanyPaymentPackage.EndDate != null)
                            {
                                packageStartDate = oldCompanyPaymentPackage.EndDate.Value;
                            }
                        }
                    }
                    PricePlanDetails.PackageStartDate = packageStartDate;

                    OriginalLastUpdatedDate = oldCompanyPaymentPackage != null ? oldCompanyPaymentPackage.LastUpdateDate : null;

                    // No projects selected during free trial period
                    if (!HasRespondedToFreeTrailNoProjectsPopup && this.CompanyId > 0 && projectPackageDetails.Amount == 0 && GetBL <CompanyBL>().IsFreeTrialCompany(this.CompanyId))
                    {
                        ShowPopupForNoProjectsPackageSelectionDuringFreeTrail();
                    }
                    // free inventory scenario
                    else if ((projectPackageDetails.Amount + inventoryPaymentPackageDetails.Amount) == 0)
                    {
                        ShowFreeInventoryOnlyPopUp(inventoryPaymentPackageDetails.ItemCount.Value);
                    }
                    else if (HandleConcurrentDiscountChanges())
                    {
                        this.PricePlanDetails.DiscountCodeUsage = this.DiscountCodeUsage;
                        this.PricePlanDetails.DiscountCode      = (this.DiscountCodeUsage != null ? this.DiscountCodeUsage.DiscountCode : null);
                    }
                    else if (!HasRespondedToNoPackageChangesPopup && !this.GetBL <FinanceBL>().IsCompanyPaymentPackageChanged(this.CompanyId, pricePlanDetails))
                    {
                        ShowPopupNoPackageChanges();
                    }
                    else if (!PricePlanDetails.IsEducationalPackage && (PricePlanDetails.DiscountCodeUsage != null &&
                                                                        PricePlanDetails.DiscountCodeUsage.DiscountCode.Discount == 100 && PricePlanDetails.TotalAmountForPeriod == 0))
                    {
                        ShowHundredPercentDiscountPopUp(PricePlanDetails.DiscountCodeUsage);
                    }
                    else
                    {
                        ShowAdddetailsPaymentpopUp();
                    }
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Creates the company payment summary.
        /// </summary>
        /// <param name="amount">The amount.</param>
        /// <param name="nextCycleStartingDate">The next cycle starting date.</param>
        /// <param name="paymentSummaryDetail">The payment summary detail.</param>
        /// <param name="discountCodeUsage">The discount code usage.</param>
        /// <param name="fromDate">From date.</param>
        /// <param name="toDate">To date.</param>
        /// <param name="shouldMonthlyAgentProcessed">if set to <c>true</c> [should monthly agent processed].</param>
        /// <param name="paymentMethodCodeId">The payment method code identifier.</param>
        /// <param name="companyPaymentPackage">The company payment package.</param>
        /// <returns></returns>
        private static CompanyPaymentSummary CreateCompanyPaymentSummary(decimal amount, DateTime nextCycleStartingDate,
                                                                         PaymentSummaryDetails paymentSummaryDetail, DiscountCodeUsage discountCodeUsage,
                                                                         DateTime fromDate, DateTime toDate, bool shouldMonthlyAgentProcessed, int?paymentMethodCodeId, CompanyPaymentPackage companyPaymentPackage)
        {
            CompanyPaymentSummary companyPaymentSummary = new CompanyPaymentSummary()
            {
                CompanyId                      = paymentSummaryDetail.CompanyId,
                ShouldProcess                  = (paymentSummaryDetail.PaymentMethodCodeId != null && paymentSummaryDetail.ShouldProcess),
                IsMonthlyAgentProcessed        = shouldMonthlyAgentProcessed,
                CompanyPaymentPackage          = companyPaymentPackage,
                IsImmidiateFutureRecordCreated = false,
                Amount = decimal.Round((amount <= 0 ? 0 : amount), 2),
                NextPaymentCycleStartingDate = nextCycleStartingDate,
                FromDate            = fromDate,
                ToDate              = toDate,
                CreatedBy           = paymentSummaryDetail.UserId,
                LastUpdatedBy       = paymentSummaryDetail.UserId,
                CreatedDate         = Utils.Today,
                LastUpdatedDate     = Utils.Today,
                PaymentMethodCodeId = paymentMethodCodeId
            };

            if (!paymentSummaryDetail.IsEducationPackage && discountCodeUsage != null) //we should only include the discound usage to summary if the company is not educational
            {
                companyPaymentSummary.DiscountCodeUsageId = discountCodeUsage.DiscountCodeUsageId;
            }
            return(companyPaymentSummary);
        }
Esempio n. 13
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);
        }
Esempio n. 14
0
        /// <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
        }
Esempio n. 15
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.ApplicationException">You do not have administrator rights to view this page.</exception>
        protected void Page_Load(object sender, EventArgs e)
        {
            //Check for permissions
            if (!IsPostBack)
            {
                if (!Support.IsCompanyAdministrator(CompanyId))
                {
                    throw new ApplicationException("You do not have administrator rights to view this page.");
                }

                sbCompanyWarningDisplay.CompanyID = CompanyId;
                sbCompanyWarningDisplay.LoadData();
                sbFutureRequestNotificationMessage.CompanyId = CompanyId;
                sbFutureRequestNotificationMessage.LoadData();
                IsReadOnly = Support.IsReadOnlyRightsForPricingPlanPage(CompanyId);
                paymentPackageSummary.IsReadOnly  = IsReadOnly;
                paymentPackageSelector.IsReadOnly = IsReadOnly;
                btnNext.Enabled = !IsReadOnly;

                string companyName = Support.GetCompanyNameById(CompanyId);
                DisplayTitle = string.Format("Pricing Plans");
                LoadBreadCrumbs(companyName);

                //Display the Header Display Text
                //Check whether a Company has a payment package
                CompanyPaymentPackage companyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
                StringBuilder         textBuilder           = new StringBuilder();
                if (companyPaymentPackage == null)
                {
                    textBuilder.AppendFormat("<h2>{0}</h2> <br/>{1}", "Thanks for sticking around!", "To continue with StageBitz, please choose your Project level,<br/> and then your Inventory level.");
                }
                else
                {
                    textBuilder.AppendFormat("<h2>{0}</h2> <br/>{1}", "Need a new Plan? Have a Promotional Code?", "Just choose the Project and Inventory level that suits you best!");
                    paymentPackageSummary.IsEducationalPackage = this.GetBL <FinanceBL>().IsEducationalCompany(companyPaymentPackage);
                }

                if (GetBL <CompanyBL>().IsFreeTrialCompany(this.CompanyId))
                {
                    string freeTrailDurationText = string.Empty;
                    int    freeTrailDays         = int.Parse(Support.GetSystemValue("FreeTrialDays"));
                    if (freeTrailDays % 7 > 0)
                    {
                        freeTrailDurationText = string.Format("{0} days", freeTrailDays);
                    }
                    else
                    {
                        int freeTrailWeeks = freeTrailDays / 7;
                        freeTrailDurationText = string.Format("{0} weeks", freeTrailWeeks);
                    }

                    textBuilder.AppendFormat("<br /><br />{0}{1}{2}", "If you’re still in your Free Trial, you will not be charged until the <br/>end of the ", freeTrailDurationText, " trial period.");
                }

                lblMsg.Text     = textBuilder.ToString();
                btnNext.Enabled = (paymentPackageSelector.InventoryPaymentPackageTypeId != 0 && paymentPackageSelector.ProjectPaymentPackageTypeId != 0) && !IsReadOnly;
                paymentPackageSummary.CompanyId = CompanyId;

                lnkCreateNewProject.CompanyId = this.CompanyId;
                lnkCreateNewProject.LoadData();
                lnkCompanyInventory.HRef = string.Format("~/Inventory/CompanyInventory.aspx?companyid={0}", CompanyId);

                bool isReadOnly = this.GetBL <CompanyBL>().HasCompanySuspendedbySBAdmin(CompanyId) || this.GetBL <CompanyBL>().IsCompanyPaymentFailed(CompanyId);
                spnCreateNewProject.Visible = !isReadOnly;
            }

            paymentPackageSelector.InformParentToUpdate += delegate(int projectPaymentTypeId, int inventoryPaymentPackageTypeId, int paymentDurationTypeCodeId, bool hasAllpackagesSelected)//Subsucribe to the Informparent to update
            {
                paymentPackageSummary.ProjectPaymentPackageDetailId   = projectPaymentTypeId;
                paymentPackageSummary.InventoryPaymentPackageDetailId = inventoryPaymentPackageTypeId;
                paymentPackageSummary.PaymentDurationTypeCodeId       = paymentDurationTypeCodeId;
                paymentPackageSummary.UpdatePaymentSummary();
                btnNext.Enabled = hasAllpackagesSelected && !IsReadOnly;
                btnNext.ToolTip = IsReadOnly || hasAllpackagesSelected ? string.Empty : "Please select an option for both Project and Inventory";
                upnlPaymentPackage.Update();
            };

            paymentValidation.InformParentToUpdateValidation += delegate()
            {
                //paymentPackageSelector.LoadData();
                Response.Redirect(string.Format("~/Company/CompanyFinancialDetails.aspx?companyid={0}", CompanyId));
            };

            paymentValidation.InformDiscountChanged += delegate(DiscountCodeUsage discountCodeUsage)
            {
                paymentPackageSummary.DiscountCodeUsage = discountCodeUsage;
                paymentPackageSummary.UpdateDiscountCode(discountCodeUsage);
                paymentPackageSummary.UpdatePaymentSummary();
            };
        }
Esempio n. 16
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.ApplicationException">You do not have administrator rights to view this page.</exception>
        protected void Page_Load(object sender, EventArgs e)
        {
            //Check for permissions
            if (!IsPostBack)
            {
                if (!Support.IsCompanyAdministrator(CompanyId))
                {
                    throw new ApplicationException("You do not have administrator rights to view this page.");
                }

                string companyName = Support.GetCompanyNameById(CompanyId);

                lnkCreateNewProject.CompanyId = this.CompanyId;
                lnkCreateNewProject.LoadData();
                lnkFinancialHistory.HRef = string.Format("~/Company/CompanyFinanceHistory.aspx?companyid={0}", CompanyId);
                lnkCompanyInventory.HRef = string.Format("~/Inventory/CompanyInventory.aspx?companyid={0}", CompanyId);

                sbPackageLimitsValidation.CompanyId   = CompanyId;
                sbPackageLimitsValidation.DisplayMode = UserWeb.Controls.Company.PackageLimitsValidation.ViewMode.ReactivateProjects;
                sbPackageLimitsValidation.LoadData();

                bool isReadOnly = HasCompanySuspendedBySBAdmin || this.GetBL <CompanyBL>().IsCompanyPaymentFailed(CompanyId);
                spnCreateNewProject.Visible = !isReadOnly;
                LoadBreadCrumbs(companyName);

                gvProjects.DataBind();

                CompanyPaymentPackage currentPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
                if (currentPaymentPackage != null)
                {
                    int      anualDurationCodeId   = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");
                    int      monthlyDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "MONTHLY");
                    DateTime newPackageStartDate   = Utils.Today;
                    string   period             = string.Empty;
                    int      durationDifference = this.GetBL <FinanceBL>().GetDurationDifference(currentPaymentPackage.StartDate, Utils.Today, currentPaymentPackage.PaymentDurationCodeId);

                    if (currentPaymentPackage.PaymentDurationCodeId == anualDurationCodeId)
                    {
                        period = "Yearly";
                        newPackageStartDate = currentPaymentPackage.EndDate != null ? (DateTime)currentPaymentPackage.EndDate : (DateTime)currentPaymentPackage.StartDate.AddYears(durationDifference);
                    }
                    else
                    {
                        period = "Monthly";
                        newPackageStartDate = currentPaymentPackage.EndDate != null ? (DateTime)currentPaymentPackage.EndDate : (DateTime)currentPaymentPackage.StartDate.AddMonths(durationDifference);
                    }
                    CompanyBL companyBL = new CompanyBL(DataContext);
                    if (companyBL.IsFreeTrialStatusIncludedFortheDay(CompanyId, Utils.Today))
                    {
                        newPackageStartDate = currentPaymentPackage.StartDate;
                    }

                    if (newPackageStartDate == Utils.Today)
                    {
                        if (currentPaymentPackage.PaymentDurationCodeId == anualDurationCodeId)
                        {
                            newPackageStartDate = newPackageStartDate.AddYears(1);
                        }
                        else
                        {
                            newPackageStartDate = newPackageStartDate.AddMonths(1);
                        }
                    }
                    lblRenewsOn.Text              = Utils.FormatDate(newPackageStartDate);
                    lblSubscriptionPeriod.Text    = period;
                    divSubscriptionPeriod.Visible = true;
                    divRenewsOn.Visible           = true;
                }
                else
                {
                    divSubscriptionPeriod.Visible = false;
                    divRenewsOn.Visible           = false;
                }
                setUpCreditCardDetails.CompanyId    = CompanyId;
                setUpCreditCardDetails.RelatedTable = "Company";
                setUpCreditCardDetails.DisplayMode  = SetupCreditCardDetails.ViewMode.CompanyBilling;
                Data.CreditCardToken creditCardToken = this.GetBL <FinanceBL>().GetCreditCardToken(CompanyId);
                SetUISettings(creditCardToken);
                planMonitor.CompanyId = CompanyId;

                sbCompanyWarningDisplay.CompanyID = CompanyId;
                sbCompanyWarningDisplay.LoadData();
                sbFutureRequestNotificationMessage.CompanyId = CompanyId;
                sbFutureRequestNotificationMessage.LoadData();

                ConfigureCompanyStatus();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Handles the Click event of the btnConfirmHundredPercentDiscount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnConfirmHundredPercentDiscount_Click(object sender, EventArgs e)
        {
            if (!IsCompanyValidToSave())
            {
                popupHundredPercentDiscount.HidePopup();
                return;
            }

            this.DisplayMode = ViewMode.HundredPercentDiscount;    //concurrent discount chaged popups come on top of payment details popup. view mode set accordingly.
            if (HandleConcurrentDiscountChanges())
            {
                this.PricePlanDetails.DiscountCodeUsage = this.DiscountCodeUsage;
                this.PricePlanDetails.DiscountCode      = (this.DiscountCodeUsage != null ? this.DiscountCodeUsage.DiscountCode : null);
            }
            else
            {
                CompanyPaymentPackage oldCompanyPaymentPackage = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
                bool isInventoryPackageOrDurationChanged       = GetBL <FinanceBL>().HasInventryProjectOrDurationChanged(PricePlanDetails, oldCompanyPaymentPackage);
                //Handling concurrency (another admin changed the package concurrently)
                if (oldCompanyPaymentPackage != null && oldCompanyPaymentPackage.LastUpdateDate > OriginalLastUpdatedDate)
                {
                    StageBitzException.ThrowException(new ConcurrencyException(ExceptionOrigin.CompanyPaymentPackage, CompanyId));
                }
                else
                {
                    if (CompanyId == 0)
                    {
                        DataContext.Companies.AddObject(NewCompany);
                    }

                    this.GetBL <FinanceBL>().SaveCompanyPackage(UserID, oldCompanyPaymentPackage, PricePlanDetails, false);
                    //First check whether the applied Discount is valid. Because it can be either deleted, some one else being used, etc..
                    string errorMsg = string.Empty;
                    bool   isValid  = GetBL <FinanceBL>().IsDiscountCodeValidToUse(PricePlanDetails.DiscountCodeUsage.DiscountCode.Code, CompanyId, out errorMsg, PricePlanDetails.DiscountCodeUsage.DiscountCode);
                    if (isValid)
                    {
                        SaveDiscountCode();
                    }
                    this.GetBL <CompanyBL>().SaveChanges();

                    var    globalizationSection = WebConfigurationManager.GetSection("system.web/globalization") as GlobalizationSection;
                    string cultureName          = globalizationSection.Culture;
                    string authText             = string.Concat(String.Format("{0:P}", PricePlanDetails.DiscountCodeUsage.DiscountCode.Discount / 100), " discount code is applied.");

                    if (chkAcceptTermsDiscount.Visible)
                    {
                        this.GetBL <FinanceBL>().SendStageBitzAdminEmail(CompanyId == 0 ? NewCompany.CompanyId : CompanyId, UserID, PricePlanDetails, cultureName, string.Empty, authText, isInventoryPackageOrDurationChanged);
                    }

                    //Save the Company Profile image. First you need to save the Company to get the CompanyId.
                    if (CompanyId == 0 && Media != null)
                    {
                        Media.RelatedId = NewCompany.CompanyId;
                        DataContext.DocumentMedias.AddObject(Media);
                        this.GetBL <CompanyBL>().SaveChanges();
                    }
                }
                popupHundredPercentDiscount.HidePopup();
                btnChangesSaved.CommandArgument = "HundredDiscount";
                popupSaveChangesConfirm.ShowPopup();
            }
        }
        /// <summary>
        /// Validates this instance of User control.
        /// </summary>
        /// <param name="bulkUploadCount">The bulk upload count.</param>
        /// <returns></returns>
        public bool Validate(int?bulkUploadCount = null)
        {
            bool isValid = true;

            bool isFreeTrailCompany = GetBL <CompanyBL>().IsFreeTrialCompany(this.CompanyId);
            CompanyPaymentPackage          companyPaymentPackage          = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);
            ProjectPaymentPackageDetails   projectPaymentPackageDetails   = null;
            InventoryPaymentPackageDetails inventoryPaymentPackageDetails = null;

            if (companyPaymentPackage != null)
            {
                projectPaymentPackageDetails =
                    Utils.GetSystemProjectPackageDetailByPaymentPackageTypeId(companyPaymentPackage.ProjectPaymentPackageTypeId);
                inventoryPaymentPackageDetails =
                    Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(companyPaymentPackage.InventoryPaymentPackageTypeId);
            }

            CompanyCurrentUsage companyCurrentUsage = GetBL <FinanceBL>().GetCompanyCurrentUsage(CompanyId, null);

            switch (DisplayMode)
            {
            case ViewMode.CreateProjects:
                if (isFreeTrailCompany)
                {
                    if (GetBL <FinanceBL>().HasExceededProjectLimit(isFreeTrailCompany, projectPaymentPackageDetails, companyCurrentUsage))
                    {
                        if (companyPaymentPackage != null)
                        {
                            popupCheckProjectsLimits.ShowPopup(Z_Index);
                        }
                        else
                        {
                            popupCreateNewProjectsDuringFreeTrail.ShowPopup(Z_Index);
                        }

                        isValid = false;
                    }
                }
                else
                {
                    var discountUsage = this.GetBL <FinanceBL>().GetLatestDiscountCodeUsage(CompanyId);
                    ProjectPaymentPackageDetails freeProjectPackage = Utils.GetFreeSystemProjectPackageDetail();

                    if (companyPaymentPackage != null && (companyPaymentPackage.PaymentMethodCodeId.HasValue ||
                                                          (projectPaymentPackageDetails != null && projectPaymentPackageDetails.ProjectPaymentPackageDetailId == freeProjectPackage.ProjectPaymentPackageDetailId)))
                    {
                        if (GetBL <FinanceBL>().HasExceededProjectLimit(isFreeTrailCompany, projectPaymentPackageDetails, companyCurrentUsage))
                        {
                            popupCheckProjectsLimits.ShowPopup(Z_Index);
                            isValid = false;
                        }
                    }
                    else if (companyPaymentPackage == null)
                    {
                        if (GetBL <CompanyBL>().IsFreeTrialEndedCompany(this.CompanyId))
                        {
                            lblProjectLimitFreeTrailEnd.Visible = true;
                            lblProjectLimitNoPackage.Visible    = false;
                            popupCreateNewProjectsNoPricingPlan.ShowPopup(Z_Index);
                            isValid = false;
                        }
                        else
                        {
                            lblProjectLimitFreeTrailEnd.Visible = false;
                            lblProjectLimitNoPackage.Visible    = true;
                            popupCreateNewProjectsNoPricingPlan.ShowPopup(Z_Index);
                            isValid = false;
                        }
                    }
                    else if (!(companyPaymentPackage != null &&
                               (companyPaymentPackage.PaymentMethodCodeId.HasValue || discountUsage != null && discountUsage.DiscountCode.Discount == 100)) &&
                             (projectPaymentPackageDetails == null || projectPaymentPackageDetails.ProjectCount > 0))
                    {
                        lblReActivateProjectsNoPaymentDetails.Visible = true;
                        lblReActivateProjectsNoPricePlan.Visible      = false;
                        lblReActivateProjectsNoPaymentDetails.Text    = "To create a new Project you will need to setup your payment details.";
                        popupProjectsNoPricePlan.ShowPopup(Z_Index);
                        isValid = false;
                        break;
                    }
                }

                break;

            case ViewMode.ReactivateProjects:

                List <int> mustIncludeProjectIds = new List <int>();
                mustIncludeProjectIds.Add(this.ProjectId);
                companyCurrentUsage = GetBL <FinanceBL>().GetCompanyCurrentUsage(CompanyId, mustIncludeProjectIds);

                if (!isFreeTrailCompany)
                {
                    var discountUsage = this.GetBL <FinanceBL>().GetLatestDiscountCodeUsage(CompanyId);
                    if (!(companyPaymentPackage != null &&
                          (companyPaymentPackage.PaymentMethodCodeId.HasValue || discountUsage != null && discountUsage.DiscountCode.Discount == 100)) &&
                        (projectPaymentPackageDetails == null || projectPaymentPackageDetails.ProjectCount > 0))
                    {
                        lblReActivateProjectsNoPaymentDetails.Visible = companyPaymentPackage != null && !companyPaymentPackage.PaymentMethodCodeId.HasValue;
                        lblReActivateProjectsNoPricePlan.Visible      = companyPaymentPackage == null;

                        popupProjectsNoPricePlan.ShowPopup(Z_Index);
                        isValid = false;
                        break;
                    }
                }

                if (GetBL <FinanceBL>().HasExceededProjectLimit(isFreeTrailCompany, projectPaymentPackageDetails, companyCurrentUsage))
                {
                    popupCheckProjectsLimits.ShowPopup(Z_Index);
                    isValid = false;
                }
                else
                {
                    if (GetBL <FinanceBL>().HasExceededUserLimit(CompanyId, string.Empty, isFreeTrailCompany, companyPaymentPackage, projectPaymentPackageDetails, companyCurrentUsage, true))
                    {
                        lblPackageUserCount.Text         = projectPaymentPackageDetails.HeadCount.ToString(CultureInfo.InvariantCulture);
                        lnkPricingPlan.NavigateUrl       = string.Format("~/Company/CompanyPricingPlans.aspx?companyId={0}", CompanyId);
                        lnkManageProjectTeam.NavigateUrl = string.Format("~/Project/ProjectTeam.aspx?projectid={0}", this.ProjectId);
                        popupReActivateProjectsUserLimitExceeded.ShowPopup(Z_Index);
                        isValid = false;
                    }
                }

                break;

            case ViewMode.InventoryLimit:
                if (isFreeTrailCompany)
                {
                    if (GetBL <FinanceBL>().HasExceededInventoryLimit(isFreeTrailCompany, inventoryPaymentPackageDetails, companyCurrentUsage, bulkUploadCount))
                    {
                        if (companyPaymentPackage != null)
                        {
                            if (IsCompanyAdmin)
                            {
                                popupInventoryLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblInventoryLimitCompanyAdmin.Visible = true;
                                lblInventoryLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                            }
                            else
                            {
                                popupInventoryLimitInventoryManager.ShowPopup(Z_Index);
                                lblInventoryLimitInventoryManager.Visible = true;
                                lblInventoryLimitInventoryManagerFreeTrailEndNoPackage.Visible = false;
                            }
                        }
                        else
                        {
                            if (IsCompanyAdmin)
                            {
                                popupFreeTrailInventoryLimitCompanyAdmin.ShowPopup(Z_Index);
                            }
                            else
                            {
                                popupFreeTrailInventoryLimitInventoryManager.ShowPopup(Z_Index);
                            }
                        }

                        isValid = false;
                    }
                }
                else
                {
                    if (companyPaymentPackage != null)
                    {
                        if (GetBL <FinanceBL>().HasExceededInventoryLimit(isFreeTrailCompany, inventoryPaymentPackageDetails, companyCurrentUsage, bulkUploadCount))
                        {
                            if (IsCompanyAdmin)
                            {
                                popupInventoryLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblInventoryLimitCompanyAdmin.Visible = true;
                                lblInventoryLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                            }
                            else
                            {
                                popupInventoryLimitInventoryManager.ShowPopup(Z_Index);
                                lblInventoryLimitInventoryManager.Visible = true;
                                lblInventoryLimitInventoryManagerFreeTrailEndNoPackage.Visible = false;
                            }

                            isValid = false;
                        }
                    }
                    else
                    {
                        if (GetBL <CompanyBL>().IsFreeTrialEndedCompany(this.CompanyId))
                        {
                            if (IsCompanyAdmin)
                            {
                                popupInventoryLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblInventoryLimitCompanyAdmin.Visible = false;
                                lblInventoryLimitCompanyAdminFreeTrailEndNoPackage.Visible = true;
                                lblInventoryLimitCompanyAdminNoPackage.Visible             = false;
                            }
                            else
                            {
                                popupInventoryLimitInventoryManager.ShowPopup(Z_Index);
                                lblInventoryLimitInventoryManager.Visible = false;
                                lblInventoryLimitInventoryManagerFreeTrailEndNoPackage.Visible = true;
                                lblInventoryLimitInventoryManagerNoPackage.Visible             = false;
                            }

                            isValid = false;
                        }
                        else
                        {
                            if (IsCompanyAdmin)
                            {
                                popupInventoryLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblInventoryLimitCompanyAdmin.Visible = false;
                                lblInventoryLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                                lblInventoryLimitCompanyAdminNoPackage.Visible             = true;
                            }
                            else
                            {
                                popupInventoryLimitInventoryManager.ShowPopup(Z_Index);
                                lblInventoryLimitInventoryManager.Visible = false;
                                lblInventoryLimitInventoryManagerFreeTrailEndNoPackage.Visible = false;
                                lblInventoryLimitInventoryManagerNoPackage.Visible             = true;
                            }
                            isValid = false;
                        }
                    }
                }
                break;

            case ViewMode.UserLimit:
                if (isFreeTrailCompany)
                {
                    if (GetBL <FinanceBL>().HasExceededUserLimit(CompanyId, InvitedUserEmail, isFreeTrailCompany, companyPaymentPackage, projectPaymentPackageDetails, companyCurrentUsage))
                    {
                        if (companyPaymentPackage != null)
                        {
                            if (IsCompanyAdmin)
                            {
                                popupUserLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblUserLimitCompanyAdmin.Visible = true;
                                lblUserLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                            }
                            else
                            {
                                popupUserLimitProjectAdmin.ShowPopup(Z_Index);
                                lblUserLimitProjectAdmin.Visible = true;
                                lblUserLimitProjectAdminFreeTrailEndNoPackage.Visible = false;
                            }
                        }
                        else
                        {
                            if (IsCompanyAdmin)
                            {
                                popupFreeTrailUserLimitCompanyAdmin.ShowPopup(Z_Index);
                            }
                            else
                            {
                                popupFreeTrailUserLimitProjectAdmin.ShowPopup(Z_Index);
                            }
                        }

                        isValid = false;
                    }
                }
                else
                {
                    if (companyPaymentPackage != null)
                    {
                        if (GetBL <FinanceBL>().HasExceededUserLimit(CompanyId, InvitedUserEmail, isFreeTrailCompany, companyPaymentPackage, projectPaymentPackageDetails, companyCurrentUsage))
                        {
                            if (IsCompanyAdmin)
                            {
                                popupUserLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblUserLimitCompanyAdmin.Visible = true;
                                lblUserLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                            }
                            else
                            {
                                popupUserLimitProjectAdmin.ShowPopup(Z_Index);
                                lblUserLimitProjectAdmin.Visible = true;
                                lblUserLimitProjectAdminFreeTrailEndNoPackage.Visible = false;
                            }
                            isValid = false;
                        }
                    }
                    else
                    {
                        if (GetBL <CompanyBL>().IsFreeTrialEndedCompany(this.CompanyId))
                        {
                            if (IsCompanyAdmin)
                            {
                                popupUserLimitCompanyAdmin.ShowPopup(Z_Index);
                                lblUserLimitCompanyAdmin.Visible = false;
                                lblUserLimitCompanyAdminFreeTrailEndNoPackage.Visible = true;
                                lblUserLimitCompanyAdminNoPackage.Visible             = false;
                            }
                            else
                            {
                                popupUserLimitProjectAdmin.ShowPopup(Z_Index);
                                lblUserLimitProjectAdmin.Visible = false;
                                lblUserLimitProjectAdminFreeTrailEndNoPackage.Visible = true;
                                lblUserLimitProjectAdminNoPackage.Visible             = false;
                            }

                            isValid = false;
                        }
                        else
                        {
                            if (IsCompanyAdmin)
                            {
                                popupUserLimitCompanyAdmin.ShowPopup(Z_Index);

                                lblUserLimitCompanyAdmin.Visible = false;
                                lblUserLimitCompanyAdminFreeTrailEndNoPackage.Visible = false;
                                lblUserLimitCompanyAdminNoPackage.Visible             = true;
                            }
                            else
                            {
                                popupUserLimitProjectAdmin.ShowPopup(Z_Index);
                                lblUserLimitProjectAdmin.Visible = false;
                                lblUserLimitProjectAdminFreeTrailEndNoPackage.Visible = false;
                                lblUserLimitProjectAdminNoPackage.Visible             = true;
                            }
                            isValid = false;
                        }
                    }
                }

                break;
            }

            return(isValid);
        }
Esempio n. 19
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);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Saves the creadit fatzibra card token.
        /// </summary>
        /// <param name="ucCreditCardDetails">The credit card details control.</param>
        /// <param name="commit">if set to <c>true</c> [commit to database].</param>
        private void SaveCreaditCardToken(CreditCardDetails ucCreditCardDetails, bool commit)
        {
            // If credit card not validated
            if (Response == null)
            {
                ValidateCardDetails(ucCreditCardDetails);
            }

            if (Response != null && Response.Successful)
            {
                #region Update existing token details if available

                CreditCardToken creditCardToken = GetCreditCardToken();
                if (creditCardToken != null)
                {
                    creditCardToken.IsActive        = false;
                    creditCardToken.LastUpdatedBy   = UserID;
                    creditCardToken.LastUpdatedDate = Now;
                }

                #endregion Update existing token details if available

                #region Add New token details

                CreditCardToken newCreditCardToken = new CreditCardToken();
                newCreditCardToken.Token            = Utils.EncryptStringAES(Response.Result.ID);
                newCreditCardToken.CreatedBy        = UserID;
                newCreditCardToken.LastUpdatedBy    = UserID;
                newCreditCardToken.LastUpdatedDate  = Now;
                newCreditCardToken.CreatedDate      = Now;
                newCreditCardToken.IsActive         = true;
                newCreditCardToken.RelatedTableName = RelatedTable;
                newCreditCardToken.RelatedId        = CompanyId;
                creditCardNumber = ucCreditCardDetails.CreditCardNumber;
                newCreditCardToken.LastFourDigitsCreditCardNumber = Utils.EncryptStringAES(creditCardNumber.Substring(creditCardNumber.Length - 4));
                DataContext.CreditCardTokens.AddObject(newCreditCardToken);

                #endregion Add New token details

                #region Check the company status and reactivate it

                var company = GetBL <CompanyBL>().GetCompany(CompanyId);
                if (company != null)
                {
                    CompanyStatusHandler.CompanyWarningInfo warningInfo = CompanyStatusHandler.GetCompanyWarningStatus(CompanyId, company.CompanyStatusCodeId, company.ExpirationDate);
                    if (warningInfo.WarningStatus == CompanyStatusHandler.CompanyWarningStatus.SuspendedForNoPaymentOptions)
                    {
                        CompanyPaymentPackage companyPaymentPackage = GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(company.CompanyId);
                        companyPaymentPackage.PaymentMethodCodeId = Support.GetCodeIdByCodeValue("PaymentMethod", "CREDITCARD");
                        company.CompanyStatusCodeId = Support.GetCodeIdByCodeValue("CompanyStatus", "ACTIVE");

                        //update if there is summary for the period
                        CompanyPaymentSummary companyPaymentSummary = this.GetBL <FinanceBL>().GetPaymentSummaryToShouldProcess(company.CompanyId);
                        if (companyPaymentSummary != null)
                        {
                            companyPaymentSummary.ShouldProcess = true;
                        }
                    }
                }

                #endregion Check the company status and reactivate it

                if (commit)
                {
                    DataContext.SaveChanges();
                }

                ucCreditCardDetails.ClearValues();

                if (DisplayMode == ViewMode.CompanyBilling)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "HideDiv", "HidePaymentSuccessMessage();", true);
                }

                popupConfirmPaymentDetails.HidePopup();
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                if (Response != null && Response.Errors.Count > 0)
                {
                    sb.Append(string.Join("<br />", Response.Errors));
                    ucCreditCardDetails.SetNotification(sb.ToString().Length == 0 ? "Failed to set up payment details. Please verify the payment details and retry" : sb.ToString());
                }

                popupConfirmPaymentDetails.ShowPopup();
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Loads the data.
        /// </summary>
        public void LoadData()
        {
            if (CompanyId > 0)
            {
                Data.Company company = this.GetBL <CompanyBL>().GetCompany(CompanyId);
                CompanyStatusHandler.CompanyWarningInfo warningInfo = CompanyStatusHandler.GetCompanyWarningStatus(CompanyId, company.CompanyStatusCodeId, company.ExpirationDate);
                if (warningInfo.WarningStatus == CompanyStatusHandler.CompanyWarningStatus.NoWarning)
                {
                    var                   globalizationSection  = WebConfigurationManager.GetSection("system.web/globalization") as GlobalizationSection;
                    int                   anualDurationCodeId   = (int)Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL");
                    int                   monthlyDurationCodeId = Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "MONTHLY");
                    CompanyBL             companyBL             = new CompanyBL(DataContext);
                    CompanyPaymentPackage oldPackage            = this.GetBL <FinanceBL>().GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(CompanyId);

                    if (!((companyBL.IsFreeTrialStatusIncludedFortheDay(CompanyId, Utils.Today)) || oldPackage == null))  //free trial scenario and first time configuration. In this case no banners to display.
                    {
                        //comming from a popup. Refer PBI 14218.If user changes from yearly->monthly and downgrading or upgrading we should display banners in AC2,AC3.5. Else if it is a downgrade, display the banner in AC 3.4. If it is just an option change or upgrade with option change, then display banner in AC1.
                        if (PricePlanDetails != null)
                        {
                            divNotifyFutureRequest.Style.Add("Width", Width.ToString() + "px");

                            #region Calculations

                            int      durationDifference = this.GetBL <FinanceBL>().GetDurationDifference(oldPackage.StartDate, Utils.Today, oldPackage.PaymentDurationCodeId);
                            DateTime endDate            = Utils.Today;
                            DateTime newBillingDate     = Utils.Today;
                            DateTime virtualBillingDate = Utils.Today;
                            string   newOption          = PricePlanDetails.PaymentDurationCodeId == (int)Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL") ? "yearly" : "monthly";
                            string   currentOption      = oldPackage.PaymentDurationCodeId == (int)Utils.GetCodeIdByCodeValue("PaymentPackageDuration", "ANUAL") ? "yearly" : "monthly";

                            //In order to find whether it is an upgrade or downgrade,
                            decimal newAmount = this.GetBL <FinanceBL>().CalculateALLPackageAmountsByPeriod(PricePlanDetails.ProjectPaymentPackageTypeId, PricePlanDetails.InventoryPaymentPackageTypeId, oldPackage.PaymentDurationCodeId);
                            decimal oldAmount = this.GetBL <FinanceBL>().CalculateALLPackageAmountsByPeriod(oldPackage.ProjectPaymentPackageTypeId, oldPackage.InventoryPaymentPackageTypeId, oldPackage.PaymentDurationCodeId);
                            int     dayToRun  = int.Parse(Utils.GetSystemValue("MonthlyFinanceProcessDay"));

                            if (oldPackage.PaymentDurationCodeId == anualDurationCodeId)
                            {
                                endDate = oldPackage.EndDate != null ? (DateTime)oldPackage.EndDate : (DateTime)oldPackage.StartDate.AddYears(durationDifference);

                                if (PricePlanDetails.PaymentDurationCodeId == monthlyDurationCodeId)
                                {
                                    virtualBillingDate = new DateTime(endDate.Year, endDate.Month, dayToRun);
                                    newBillingDate     = virtualBillingDate > endDate ? virtualBillingDate : virtualBillingDate.AddMonths(1);
                                }
                            }
                            else
                            {
                                endDate = oldPackage.EndDate != null ? (DateTime)oldPackage.EndDate : (DateTime)oldPackage.StartDate.AddMonths(durationDifference);

                                if (PricePlanDetails.PaymentDurationCodeId == anualDurationCodeId)
                                {
                                    virtualBillingDate = new DateTime(endDate.Year, endDate.Month, dayToRun);
                                    newBillingDate     = virtualBillingDate > endDate ? virtualBillingDate : virtualBillingDate.AddMonths(1);
                                }
                            }

                            #endregion Calculations

                            #region creating banners

                            if (endDate == Utils.Today)
                            {
                                pnlNotifyFutureRequest.Visible = false;
                            }
                            else if (PricePlanDetails.PaymentDurationCodeId != oldPackage.PaymentDurationCodeId) //Duration change
                            {
                                string displayText = string.Empty;
                                if (PricePlanDetails.PaymentDurationCodeId == monthlyDurationCodeId && newAmount != oldAmount)
                                {
                                    if (newAmount < oldAmount)  //downgrade yearly->monthly
                                    {
                                        displayText = string.Format("<b>A little note on downgrades…</b> We’re glad you’ve found the levels that are right for you in StageBitz, but we do need to let you know that we can’t offer refunds, as Yearly subscriptions are paid in advance. " +
                                                                    "You’re currently paid up until {0}. Your choice will be effective immediately so if you would like to continue to enjoy the higher subscription level until that date please downgrade later." +
                                                                    " After that, we’ll change your billing to the lower level you’ve chosen. Your {1} charges will start on {2}.", Utils.FormatDate(endDate), newOption, Utils.FormatDate(newBillingDate));
                                    }
                                    else if (newAmount > oldAmount)  //upgrade yearly->monthly
                                    {
                                        PaymentSummaryDetails paymentSummaryDetail = this.GetBL <FinanceBL>().GetPaymentSummaryDetailRecord(PricePlanDetails, true);
                                        int     totalDays     = (int)(endDate - Utils.Today).TotalDays;
                                        decimal prorataAmount = ProjectUsageHandler.GetProrataAmount(paymentSummaryDetail, oldPackage, this.GetBL <FinanceBL>().GetLatestDiscountCodeUsage(CompanyId), newAmount, oldAmount, endDate, totalDays);

                                        StringBuilder upgradeText = new StringBuilder();
                                        upgradeText.Append(string.Format("You have selected to upgrade your plan and pay {0}. ", newOption));
                                        if (prorataAmount > 0)
                                        {
                                            upgradeText.Append(string.Format("You will be charged a pro-rata amount of {0} for your upgrade. ", Utils.FormatCurrency(prorataAmount, globalizationSection.Culture)));
                                        }
                                        upgradeText.Append(string.Format("Your {0} charges will start on {1}.", newOption, Utils.FormatDate(newBillingDate)));
                                        displayText = upgradeText.ToString();
                                    }
                                }
                                else
                                {
                                    if (newAmount < oldAmount)//even for monthly->yearly downgrade we should display downgrade banner
                                    {
                                        displayText = string.Format("<b>A little note on downgrades…</b> We’re glad you’ve found the levels that are right for you in StageBitz, but we do need to let you know that we can’t offer refunds, as subscriptions are paid in advance. " +
                                                                    "You’re currently paid up until {0}. Your choice will be effective immediately so if you would like to continue to enjoy the higher subscription level until that date please downgrade later.", Utils.FormatDate(endDate));
                                    }
                                    else//only an option change (yearly->monthly or monthly->yearly).Even if it is a monthly->yearly upgrade we display this banner.
                                    {
                                        displayText = string.Format("You are currently paying {0}, but you have opted to pay {1} as of {2}.",
                                                                    currentOption, newOption, Utils.FormatDate(endDate));
                                    }
                                }
                                divNotifyFutureRequest.InnerHtml = displayText;
                                pnlNotifyFutureRequest.Visible   = true;
                            }
                            else
                            {
                                if (newAmount < oldAmount)  //downgrade only.
                                {
                                    string downgradeOnlyText = string.Format("<b>A little note on downgrades…</b> We’re glad you’ve found the levels that are right for you in StageBitz, but we do need to let you know that we can’t offer refunds, as subscriptions are paid in advance. " +
                                                                             "You’re currently paid up until {0}. Your choice will be effective immediately so if you would like to continue to enjoy the higher subscription level until that date please downgrade later.", Utils.FormatDate(endDate));
                                    divNotifyFutureRequest.InnerHtml = downgradeOnlyText;
                                    pnlNotifyFutureRequest.Visible   = true;
                                }
                                else
                                {
                                    pnlNotifyFutureRequest.Visible = false;
                                }
                            }

                            #endregion creating banners
                        }
                        else  //Comming from company billing or price plan page
                        {
                            CompanyPaymentPackage futurePackage = this.GetBL <FinanceBL>().GetLatestRequestForTheCompany(CompanyId);
                            DateTime newDurationStartDate       = Utils.Today;
                            if (futurePackage != null && oldPackage != null && futurePackage.PaymentDurationCodeId != oldPackage.PaymentDurationCodeId)
                            {
                                string currentPaymentDuration = string.Empty;
                                string newPaymentDuration     = string.Empty;
                                int    durationDifference     = this.GetBL <FinanceBL>().GetDurationDifference(oldPackage.StartDate, Utils.Today, oldPackage.PaymentDurationCodeId);

                                if (oldPackage.PaymentDurationCodeId == anualDurationCodeId)
                                {
                                    currentPaymentDuration = "yearly";
                                    newPaymentDuration     = "monthly";
                                    newDurationStartDate   = oldPackage.EndDate != null ? (DateTime)oldPackage.EndDate : (DateTime)oldPackage.StartDate.AddMonths(durationDifference);
                                }
                                else
                                {
                                    currentPaymentDuration = "monthly";
                                    newPaymentDuration     = "yearly";
                                    newDurationStartDate   = oldPackage.EndDate != null ? (DateTime)oldPackage.EndDate : (DateTime)oldPackage.StartDate.AddYears(durationDifference);
                                }
                                string optionChangedText = string.Format("You are currently paying {0}, but you have opted to pay {1} as of {2}.", currentPaymentDuration, newPaymentDuration, Utils.FormatDate(newDurationStartDate));
                                divNotifyFutureRequest.InnerHtml = optionChangedText;
                                pnlNotifyFutureRequest.Visible   = true;
                            }
                            else
                            {
                                pnlNotifyFutureRequest.Visible = false;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 22
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);
        }