Exemplo n.º 1
0
  void Awake() {
    if (bm != null && bm != this) {
      Destroy(gameObject);
      return;
    }

    DontDestroyOnLoad(gameObject);
    bm = this;
  }
Exemplo n.º 2
0
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            UserAccount u = GetCorrectUser();
            long storeId = this.MTApp.CurrentStore.Id;

            var billManager = new BillingManager(this.MTApp);
            var response = billManager.CancelSubscription(this.MTApp.CurrentStore.StripeCustomerId);            
            MTApp.AccountServices.CancelStore(storeId, u.Id);
            Response.Redirect("http://www.merchanttribestores.com");
        }
Exemplo n.º 3
0
 public static Organization GenerateSampleOrganization(BillingManager billingManager, BillingPlans plans)
 {
     return(GenerateOrganization(billingManager, plans, id: TestConstants.OrganizationId, name: "Acme", inviteEmail: TestConstants.InvitedOrganizationUserEmail));
 }
Exemplo n.º 4
0
 public void GetBillingPlan()
 {
     Assert.Equal(BillingManager.FreePlan.Id, BillingManager.GetBillingPlan(BillingManager.FreePlan.Id).Id);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Handles the Click event of the btnPrint 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 btnPrint_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            /// <summary>
            /// The XSL document
            /// </summary>
            XmlDocument xslDoc;

            try
            {
                if (CurrentSession.Current.HasBilling && CurrentSession.Current.HasFeaturePermission("BILLING_CONFIGURATION"))
                {
                    xmlDoc = new XmlDocument();
                    string strfile = Server.MapPath("~/Billing/PriceList_1_0.xsl");

                    byte[] fileData = File.ReadAllBytes(strfile);

                    string strOut_XSL;

                    strOut_XSL = XmlEncodingBOM.GetBOMString(fileData);

                    xslDoc = new XmlDocument();

                    xslDoc.LoadXml(strOut_XSL);

                    // xmlDoc.LoadXml(docX.ToString());
                    DateTime?printPriceDate;

                    printPriceDate = textPriceListDate.Text.Trim() == "" ? DateTime.Now : DateTime.Parse(textPriceListDate.Text);
                    xmlDoc.LoadXml(BillingManager.GetPriceListXML(Session["AppLocation"].ToString(), Session["AppUserName"].ToString(), printPriceDate));
                    //Create an XML declaration.
                    XmlDeclaration xmldecl;
                    xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    //Add the new node to the document.
                    XmlElement root = xmlDoc.DocumentElement;
                    xmlDoc.InsertBefore(xmldecl, root);

                    Hashtable ht = new Hashtable()
                    {
                        { "data", xmlDoc.InnerXml }, { "style", strOut_XSL }
                    };

                    Session["ReportData"] = ht;
                    string strScript = @"<script language=""javascript"" type=""text/javascript"">
                        var w = screen.width - 60; var h = screen.height - 60; var winprops = ""location=no,scrollbars=yes,resizable=yes,status=no"";
                        var frmwin = window.open(""PrintPriceList.aspx?print=true"", ""PrintPriceList"", winprops);
                        if (parseInt(navigator.appVersion) >= 4) {
                            frmwin.window.focus();
                        }   </script>";
                    //mpePrintPriceList.Hide();
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "PrintReport", strScript, false);
                }
                else
                {
                    CurrentSession.Logout();
                    Response.Redirect("~/frmLogin.aspx?error=true");
                }
            }
            catch (Exception ex)
            {
                showErrorMessage(ref ex);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the price list.
        /// </summary>
        /// <param name="itemTypeID">The item type identifier.</param>
        /// <param name="searchText">The search text.</param>
        /// <param name="WithPriceOnly">if set to <c>true</c> [with price only].</param>
        /// <param name="page">The page.</param>
        /// <returns></returns>
        private ResultSet <SaleItem> GetPriceList(int itemTypeID, string searchText, bool _withPriceOnly, Pager page)
        {
            ResultSet <SaleItem> resultSet = BillingManager.GetPriceList(itemTypeID, null, searchText, _withPriceOnly, page);

            return(resultSet);
        }
 public ProjectController(IProjectRepository projectRepository, IOrganizationRepository organizationRepository, IEventRepository eventRepository, IQueue <WorkItemData> workItemQueue, BillingManager billingManager, SlackService slackService, IMapper mapper, IQueryValidator validator, ILoggerFactory loggerFactory) : base(projectRepository, mapper, validator, loggerFactory)
 {
     _organizationRepository = organizationRepository;
     _eventRepository        = eventRepository;
     _workItemQueue          = workItemQueue;
     _billingManager         = billingManager;
     _slackService           = slackService;
 }
        public async Task <IActionResult> ChangePlanAsync(string id, [FromQuery] string planId, [FromQuery] string stripeToken = null, [FromQuery] string last4 = null, [FromQuery] string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(NotFound());
            }

            if (!Settings.Current.EnableBilling)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Plans cannot be changed while billing is disabled.")));
            }

            var organization = await GetModelAsync(id, false);

            if (organization == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid OrganizationId.")));
            }

            var plan = BillingManager.GetBillingPlan(planId);

            if (plan == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid PlanId.")));
            }

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
            {
                return(Ok(ChangePlanResult.SuccessWithMessage("Your plan was not changed as you were already on the free plan.")));
            }

            // Only see if they can downgrade a plan if the plans are different.
            if (!String.Equals(organization.PlanId, plan.Id))
            {
                var result = await _billingManager.CanDownGradeAsync(organization, plan, CurrentUser);

                if (!result.Success)
                {
                    return(Ok(result));
                }
            }

            var customerService     = new StripeCustomerService(Settings.Current.StripeApiKey);
            var subscriptionService = new StripeSubscriptionService(Settings.Current.StripeApiKey);

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id))
                {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                    {
                        var subs = await subscriptionService.ListAsync(new StripeSubscriptionListOptions { CustomerId = organization.StripeCustomerId });

                        foreach (var sub in subs.Where(s => !s.CanceledAt.HasValue))
                        {
                            await subscriptionService.CancelAsync(sub.Id);
                        }
                    }

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                }
                else if (String.IsNullOrEmpty(organization.StripeCustomerId))
                {
                    if (String.IsNullOrEmpty(stripeToken))
                    {
                        return(Ok(ChangePlanResult.FailWithMessage("Billing information was not set.")));
                    }

                    organization.SubscribeDate = SystemClock.UtcNow;

                    var createCustomer = new StripeCustomerCreateOptions {
                        SourceToken = stripeToken,
                        PlanId      = planId,
                        Description = organization.Name,
                        Email       = CurrentUser.EmailAddress
                    };

                    if (!String.IsNullOrWhiteSpace(couponId))
                    {
                        createCustomer.CouponId = couponId;
                    }

                    var customer = await customerService.CreateAsync(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.Sources.TotalCount > 0)
                    {
                        organization.CardLast4 = customer.Sources.Data.First().Card.Last4;
                    }
                }
                else
                {
                    var update = new StripeSubscriptionUpdateOptions {
                        Items = new List <StripeSubscriptionItemUpdateOption> {
                            new StripeSubscriptionItemUpdateOption {
                                PlanId = planId
                            }
                        }
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken))
                    {
                        update.Source = stripeToken;
                        create.Source = stripeToken;
                        cardUpdated   = true;
                    }

                    var subscriptionList = await subscriptionService.ListAsync(new StripeSubscriptionListOptions { CustomerId = organization.StripeCustomerId });

                    var subscription = subscriptionList.FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        await subscriptionService.UpdateAsync(subscription.Id, update);
                    }
                    else
                    {
                        await subscriptionService.CreateAsync(organization.StripeCustomerId, planId, create);
                    }

                    await customerService.UpdateAsync(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = CurrentUser.EmailAddress
                    });

                    if (cardUpdated)
                    {
                        organization.CardLast4 = last4;
                    }

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                BillingManager.ApplyBillingPlan(organization, plan, CurrentUser);
                await _repository.SaveAsync(organization, o => o.Cache());

                await _messagePublisher.PublishAsync(new PlanChanged { OrganizationId = organization.Id });
            } catch (Exception ex) {
                using (_logger.BeginScope(new ExceptionlessState().Tag("Change Plan").Identity(CurrentUser.EmailAddress).Property("User", CurrentUser).SetHttpContext(HttpContext)))
                    _logger.LogCritical(ex, "An error occurred while trying to update your billing plan: {Message}", ex.Message);

                return(Ok(ChangePlanResult.FailWithMessage(ex.Message)));
            }

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }
        public IHttpActionResult ChangePlan(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(NotFound());
            }

            if (!Settings.Current.EnableBilling)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Plans cannot be changed while billing is disabled.")));
            }

            Organization organization = _repository.GetById(id);

            if (organization == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid OrganizationId.")));
            }

            BillingPlan plan = BillingManager.GetBillingPlan(planId);

            if (plan == null)
            {
                return(Ok(ChangePlanResult.FailWithMessage("Invalid PlanId.")));
            }

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
            {
                return(Ok(ChangePlanResult.SuccessWithMessage("Your plan was not changed as you were already on the free plan.")));
            }

            // Only see if they can downgrade a plan if the plans are different.
            string message;

            if (!String.Equals(organization.PlanId, plan.Id) && !_billingManager.CanDownGrade(organization, plan, ExceptionlessUser, out message))
            {
                return(Ok(ChangePlanResult.FailWithMessage(message)));
            }

            var customerService     = new StripeCustomerService();
            var subscriptionService = new StripeSubscriptionService();

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id))
                {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                    {
                        var subs = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                        foreach (var sub in subs)
                        {
                            subscriptionService.Cancel(organization.StripeCustomerId, sub.Id);
                        }
                    }

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                }
                else if (String.IsNullOrEmpty(organization.StripeCustomerId))
                {
                    if (String.IsNullOrEmpty(stripeToken))
                    {
                        return(Ok(ChangePlanResult.FailWithMessage("Billing information was not set.")));
                    }

                    organization.SubscribeDate = DateTime.Now;

                    var createCustomer = new StripeCustomerCreateOptions {
                        Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        },
                        PlanId      = planId,
                        Description = organization.Name,
                        Email       = ExceptionlessUser.EmailAddress
                    };

                    if (!String.IsNullOrWhiteSpace(couponId))
                    {
                        createCustomer.CouponId = couponId;
                    }

                    StripeCustomer customer = customerService.Create(createCustomer);

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.StripeCardList.StripeCards.Count > 0)
                    {
                        organization.CardLast4 = customer.StripeCardList.StripeCards[0].Last4;
                    }
                }
                else
                {
                    var update = new StripeSubscriptionUpdateOptions {
                        PlanId = planId
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken))
                    {
                        update.Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        };
                        create.Card = new StripeCreditCardOptions {
                            TokenId = stripeToken
                        };
                        cardUpdated = true;
                    }

                    var subscription = subscriptionService.List(organization.StripeCustomerId).FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        subscriptionService.Update(organization.StripeCustomerId, subscription.Id, update);
                    }
                    else
                    {
                        subscriptionService.Create(organization.StripeCustomerId, planId, create);
                    }

                    customerService.Update(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = ExceptionlessUser.EmailAddress
                    });

                    if (cardUpdated)
                    {
                        organization.CardLast4 = last4;
                    }

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                BillingManager.ApplyBillingPlan(organization, plan, ExceptionlessUser);
                _repository.Save(organization);
                _messagePublisher.Publish(new PlanChanged {
                    OrganizationId = organization.Id
                });
            } catch (Exception e) {
                Log.Error().Exception(e).Message("An error occurred while trying to update your billing plan: " + e.Message).Critical().Property("User", ExceptionlessUser).ContextProperty("HttpActionContext", ActionContext).Write();
                return(Ok(ChangePlanResult.FailWithMessage(e.Message)));
            }

            return(Ok(new ChangePlanResult {
                Success = true
            }));
        }
Exemplo n.º 10
0
 void Awake()
 {
     BillingManager.init();
 }
Exemplo n.º 11
0
 public WebHookController(IWebHookRepository repository, IProjectRepository projectRepository, BillingManager billingManager) : base(repository)
 {
     _projectRepository = projectRepository;
     _billingManager    = billingManager;
 }
Exemplo n.º 12
0
        private void BindPerUseBilling(DateTime period, int clientId)
        {
            gvRoom.DataSource = null;
            gvRoom.DataBind();

            //Create the list to contain all summary total for each organization
            //IList<UsageSummaryTotal> mylist = new List<UsageSummaryTotal>();

            DataTable SummaryTable = new DataTable();

            SummaryTable.Columns.Add("OrgID", typeof(int));
            SummaryTable.Columns.Add("OrgName", typeof(string));
            SummaryTable.Columns.Add("BillingTypeID", typeof(int));
            SummaryTable.Columns.Add("RoomTotal", typeof(double));
            SummaryTable.Columns.Add("ToolTotal", typeof(double));
            SummaryTable.Columns.Add("StoreTotal", typeof(double));

            double sumCost = 0.0;

            var dsReport = ContextBase.GetCacheData();

            gvRoom.DataSource = BillingManager.GetRoomCost(dsReport, period, clientId, SummaryTable, ref sumCost);
            gvRoom.DataBind();
            lblRoom2.Text = string.Format("Total lab usage fees: {0:C}", sumCost);

            DataTable dtCancelled = null;
            DataTable dtForgiven  = null;

            gvTool2.DataSource = BillingManager.GetToolCost(dsReport, period, clientId, SummaryTable, ref sumCost, dtCancelled, dtForgiven);
            gvTool2.DataBind();

            gvToolCancelled2.DataSource = dtCancelled;
            gvToolCancelled2.DataBind();

            gvToolForgiven2.DataSource = dtForgiven;
            gvToolForgiven2.DataBind();

            double cancelledCost;
            double forgivenCost;

            if (dtCancelled == null || dtCancelled.Rows.Count == 0)
            {
                cancelledCost = 0;
            }
            else
            {
                cancelledCost = Convert.ToDouble(dtCancelled.Compute("SUM(TotalCalcCost)", string.Empty));
            }

            if (dtForgiven == null || dtForgiven.Rows.Count == 0)
            {
                forgivenCost = 0;
            }
            else
            {
                forgivenCost = Convert.ToDouble(dtForgiven.Compute("SUM(TotalCalcCost)", string.Empty));
            }

            lblTool2.Text             = string.Format("Total tool usage fees: {0:C}", sumCost + cancelledCost);
            lblActivatedToolFee2.Text = string.Format("Sub Total: {0:C}", sumCost);
            lblCancelledToolFee2.Text = string.Format("Sub Total: {0:C}", cancelledCost);
            lblForgivenToolFee2.Text  = string.Format("Sub Total: {0:$#,##0.00;($#,##0.00)}", forgivenCost);

            //Store
            //gvStore2.DataSource = BillingManager.GetStoreCost(period, clientId, SummaryTable, sumCost);
            //gvStore2.DataBind();
            //lblStore2.Text = string.Format("Total store usage fees: {0:C}", sumCost);
            if (dtStore2.Rows.Count > 0)
            {
                foreach (DataRow r in SummaryTable.Rows)
                {
                    r["StoreTotal"] = dtStore2.Compute("SUM(CalcCost)", string.Format("OrgID = {0}", r["OrgID"]));

                    if (r["StoreTotal"] == null || r["StoreTotal"] == DBNull.Value)
                    {
                        r["StoreTotal"] = 0.0;
                    }
                }

                gvStore2.DataSource = dtStore2;
                gvStore2.DataBind();
                object sumobj;

                //2009-08-05 it's possible that a user bought stuff but didn't use the lab at all
                sumobj = SummaryTable.Compute("SUM(StoreTotal)", string.Empty);
                if (sumobj == null || sumobj == DBNull.Value)
                {
                    sumCost = 0.0;
                    //no lab usage, only store usage
                    sumobj = dtStore2.Compute("SUM(CalcCost)", string.Empty);
                    if (sumobj != null && sumobj != DBNull.Value)
                    {
                        sumCost = Convert.ToDouble(sumobj);
                    }
                }
                else
                {
                    sumCost = Convert.ToDouble(sumobj);
                }

                lblStore2.Text = string.Format("Total store usage fees: {0:C}", sumCost);
            }
            else
            {
                lblStore2.Text = "No store usage during period";

                foreach (DataRow r in SummaryTable.Rows)
                {
                    r["StoreTotal"] = 0.0;
                }
            }

            dlSummary2.DataSource = SummaryTable;
            dlSummary2.DataBind();
        }
	private void Awake() {
		mInstance = this;
		DontDestroyOnLoad(this);
	}
 public OrganizationMaintenanceWorkItemHandler(IOrganizationRepository organizationRepository, ICacheClient cacheClient, IMessageBus messageBus, BillingManager billingManager, ILoggerFactory loggerFactory = null) : base(loggerFactory)
 {
     _organizationRepository = organizationRepository;
     _billingManager         = billingManager;
     _lockProvider           = new CacheLockProvider(cacheClient, messageBus);
 }
Exemplo n.º 15
0
        public override FundingTypeDTO Perform()
        {
            var manager = new BillingManager(this.DbContext);

            return(manager.GetFundingTypeSupportedCurrencies(this.Id));
        }
        async void ButtonSubscribe_ClickedAsync(object sender, EventArgs e)
        {
            this.CustomActivityIndicator.IsRunning = true;
            string productDisclaimer;

            switch (Device.RuntimePlatform)
            {
            case Device.iOS:
                productDisclaimer = ViewModel.kAppleSubscriptionDisclaimer; break;

            case Device.Android:
                productDisclaimer = ViewModel.kAndroidSubscriptionDisclaimer; break;

            default:
                productDisclaimer = ""; break;
            }
            if (!ViewModel.User.IsSubscribed)
            {
                // needs subscribe to single first
                var product = await BillingManager.GetIAPBillingProductWithTypeAsync(EVeSubscriptionType.SingleSubscription);

                if (product.Success)
                {
                    var popupPage = new LabelButtonCancelPopupPage(StringSingleSubscription, "Subscribe now to get your 30 image slideshow of your very own photos! Images upload to your Tesla screen " +
                                                                   "in a matter of seconds directly from your mobile phone.\n\n", $"Pay {product.Product.LocalizedPrice}", productDisclaimer, "See Terms and Condition", 200)
                    {
                        PageDelegate = this
                    };
                    await Navigation.PushPopupAsync(popupPage);
                }
                else
                {
                    if (!String.IsNullOrEmpty(product.Message))
                    {
                        await DisplayAlert("Error", product.Message, "Ok");
                    }
                    else
                    {
                        await DisplayAlert("Error", "Oops, something went wrong. Please try again later.", "Ok");
                    }
                    return;
                }
            }
            else if (!ViewModel.User.HasMultipleSubscription)
            {
                // they already have single so they can opt for multiple
                var product = await BillingManager.GetIAPBillingProductWithTypeAsync(EVeSubscriptionType.AdditionalSubscription);

                if (product.Success)
                {
                    var popupPage = new LabelButtonCancelPopupPage(StringAdditionalSubscription, "Get 2 additional slideshows for your Tesla Screen! " +
                                                                   "Use additional slideshows for family, business, or specific events.\n\n" + productDisclaimer, $"Buy for {product.Product.LocalizedPrice}", "See Terms and Condition", productDisclaimer, 200)
                    {
                        PageDelegate = this
                    };
                    await Navigation.PushPopupAsync(popupPage);
                }
                else
                {
                    if (!String.IsNullOrEmpty(product.Message))
                    {
                        await DisplayAlert("Error", product.Message, "Ok");
                    }
                    else
                    {
                        await DisplayAlert("Error", "Oops, something went wrong. Please try again later.", "Ok");
                    }
                    return;
                }
            }
            else
            {
                // they already have both memberships
                await DisplayAlert("Subscription", "You already have full access", "Ok");
            }
            this.CustomActivityIndicator.IsRunning = false;
        }
Exemplo n.º 17
0
 public AccountController(IMembershipProvider membership, IOrganizationRepository organizationRepository, IProjectRepository projectRepository, IUserRepository userRepository, BillingManager billingManager, NotificationSender notificationSender, IMailer mailer, DataHelper dataHelper)
 {
     _membershipProvider     = membership;
     _organizationRepository = organizationRepository;
     _projectRepository      = projectRepository;
     _userRepository         = userRepository;
     _billingManager         = billingManager;
     _notificationSender     = notificationSender;
     _mailer     = mailer;
     _dataHelper = dataHelper;
 }
Exemplo n.º 18
0
 public AdminController(IOrganizationRepository repository, BillingManager billingManager, IMessagePublisher messagePublisher)
 {
     _repository       = repository;
     _billingManager   = billingManager;
     _messagePublisher = messagePublisher;
 }
Exemplo n.º 19
0
        public StackController(IStackRepository stackRepository, IOrganizationRepository organizationRepository, IProjectRepository projectRepository, IQueue <WorkItemData> workItemQueue, IWebHookRepository webHookRepository, WebHookDataPluginManager webHookDataPluginManager, IQueue <WebHookNotification> webHookNotificationQueue, ICacheClient cacheClient, EventStats eventStats, BillingManager billingManager, FormattingPluginManager formattingPluginManager, ILoggerFactory loggerFactory, IMapper mapper) : base(stackRepository, loggerFactory, mapper)
        {
            _stackRepository          = stackRepository;
            _organizationRepository   = organizationRepository;
            _projectRepository        = projectRepository;
            _workItemQueue            = workItemQueue;
            _webHookRepository        = webHookRepository;
            _webHookDataPluginManager = webHookDataPluginManager;
            _webHookNotificationQueue = webHookNotificationQueue;
            _cacheClient             = cacheClient;
            _eventStats              = eventStats;
            _billingManager          = billingManager;
            _formattingPluginManager = formattingPluginManager;

            AllowedFields.AddRange(new[] { "first", "last" });
        }
 public OrganizationController(IOrganizationRepository organizationRepository, ICacheClient cacheClient, IUserRepository userRepository, IProjectRepository projectRepository, BillingManager billingManager, ProjectController projectController, IMailer mailer, IMessagePublisher messagePublisher, EventStats stats) : base(organizationRepository)
 {
     _cacheClient       = cacheClient;
     _userRepository    = userRepository;
     _projectRepository = projectRepository;
     _billingManager    = billingManager;
     _projectController = projectController;
     _mailer            = mailer;
     _messagePublisher  = messagePublisher;
     _stats             = stats;
 }
Exemplo n.º 21
0
 public StackController(IErrorStackRepository repository, IOrganizationRepository organizationRepository, IProjectRepository projectRepository,
                        IProjectHookRepository projectHookRepository, IMessageFactory messageFactory, BillingManager billingManager, NotificationSender notificationSender, DataHelper dataHelper)
     : base(repository)
 {
     _organizationRepository = organizationRepository;
     _projectRepository      = projectRepository;
     _projectHookRepository  = projectHookRepository;
     _messageFactory         = messageFactory;
     _billingManager         = billingManager;
     _notificationSender     = notificationSender;
     _dataHelper             = dataHelper;
 }
Exemplo n.º 22
0
 public ProjectController(IProjectRepository projectRepository, OrganizationRepository organizationRepository, BillingManager billingManager, DataHelper dataHelper, EventStats stats) : base(projectRepository)
 {
     _organizationRepository = organizationRepository;
     _billingManager         = billingManager;
     _dataHelper             = dataHelper;
     _stats = stats;
 }
Exemplo n.º 23
0
        private void GoToPlan(int planId)
        {
            var user        = GetCorrectUser();
            var store       = MTApp.CurrentStore;
            var billManager = new BillingManager(this.MTApp);

            if (store.Id == (long)planId)
            {
                this.MessageBox1.ShowInformation("You selected the same plan you're currently on. No change required.");
                return;
            }

            // Make sure you don't have too many items to downgrade
            if (!CheckMax(planId))
            {
                return;
            }

            if (store.StripeCustomerId.Trim().Length > 0)
            {
                if (planId == 0)
                {
                    billManager.CancelSubscription(store.StripeCustomerId);
                    MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp);
                    Response.Redirect("ChangePlan.aspx?ok=1");
                }

                var updateRequest = new UpdateCustomerRequest();
                updateRequest.CustomerId = store.StripeCustomerId;
                updateRequest.PlanId     = TranslatePlanId(planId);

                var updateResponse = billManager.UpdateCustomer(updateRequest);
                if (!updateResponse.Success)
                {
                    this.MessageBox1.ShowWarning("Unable to update plan: " + updateResponse.Message);
                    return;
                }
                if (!MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp))
                {
                    this.MessageBox1.ShowWarning("Unable to change plans! Check with support.");
                    return;
                }

                Response.Redirect("ChangePlan.aspx?ok=1");
            }
            else
            {
                var createRequest = new CreateCustomerRequest();
                createRequest.CreditCard = this.CreditCardInput1.GetCardData();
                createRequest.PostalCode = this.txtZipCode.Text;
                createRequest.PlanId     = TranslatePlanId(planId);
                createRequest.Name       = store.Id + " - " + store.StoreName;
                createRequest.Email      = user.Email.Replace("@", "+store" + store.Id + "@");

                var createResponse = billManager.CreateCustomer(createRequest);
                if (!createResponse.Success)
                {
                    this.MessageBox1.ShowWarning("Unable to change plans: " + createResponse.Message);
                    return;
                }

                // Save customer subscription id
                store.StripeCustomerId = createResponse.NewCustomerId;
                MTApp.UpdateCurrentStore();

                // Change plan in MerchantTribe
                MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp);
                Response.Redirect("ChangePlan.aspx?ok=1");
            }
        }
Exemplo n.º 24
0
 public WebHookController(IWebHookRepository repository, IProjectRepository projectRepository, BillingManager billingManager, IMapper mapper, QueryValidator validator, ILoggerFactory loggerFactory) : base(repository, mapper, validator, loggerFactory)
 {
     _projectRepository = projectRepository;
     _billingManager    = billingManager;
 }
Exemplo n.º 25
0
        public async Task <ActionResult <Invoice> > GetInvoiceAsync(string id)
        {
            if (!Settings.Current.EnableBilling)
            {
                return(NotFound());
            }

            if (!id.StartsWith("in_"))
            {
                id = "in_" + id;
            }

            StripeInvoice stripeInvoice = null;

            try {
                var invoiceService = new StripeInvoiceService(Settings.Current.StripeApiKey);
                stripeInvoice = await invoiceService.GetAsync(id);
            } catch (Exception ex) {
                using (_logger.BeginScope(new ExceptionlessState().Tag("Invoice").Identity(CurrentUser.EmailAddress).Property("User", CurrentUser).SetHttpContext(HttpContext)))
                    _logger.LogError(ex, "An error occurred while getting the invoice: {InvoiceId}", id);
            }

            if (String.IsNullOrEmpty(stripeInvoice?.CustomerId))
            {
                return(NotFound());
            }

            var organization = await _repository.GetByStripeCustomerIdAsync(stripeInvoice.CustomerId);

            if (organization == null || !CanAccessOrganization(organization.Id))
            {
                return(NotFound());
            }

            var invoice = new Invoice {
                Id               = stripeInvoice.Id.Substring(3),
                OrganizationId   = organization.Id,
                OrganizationName = organization.Name,
                Date             = stripeInvoice.Date.GetValueOrDefault(),
                Paid             = stripeInvoice.Paid,
                Total            = stripeInvoice.Total / 100.0m
            };

            foreach (var line in stripeInvoice.StripeInvoiceLineItems.Data)
            {
                var item = new InvoiceLineItem {
                    Amount = line.Amount / 100.0m
                };

                if (line.Plan != null)
                {
                    string planName = line.Plan.Nickname ?? BillingManager.GetBillingPlan(line.Plan.Id)?.Name;
                    item.Description = $"Exceptionless - {planName} Plan ({(line.Plan.Amount / 100.0):c}/{line.Plan.Interval})";
                }
                else
                {
                    item.Description = line.Description;
                }

                item.Date = $"{(line.StripePeriod.Start ?? stripeInvoice.PeriodStart).ToShortDateString()} - {(line.StripePeriod.End ?? stripeInvoice.PeriodEnd).ToShortDateString()}";
                invoice.Items.Add(item);
            }

            var coupon = stripeInvoice.StripeDiscount?.StripeCoupon;

            if (coupon != null)
            {
                if (coupon.AmountOff.HasValue)
                {
                    decimal discountAmount = coupon.AmountOff.GetValueOrDefault() / 100.0m;
                    string  description    = $"{coupon.Id} ({discountAmount.ToString("C")} off)";
                    invoice.Items.Add(new InvoiceLineItem {
                        Description = description, Amount = discountAmount
                    });
                }
                else
                {
                    decimal discountAmount = (stripeInvoice.Subtotal / 100.0m) * (coupon.PercentOff.GetValueOrDefault() / 100.0m);
                    string  description    = $"{coupon.Id} ({coupon.PercentOff.GetValueOrDefault()}% off)";
                    invoice.Items.Add(new InvoiceLineItem {
                        Description = description, Amount = discountAmount
                    });
                }
            }

            return(Ok(invoice));
        }
 public OrganizationController(IOrganizationRepository organizationRepository, ICacheClient cacheClient, IEventRepository eventRepository, IUserRepository userRepository, IProjectRepository projectRepository, IQueue <WorkItemData> workItemQueue, BillingManager billingManager, IMailer mailer, IMessagePublisher messagePublisher, IMapper mapper, IQueryValidator validator, ILoggerFactory loggerFactory) : base(organizationRepository, mapper, validator, loggerFactory)
 {
     _cacheClient       = cacheClient;
     _eventRepository   = eventRepository;
     _userRepository    = userRepository;
     _projectRepository = projectRepository;
     _workItemQueue     = workItemQueue;
     _billingManager    = billingManager;
     _mailer            = mailer;
     _messagePublisher  = messagePublisher;
 }
Exemplo n.º 27
0
 public ProjectController(IProjectRepository projectRepository, OrganizationRepository organizationRepository, DataHelper dataHelper, BillingManager billingManager) : base(projectRepository)
 {
     _organizationRepository = organizationRepository;
     _billingManager         = billingManager;
     _dataHelper             = dataHelper;
 }
Exemplo n.º 28
0
        /// <summary>
        /// Handles the Click event of the buttonSave 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 buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                int itemTypeID = this.SelectedItemType;
                // Get the data from the db for conflict checking
                Pager page = new Pager()
                {
                    PageCount = this.ItemsPerPage, PageIndex = this.PageIndex
                };
                ResultSet <SaleItem> resultSet = this.GetPriceList(this.SelectedItemType, this.SearchText, this.ShowPricedOnly, page);

                List <SaleItem> currentSet   = resultSet.Items;
                List <SaleItem> submittedSet = new List <SaleItem>();
                foreach (GridViewRow gridRow in gridPriceList.Rows)
                {
                    //ItemID,ItemTypeID,VersionStamp

                    int    itemId     = Convert.ToInt32(gridPriceList.DataKeys[gridRow.RowIndex].Values["ItemID"].ToString());
                    int    itemTypeId = Convert.ToInt32(gridPriceList.DataKeys[gridRow.RowIndex].Values["ItemTypeID"].ToString());
                    UInt64?_version   = null;
                    string vst        = "";
                    try { vst = (gridPriceList.DataKeys[gridRow.RowIndex].Values["VersionStamp"].ToString()); }
                    catch { }
                    if (vst != "")
                    {
                        _version = Convert.ToUInt64(vst);
                    }
                    TextBox txtPrice = gridRow.FindControl("textPrice") as TextBox;
                    if (txtPrice.Text.Trim() == "")
                    {
                        continue;
                    }

                    Label lblPrice = gridRow.FindControl("labelPrice") as Label;

                    TextBox txtPriceDate = gridRow.FindControl("textPriceDate") as TextBox;

                    Label lblPriceDate = gridRow.FindControl("labelPriceDate") as Label;

                    Label lblPriceType = gridRow.FindControl("labelPriceType") as Label;

                    DropDownList ddlPriceMode     = null;
                    bool         pricePerItem     = true;
                    bool         priceModeChanged = false;
                    if (this.ddlItemType.SelectedItem.Text == "Pharmaceuticals")
                    {
                        ddlPriceMode     = gridRow.FindControl("ddlPriceType") as DropDownList;
                        pricePerItem     = ddlPriceMode.SelectedValue == "Item";
                        priceModeChanged = ddlPriceMode.SelectedValue != lblPriceType.Text;
                    }
                    CheckBox chk    = gridRow.FindControl("chkDelete") as CheckBox;
                    bool     active = true;
                    if (chk != null)
                    {
                        if (chk.Enabled)
                        {
                            active = !chk.Checked;
                        }
                    }

                    decimal?newPrice;
                    newPrice = decimal.Parse(txtPrice.Text);
                    DateTime?newPriceDate;

                    newPriceDate = txtPriceDate.Text.Trim() == "" ? DateTime.Now : DateTime.Parse(txtPriceDate.Text);
                    bool hasChanged   = false;
                    bool priceChanged = txtPrice.Text != lblPrice.Text;

                    bool priceDateChanged = lblPriceDate.Text != txtPriceDate.Text;

                    if ((priceChanged || priceModeChanged) && !priceDateChanged)
                    {
                        hasChanged = false;
                    }
                    else if ((priceChanged || priceModeChanged) && priceDateChanged)
                    {
                        hasChanged = true;
                    }
                    else if (!active)
                    {
                        hasChanged = true;
                    }

                    if (hasChanged)
                    {
                        submittedSet.Add(new SaleItem
                        {
                            ItemId        = itemId,
                            ItemTypeId    = itemTypeId,
                            VersionStamp  = _version,
                            PriceDate     = newPriceDate,
                            SellingPrice  = newPrice,
                            PricedPerItem = pricePerItem,
                            Active        = active
                        });
                    }
                    // var _it = currentSet
                    //    .Where(fr => fr.ItemID == itemId && fr.ItemTypeID == itemTypeId ).FirstOrDefault();
                }
                //get only those items that has  been updated
                var changedSet = (from cs in currentSet
                                  join ss in submittedSet on cs.ItemId equals ss.ItemId
                                  where cs.ItemTypeId == ss.ItemTypeId && cs.VersionStamp == ss.VersionStamp
                                  &&
                                  (cs.SellingPrice != ss.SellingPrice || cs.PriceDate != ss.PriceDate || cs.PricedPerItem != ss.PricedPerItem || cs.Active != ss.Active)
                                  select new SaleItem
                {
                    ItemId = cs.ItemId,
                    ItemTypeId = cs.ItemTypeId,
                    PriceDate = ss.PriceDate,
                    PricedPerItem = ss.PricedPerItem,
                    SellingPrice = ss.SellingPrice,
                    VersionStamp = cs.VersionStamp,
                    Active = ss.Active
                }
                                  ).ToList <SaleItem>();
                int    itemCount     = changedSet.Count;
                string resultMessage = "No items were updated";
                if (itemCount > 0)
                {
                    int result = BillingManager.SavePriceList(changedSet, this.UserId);
                    if (result == itemCount)
                    {
                        resultMessage = "All items have been saved successfully";
                    }
                    else if (result == 0)
                    {
                        resultMessage = "No items were updated";
                    }
                    else if (result < itemCount && result > 0)
                    {
                        resultMessage = "Some items were not saved";
                    }
                }
                this.PopulatePriceList();
                IQCareMsgBox.NotifyAction(resultMessage, "Price Configuration", false, this, "");
                return;
            }
            catch (Exception ex)
            {
                this.showErrorMessage(ref ex);
            }
        }
Exemplo n.º 29
0
 public ProjectController(IUserRepository userRepository, IProjectRepository projectRepository, OrganizationRepository organizationRepository, BillingManager billingManager, NotificationSender notificationSender)
 {
     _userRepository         = userRepository;
     _projectRepository      = projectRepository;
     _organizationRepository = organizationRepository;
     _billingManager         = billingManager;
     _notificationSender     = notificationSender;
 }
Exemplo n.º 30
0
 public ProjectController(IProjectRepository projectRepository, IOrganizationRepository organizationRepository, IQueue <WorkItemData> workItemQueue, BillingManager billingManager, EventStats stats, ILoggerFactory loggerFactory, IMapper mapper) : base(projectRepository, loggerFactory, mapper)
 {
     _organizationRepository = organizationRepository;
     _workItemQueue          = workItemQueue;
     _billingManager         = billingManager;
     _stats = stats;
 }
Exemplo n.º 31
0
        public override void UpdateDocument(MongoCollection <BsonDocument> collection, BsonDocument document)
        {
            if (document.Contains("ErrorCount"))
            {
                document.ChangeName("ErrorCount", "EventCount");
            }

            if (document.Contains("TotalErrorCount"))
            {
                document.ChangeName("TotalErrorCount", "TotalEventCount");
            }

            if (document.Contains("LastErrorDate"))
            {
                document.ChangeName("LastErrorDate", "LastEventDate");
            }

            if (document.Contains("MaxErrorsPerDay"))
            {
                int maxErrorsPerDay        = -1;
                var maxErrorsPerDayElement = document.GetValue("MaxErrorsPerDay");
                if (maxErrorsPerDayElement.IsInt32)
                {
                    maxErrorsPerDay = maxErrorsPerDayElement.AsInt32;
                }
                else if (maxErrorsPerDayElement.IsInt64)
                {
                    maxErrorsPerDay = (int)maxErrorsPerDayElement.AsInt64;
                }

                document.Set("MaxEventsPerMonth", maxErrorsPerDay > 0 ? maxErrorsPerDay * 30 : -1);
                document.Remove("MaxErrorsPerDay");
            }

            if (document.Contains("MaxErrorsPerMonth"))
            {
                document.ChangeName("MaxErrorsPerMonth", "MaxEventsPerMonth");
            }

            if (document.Contains("SuspensionCode"))
            {
                var value = document.GetValue("SuspensionCode");
                document.Remove("SuspensionCode");

                SuspensionCode suspensionCode;
                if (value.IsString && Enum.TryParse(value.AsString, true, out suspensionCode))
                {
                    document.Set("SuspensionCode", suspensionCode);
                }
            }

            if (document.Contains("PlanId"))
            {
                string planId      = document.GetValue("PlanId").AsString;
                var    currentPlan = BillingManager.GetBillingPlan(planId);

                document.Set("PlanName", currentPlan != null ? currentPlan.Name : planId);
                document.Set("PlanDescription", currentPlan != null ? currentPlan.Description : planId);
            }

            collection.Save(document);
        }
 public OrganizationController(IOrganizationRepository organizationRepository, IUserRepository userRepository, IProjectRepository projectRepository, BillingManager billingManager, ProjectController projectController, IMailer mailer) : base(organizationRepository)
 {
     _userRepository    = userRepository;
     _projectRepository = projectRepository;
     _billingManager    = billingManager;
     _projectController = projectController;
     _mailer            = mailer;
 }
Exemplo n.º 33
0
 public GeoTests(ServicesFixture fixture, ITestOutputHelper output) : base(fixture, output)
 {
     _billingManager = GetService <BillingManager>();
     _plans          = GetService <BillingPlans>();
     _options        = GetService <AppOptions>();
 }
Exemplo n.º 34
0
        protected void btnUpdateCreditCard_Click(object sender, EventArgs e)
        {
            if (!this.CreditCardInput1.IsValid())
            {
                this.MessageBox1.ShowWarning("Please check your credit card information is valid before attempting to update.");
                return;
            }

            UserAccount u = GetCorrectUser();
            
            var billManager = new BillingManager(this.MTApp);

            var updateRequest = new UpdateCustomerRequest();
            updateRequest.CreditCard = this.CreditCardInput1.GetCardData();
            updateRequest.CustomerId = this.MTApp.CurrentStore.StripeCustomerId;
            updateRequest.PostalCode = this.txtZipCode.Text.Trim();

            var res = billManager.UpdateCustomer(updateRequest);
            if (!res.Success)
            {
                this.MessageBox1.ShowWarning("Unable to update card: " + res.Message);
                return;
            }

            this.MessageBox1.ShowOk("Credit card information updated!");                        
        }
Exemplo n.º 35
0
        private void GoToPlan(int planId)
        {
            var user = GetCorrectUser();
            var store = MTApp.CurrentStore;
            var billManager = new BillingManager(this.MTApp);

            if (store.Id == (long)planId)
            {
                this.MessageBox1.ShowInformation("You selected the same plan you're currently on. No change required.");
                return;
            }

            // Make sure you don't have too many items to downgrade
            if (!CheckMax(planId)) return;
                        
            if (store.StripeCustomerId.Trim().Length > 0)
            {
                if (planId == 0)
                {
                    billManager.CancelSubscription(store.StripeCustomerId);                    
                    MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp);
                    Response.Redirect("ChangePlan.aspx?ok=1");                                    
                }

                var updateRequest = new UpdateCustomerRequest();
                updateRequest.CustomerId = store.StripeCustomerId;
                updateRequest.PlanId = TranslatePlanId(planId);

                var updateResponse = billManager.UpdateCustomer(updateRequest);
                if (!updateResponse.Success)
                {
                    this.MessageBox1.ShowWarning("Unable to update plan: " + updateResponse.Message);
                    return;
                }                                    
                if (!MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp))
                {
                    this.MessageBox1.ShowWarning("Unable to change plans! Check with support.");
                    return;                    
                }

                Response.Redirect("ChangePlan.aspx?ok=1");                
            }
            else
            {            
                var createRequest = new CreateCustomerRequest();
                createRequest.CreditCard = this.CreditCardInput1.GetCardData();
                createRequest.PostalCode = this.txtZipCode.Text;
                createRequest.PlanId = TranslatePlanId(planId);
                createRequest.Name = store.Id + " - " + store.StoreName;
                createRequest.Email = user.Email.Replace("@","+store" + store.Id + "@");

                var createResponse = billManager.CreateCustomer(createRequest);
                if (!createResponse.Success)
                {
                    this.MessageBox1.ShowWarning("Unable to change plans: " + createResponse.Message);
                    return;
                }

                // Save customer subscription id
                store.StripeCustomerId = createResponse.NewCustomerId;
                MTApp.UpdateCurrentStore();

                // Change plan in MerchantTribe
                MTApp.AccountServices.ChangePlan(store.Id, user.Id, planId, MTApp);
                Response.Redirect("ChangePlan.aspx?ok=1");                                
                
            }            
        }