示例#1
0
def tickets_clear(flow=None):
    basket = Basket.from_session(current_user, get_user_currency())
    basket.cancel_purchases()
    db.session.commit()

    Basket.clear_from_session()
    return redirect(url_for('tickets.main', flow=flow))
示例#2
0
def tickets_clear(flow=None):
    basket = Basket.from_session(current_user, get_user_currency())
    basket.cancel_purchases()
    db.session.commit()

    Basket.clear_from_session()
    return redirect(url_for("tickets.main", flow=flow))
示例#3
0
def handle_free_tickets(flow: str, view: ProductView, basket: Basket):
    """The user is trying to "buy" only free tickets.

    This is effectively a payment stage, handled differently
    from the rest of the flow.
    """
    # They must be authenticated for this.
    if not current_user.is_authenticated:
        app.logger.warn("User is not authenticated, sending to login")
        flash("You must be logged in to buy additional free tickets")
        return redirect(
            url_for("users.login", next=url_for("tickets.main", flow=flow)))

    # We sell under-12 tickets to non-CfP users, to enforce capacity.
    # We don't let people order an under-12 ticket on its own.
    # However, CfP users need to be able to buy day and parking tickets.
    admissions_tickets = current_user.get_owned_tickets(
        type="admission_ticket")
    if not any(admissions_tickets) and not view.cfp_accepted_only:
        app.logger.warn(
            "User trying to buy free add-ons without an admission ticket")
        flash(
            "You must have an admissions ticket to buy additional free tickets"
        )
        return redirect(url_for("tickets.main", flow=flow))

    basket.user = current_user
    basket.check_out_free()
    db.session.commit()

    Basket.clear_from_session()

    msg = EmailMessage(
        "Your EMF ticket order",
        from_email=from_email("TICKETS_EMAIL"),
        to=[current_user.email],
    )

    already_emailed = set_tickets_emailed(current_user)
    msg.body = render_template(
        "emails/tickets-ordered-email-free.txt",
        user=current_user,
        basket=basket,
        already_emailed=already_emailed,
    )
    if feature_enabled("ISSUE_TICKETS"):
        attach_tickets(msg, current_user)

    msg.send()

    if len(basket.purchases) == 1:
        flash("Your ticket has been confirmed")
    else:
        flash("Your tickets have been confirmed")

    return redirect(url_for("users.purchases"))
示例#4
0
def pay(flow=None):
    if flow is None:
        flow = "main"

    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.token and session.get("ticket_token") != view.token:
        if not current_user.is_anonymous and current_user.has_permission("admin"):
            abort(404)

    if request.form.get("change_currency") in ("GBP", "EUR"):
        currency = request.form.get("change_currency")
        app.logger.info("Updating currency to %s", currency)
        set_user_currency(currency)
        db.session.commit()

        return redirect(url_for(".pay", flow=flow))

    basket = Basket.from_session(current_user, get_user_currency())
    if not any(basket.values()):
        empty_baskets.inc()

        if current_user.is_authenticated:
            basket.load_purchases_from_db()

        if any(basket.values()):
            # We've lost the user's state, but we can still show them all
            # tickets they've reserved and let them empty their basket.
            flash(
                "Your browser doesn't seem to be storing cookies. This may break some parts of the site."
            )
            app.logger.warn(
                "Basket is empty, so showing reserved tickets (%s)",
                request.headers.get("User-Agent"),
            )

        else:
            app.logger.info("Basket is empty, redirecting back to choose tickets")
            if view.type == "tickets":
                flash("Please select at least one ticket to buy.")
            elif view.type == "hire":
                flash("Please select at least one item to hire.")
            else:
                flash("Please select at least one item to buy.")
            return redirect(url_for("tickets.main", flow=flow))

    if basket.requires_shipping:
        if current_user.is_authenticated:
            shipping = current_user.shipping
        else:
            shipping = None

        form = TicketPaymentShippingForm(obj=shipping)

    else:
        form = TicketPaymentForm()

    form.flow = flow

    if current_user.is_authenticated:
        form.name.data = current_user.name
        del form.email
        if current_user.name != current_user.email and not basket.requires_shipping:
            # FIXME: is this helpful?
            del form.name

    if form.validate_on_submit():
        if Decimal(form.basket_total.data) != Decimal(basket.total):
            # Check that the user's basket approximately matches what we told them they were paying.
            price_changed.inc()
            app.logger.warn(
                "User's basket has changed value %s -> %s",
                form.basket_total.data,
                basket.total,
            )
            flash(
                """The items you selected have changed, possibly because you had two windows open.
                  Please verify that you've selected the correct items."""
            )
            return redirect(url_for("tickets.pay", flow=flow))

        user = current_user
        if user.is_anonymous:
            try:
                new_user = create_current_user(form.email.data, form.name.data)
            except IntegrityError as e:
                app.logger.warn("Adding user raised %r, possible double-click", e)
                return None

            user = new_user

        elif user.name == user.email:
            user.name = form.name.data

        if form.allow_promo.data:
            user.promo_opt_in = True

        if basket.requires_shipping:
            if not user.shipping:
                user.shipping = UserShipping()

            user.shipping.address_1 = form.address_1.data
            user.shipping.address_2 = form.address_2.data
            user.shipping.town = form.town.data
            user.shipping.postcode = form.postcode.data
            user.shipping.country = form.country.data

        if form.gocardless.data:
            payment_type = GoCardlessPayment
        elif form.banktransfer.data:
            payment_type = BankPayment
        elif form.stripe.data:
            payment_type = StripePayment

        basket.user = user
        payment = basket.create_payment(payment_type)
        basket.cancel_surplus_purchases()
        db.session.commit()

        Basket.clear_from_session()

        if not payment:
            empty_baskets.inc()
            app.logger.warn("User tried to pay for empty basket")
            flash(
                "We're sorry, your session information has been lost. Please try ordering again."
            )
            return redirect(url_for("tickets.main", flow=flow))

        if payment_type == GoCardlessPayment:
            return gocardless_start(payment)
        elif payment_type == BankPayment:
            return transfer_start(payment)
        elif payment_type == StripePayment:
            return stripe_start(payment)

    form.basket_total.data = basket.total

    return render_template(
        "tickets/payment-choose.html",
        form=form,
        basket=basket,
        total=basket.total,
        flow=flow,
        view=view,
    )
示例#5
0
def main(flow=None):
    if flow is None:
        flow = "main"

    # For now, use the flow name as a view name. This might change.
    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.cfp_accepted_only and current_user.is_anonymous:
        return redirect(url_for("users.login", next=url_for(".main", flow=flow)))

    if not view.is_accessible(current_user, session.get("ticket_token")):
        abort(404)

    sales_state = get_sales_state()

    if sales_state in ["unavailable", "sold-out"]:
        # For the main entry point, we assume people want admissions tickets,
        # but we still need to sell people parking tickets, tents or tickets
        # from tokens until the final cutoff (sales-ended).
        if flow != "main":
            sales_state = "available"

    if app.config.get("DEBUG"):
        sales_state = request.args.get("sales_state", sales_state)

    if sales_state in {"available", "unavailable"}:
        pass
    elif not current_user.is_anonymous and current_user.has_permission("admin"):
        pass
    else:
        return render_template("tickets/cutoff.html")

    tiers = OrderedDict()
    products = (
        ProductViewProduct.query.filter_by(view_id=view.id)
        .join(ProductViewProduct.product)
        .with_entities(Product)
        .order_by(ProductViewProduct.order)
        .options(joinedload(Product.price_tiers).joinedload(PriceTier.prices))
    )

    for product in products:
        pts = [tier for tier in product.price_tiers if tier.active]
        if len(pts) > 1:
            app.logger.error(
                "Multiple active PriceTiers found for %s. Excluding product.", product
            )
            continue

        pt = pts[0]

        tiers[pt.id] = pt

    basket = Basket.from_session(current_user, get_user_currency())

    form = TicketAmountsForm()

    """
    For consistency and to avoid surprises, we try to ensure a few things here:
    - if the user successfully submits a form with no errors, their basket is updated
    - if they don't, the basket is left untouched
    - the basket is updated to match what was submitted, even if they added tickets in another tab
    - if they already have tickets in their basket, only reserve the extra tickets as necessary
    - don't unreserve surplus tickets until the payment is created
    - if the user hasn't submitted anything, we use their current reserved ticket counts
    - if the user has reserved tickets from exhausted tiers on this view, we still show them
    - if the user has reserved tickets from other views, don't show and don't mess with them
    - this means the user can combine tickets from multiple views into a single basket
    - show the sold-out/unavailable states only when the user doesn't have reserved tickets

    We currently don't deal with multiple price tiers being available around the same time.
    Reserved tickets from a previous tier should be cancelled before activating a new one.
    """
    if request.method != "POST":
        # Empty form - populate products
        for pt_id, tier in tiers.items():
            form.tiers.append_entry()
            f = form.tiers[-1]
            f.tier_id.data = pt_id

            f.amount.data = basket.get(tier, 0)

    # Whether submitted or not, update the allowed amounts before validating
    capacity_gone = False
    for f in form.tiers:
        pt_id = f.tier_id.data
        tier = tiers[pt_id]
        f._tier = tier

        # If they've already got reserved tickets, let them keep them
        user_limit = max(tier.user_limit(), basket.get(tier, 0))
        if f.amount.data and f.amount.data > user_limit:
            capacity_gone = True
        values = range(user_limit + 1)
        f.amount.values = values
        f._any = any(values)

    available = True
    if sales_state == "unavailable":
        if not any(p.product in products for p in basket.purchases):
            # If they have any reservations, they bypass the unavailable state.
            # This means someone can use another view to get access to this one
            # again. I'm not sure what to do about this. It usually won't matter.
            available = False

    if form.validate_on_submit():
        if form.buy_tickets.data or form.buy_hire.data or form.buy_other.data:
            if form.currency_code.data != get_user_currency():
                set_user_currency(form.currency_code.data)
                # Commit so we don't lose the currency change if an error occurs
                db.session.commit()
                # Reload the basket because set_user_currency has changed it under us
                basket = Basket.from_session(current_user, get_user_currency())

            for f in form.tiers:
                pt = f._tier
                if f.amount.data != basket.get(pt, 0):
                    app.logger.info(
                        "Adding %s %s tickets to basket", f.amount.data, pt.name
                    )
                    basket[pt] = f.amount.data

            if not available:
                app.logger.warn("User has no reservations, enforcing unavailable state")
                basket.save_to_session()
                return redirect(url_for("tickets.main", flow=flow))

            if not any(basket.values()):
                empty_baskets.inc()
                if view.type == "tickets":
                    flash("Please select at least one ticket to buy.")
                elif view.type == "hire":
                    flash("Please select at least one item to hire.")
                else:
                    flash("Please select at least one item to buy.")

                basket.save_to_session()
                return redirect(url_for("tickets.main", flow=flow))

            app.logger.info("Basket %s", basket)

            try:
                basket.create_purchases()
                basket.ensure_purchase_capacity()

                db.session.commit()

            except CapacityException as e:
                # Damn, capacity's gone since we created the purchases
                # Redirect back to show what's currently in the basket
                db.session.rollback()
                no_capacity.inc()
                app.logger.warn("Limit exceeded creating tickets: %s", e)
                flash(
                    "We're very sorry, but there is not enough capacity available to "
                    "allocate these tickets. You may be able to try again with a smaller amount."
                )
                return redirect(url_for("tickets.main", flow=flow))

            basket.save_to_session()

            if basket.total != 0:
                # Send the user off to pay
                return redirect(url_for("tickets.pay", flow=flow))

            # Otherwise, the user is trying to buy free tickets.
            # They must be authenticated for this.
            if not current_user.is_authenticated:
                app.logger.warn("User is not authenticated, sending to login")
                flash("You must be logged in to buy additional free tickets")
                return redirect(
                    url_for("users.login", next=url_for("tickets.main", flow=flow))
                )

            # We sell under-12 tickets to non-CfP users, to enforce capacity.
            # We don't let people order an under-12 ticket on its own.
            # However, CfP users need to be able to buy day and parking tickets.
            admissions_tickets = current_user.get_owned_tickets(type="admission_ticket")
            if not any(admissions_tickets) and not view.cfp_accepted_only:
                app.logger.warn(
                    "User trying to buy free add-ons without an admission ticket"
                )
                flash(
                    "You must have an admissions ticket to buy additional free tickets"
                )
                return redirect(url_for("tickets.main", flow=flow))

            basket.user = current_user
            basket.check_out_free()
            db.session.commit()

            Basket.clear_from_session()

            msg = Message(
                "Your EMF ticket order",
                sender=app.config["TICKETS_EMAIL"],
                recipients=[current_user.email],
            )

            already_emailed = set_tickets_emailed(current_user)
            msg.body = render_template(
                "emails/tickets-ordered-email-free.txt",
                user=current_user,
                basket=basket,
                already_emailed=already_emailed,
            )
            if feature_enabled("ISSUE_TICKETS"):
                attach_tickets(msg, current_user)

            mail.send(msg)

            if len(basket.purchases) == 1:
                flash("Your ticket has been confirmed")
            else:
                flash("Your tickets have been confirmed")

            return redirect(url_for("users.purchases"))

    if request.method == "POST" and form.set_currency.data:
        if form.set_currency.validate(form):
            app.logger.info("Updating currency to %s only", form.set_currency.data)
            set_user_currency(form.set_currency.data)
            db.session.commit()

            for field in form:
                field.errors = []

    if capacity_gone:
        no_capacity.inc()
        flash(
            "We're sorry, but there is not enough capacity available to "
            "allocate these tickets. You may be able to try again with a smaller amount."
        )

    form.currency_code.data = get_user_currency()
    return render_template(
        "tickets/choose.html", form=form, flow=flow, view=view, available=available
    )
示例#6
0
def logout():
    session.permanent = False
    Basket.clear_from_session()
    logout_user()
    return redirect(request.args.get("next", url_for("base.main")))
示例#7
0
def logout():
    session.permanent = False
    Basket.clear_from_session()
    logout_user()
    return redirect(get_next_url(default=url_for("base.main")))
示例#8
0
def logout():
    session.permanent = False
    Basket.clear_from_session()
    logout_user()
    return redirect(url_for('base.main'))
示例#9
0
def pay(flow=None):
    if flow is None:
        flow = 'main'

    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.token and session.get('ticket_token') != view.token:
        if not current_user.is_anonymous and current_user.has_permission(
                'admin'):
            abort(404)

    if request.form.get("change_currency") in ('GBP', 'EUR'):
        set_user_currency(request.form.get("change_currency"))
        db.session.commit()

        return redirect(url_for('.pay', flow=flow))

    form = TicketPaymentForm()
    form.flow = flow

    if not current_user.is_anonymous:
        del form.email
        if current_user.name != current_user.email:
            del form.name

    basket = Basket.from_session(current_user, get_user_currency())
    if not any(basket.values()):
        empty_baskets.inc()
        if flow == 'main':
            flash("Please select at least one ticket to buy.")
        else:
            flash("Please select at least one item to buy.")
        return redirect(url_for('tickets.main'))

    if form.validate_on_submit():
        if Decimal(form.basket_total.data) != Decimal(basket.total):
            # Check that the user's basket approximately matches what we told them they were paying.
            price_changed.inc()
            app.logger.warn("User's basket has changed value %s -> %s",
                            form.basket_total.data, basket.total)
            flash(
                """The tickets you selected have changed, possibly because you had two windows open.
                  Please verify that you've selected the correct tickets.""")
            return redirect(url_for('tickets.pay', flow=flow))

        user = current_user
        if user.is_anonymous:
            try:
                new_user = create_current_user(form.email.data, form.name.data)
            except IntegrityError as e:
                app.logger.warn('Adding user raised %r, possible double-click',
                                e)
                return None

            user = new_user

        elif user.name == user.email:
            user.name = form.name.data

        if form.allow_promo.data:
            user.promo_opt_in = True

        if form.gocardless.data:
            payment_type = GoCardlessPayment
        elif form.banktransfer.data:
            payment_type = BankPayment
        elif form.stripe.data:
            payment_type = StripePayment

        basket.user = user
        payment = basket.create_payment(payment_type)
        basket.cancel_surplus_purchases()
        db.session.commit()

        Basket.clear_from_session()

        if not payment:
            empty_baskets.inc()
            app.logger.warn('User tried to pay for empty basket')
            flash(
                "We're sorry, your session information has been lost. Please try ordering again."
            )
            return redirect(url_for('tickets.main', flow=flow))

        if payment_type == GoCardlessPayment:
            return gocardless_start(payment)
        elif payment_type == BankPayment:
            return transfer_start(payment)
        elif payment_type == StripePayment:
            return stripe_start(payment)

    form.basket_total.data = basket.total

    return render_template('payment-choose.html',
                           form=form,
                           basket=basket,
                           total=basket.total,
                           flow=flow)
示例#10
0
def start_payment(form, basket, flow):
    if Decimal(form.basket_total.data) != Decimal(basket.total):
        # Check that the user's basket approximately matches what we told them they were paying.
        price_changed.inc()
        app.logger.warn(
            "User's basket has changed value %s -> %s",
            form.basket_total.data,
            basket.total,
        )
        flash(
            """The items you selected have changed, possibly because you had two windows open.
              Please verify that you've selected the correct items.""")
        return redirect(url_for("tickets.pay", flow=flow))

    user = current_user

    if user.is_anonymous:
        try:
            new_user = create_current_user(form.email.data, form.name.data)
        except IntegrityError as e:
            app.logger.warn("Adding user raised %r, possible double-click", e)
            return redirect(url_for("tickets.pay", flow=flow))

        user = new_user
    elif user.name == user.email:
        user.name = form.name.data

    if form.allow_promo.data:
        user.promo_opt_in = True

    if basket.requires_shipping:
        if not user.shipping:
            user.shipping = UserShipping()

        user.shipping.address_1 = form.address_1.data
        user.shipping.address_2 = form.address_2.data
        user.shipping.town = form.town.data
        user.shipping.postcode = form.postcode.data
        user.shipping.country = form.country.data

    payment_type = form.get_payment_class()

    basket.user = user
    try:
        payment = basket.create_payment(payment_type)
    except VoucherUsedError as e:
        # Voucher has been used since we last checked it at the "choose" stage.
        app.logger.exception("Voucher used at payment stage")
        flash(
            "The voucher you've used does not allow you to buy this many adult tickets. "
            "Please choose fewer tickets.")
        db.session.rollback()
        return redirect(url_for("tickets.main", flow=flow))

    basket.cancel_surplus_purchases()
    db.session.commit()

    # Remove voucher ID from session, if it exists.
    try:
        del session["ticket_voucher"]
    except KeyError:
        pass

    Basket.clear_from_session()

    if not payment:
        empty_baskets.inc()
        app.logger.warn("User tried to pay for empty basket")
        flash(
            "We're sorry, your session information has been lost. Please try ordering again."
        )
        return redirect(url_for("tickets.main", flow=flow))

    if payment_type == GoCardlessPayment:
        return gocardless_start(payment)
    elif payment_type == BankPayment:
        return transfer_start(payment)
    elif payment_type == StripePayment:
        return stripe_start(payment)
示例#11
0
def pay(flow=None):
    if flow is None:
        flow = 'main'

    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.token and session.get('ticket_token') != view.token:
        if not current_user.is_anonymous and current_user.has_permission('admin'):
            abort(404)

    if request.form.get("change_currency") in ('GBP', 'EUR'):
        currency = request.form.get("change_currency")
        app.logger.info("Updating currency to %s", currency)
        set_user_currency(currency)
        db.session.commit()

        return redirect(url_for('.pay', flow=flow))

    basket = Basket.from_session(current_user, get_user_currency())
    if not any(basket.values()):
        empty_baskets.inc()

        if current_user.is_authenticated:
            basket.load_purchases_from_db()

        if any(basket.values()):
            # We've lost the user's state, but we can still show them all
            # tickets they've reserved and let them empty their basket.
            flash("Your browser doesn't seem to be storing cookies. This may break some parts of the site.")
            app.logger.warn("Basket is empty, so showing reserved tickets (%s)", request.headers.get('User-Agent'))

        else:
            app.logger.info("Basket is empty, redirecting back to choose tickets")
            if view.type == 'tickets':
                flash("Please select at least one ticket to buy.")
            elif view.type == 'hire':
                flash("Please select at least one item to hire.")
            else:
                flash("Please select at least one item to buy.")
            return redirect(url_for('tickets.main', flow=flow))

    if basket.requires_shipping:
        if current_user.is_authenticated:
            shipping = current_user.shipping
        else:
            shipping = None

        form = TicketPaymentShippingForm(obj=shipping)

    else:
        form = TicketPaymentForm()

    form.flow = flow

    if current_user.is_authenticated:
        form.name.data = current_user.name
        del form.email
        if current_user.name != current_user.email and not basket.requires_shipping:
            # FIXME: is this helpful?
            del form.name

    if form.validate_on_submit():
        if Decimal(form.basket_total.data) != Decimal(basket.total):
            # Check that the user's basket approximately matches what we told them they were paying.
            price_changed.inc()
            app.logger.warn("User's basket has changed value %s -> %s", form.basket_total.data, basket.total)
            flash("""The items you selected have changed, possibly because you had two windows open.
                  Please verify that you've selected the correct items.""")
            return redirect(url_for('tickets.pay', flow=flow))

        user = current_user
        if user.is_anonymous:
            try:
                new_user = create_current_user(form.email.data, form.name.data)
            except IntegrityError as e:
                app.logger.warn('Adding user raised %r, possible double-click', e)
                return None

            user = new_user

        elif user.name == user.email:
            user.name = form.name.data

        if form.allow_promo.data:
            user.promo_opt_in = True

        if basket.requires_shipping:
            if not user.shipping:
                user.shipping = UserShipping()

            user.shipping.address_1 = form.address_1.data
            user.shipping.address_2 = form.address_2.data
            user.shipping.town = form.town.data
            user.shipping.postcode = form.postcode.data
            user.shipping.country = form.country.data

        if form.gocardless.data:
            payment_type = GoCardlessPayment
        elif form.banktransfer.data:
            payment_type = BankPayment
        elif form.stripe.data:
            payment_type = StripePayment

        basket.user = user
        payment = basket.create_payment(payment_type)
        basket.cancel_surplus_purchases()
        db.session.commit()

        Basket.clear_from_session()

        if not payment:
            empty_baskets.inc()
            app.logger.warn('User tried to pay for empty basket')
            flash("We're sorry, your session information has been lost. Please try ordering again.")
            return redirect(url_for('tickets.main', flow=flow))

        if payment_type == GoCardlessPayment:
            return gocardless_start(payment)
        elif payment_type == BankPayment:
            return transfer_start(payment)
        elif payment_type == StripePayment:
            return stripe_start(payment)

    form.basket_total.data = basket.total

    return render_template('payment-choose.html', form=form,
                           basket=basket, total=basket.total,
                           flow=flow, view=view)
示例#12
0
def main(flow=None):
    if flow is None:
        flow = 'main'

    # For now, use the flow name as a view name. This might change.
    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.cfp_accepted_only and current_user.is_anonymous:
        return redirect(url_for('users.login', next=url_for('.main', flow=flow)))

    if not view.is_accessible(current_user, session.get('ticket_token')):
        abort(404)

    sales_state = get_sales_state()

    if sales_state in ['unavailable', 'sold-out']:
        # For the main entry point, we assume people want admissions tickets,
        # but we still need to sell people parking tickets, tents or tickets
        # from tokens until the final cutoff (sales-ended).
        if flow != 'main':
            sales_state = 'available'

    if app.config.get('DEBUG'):
        sales_state = request.args.get("sales_state", sales_state)

    if sales_state in {'available', 'unavailable'}:
        pass
    elif not current_user.is_anonymous and current_user.has_permission('admin'):
        pass
    else:
        return render_template("tickets-cutoff.html")

    tiers = OrderedDict()
    products = ProductViewProduct.query.filter_by(view_id=view.id) \
                                 .join(ProductViewProduct.product) \
                                 .with_entities(Product) \
                                 .order_by(ProductViewProduct.order) \
                                 .options(joinedload(Product.price_tiers)
                                          .joinedload(PriceTier.prices)
                                 )

    for product in products:
        pts = [tier for tier in product.price_tiers if tier.active]
        if len(pts) > 1:
            app.logger.error("Multiple active PriceTiers found for %s. Excluding product.", product)
            continue

        pt = pts[0]

        tiers[pt.id] = pt

    basket = Basket.from_session(current_user, get_user_currency())

    form = TicketAmountsForm()

    """
    For consistency and to avoid surprises, we try to ensure a few things here:
    - if the user successfully submits a form with no errors, their basket is updated
    - if they don't, the basket is left untouched
    - the basket is updated to match what was submitted, even if they added tickets in another tab
    - if they already have tickets in their basket, only reserve the extra tickets as necessary
    - don't unreserve surplus tickets until the payment is created
    - if the user hasn't submitted anything, we use their current reserved ticket counts
    - if the user has reserved tickets from exhausted tiers on this view, we still show them
    - if the user has reserved tickets from other views, don't show and don't mess with them
    - this means the user can combine tickets from multiple views into a single basket
    - show the sold-out/unavailable states only when the user doesn't have reserved tickets

    We currently don't deal with multiple price tiers being available around the same time.
    Reserved tickets from a previous tier should be cancelled before activating a new one.
    """
    if request.method != 'POST':
        # Empty form - populate products
        for pt_id, tier in tiers.items():
            form.tiers.append_entry()
            f = form.tiers[-1]
            f.tier_id.data = pt_id

            f.amount.data = basket.get(tier, 0)


    # Whether submitted or not, update the allowed amounts before validating
    capacity_gone = False
    for f in form.tiers:
        pt_id = f.tier_id.data
        tier = tiers[pt_id]
        f._tier = tier

        # If they've already got reserved tickets, let them keep them
        user_limit = max(tier.user_limit(), basket.get(tier, 0))
        if f.amount.data and f.amount.data > user_limit:
            capacity_gone = True
        values = range(user_limit + 1)
        f.amount.values = values
        f._any = any(values)

    available = True
    if sales_state == 'unavailable':
        if not any(p.product in products for p in basket.purchases):
            # If they have any reservations, they bypass the unavailable state.
            # This means someone can use another view to get access to this one
            # again. I'm not sure what to do about this. It usually won't matter.
            available = False

    if form.validate_on_submit():
        if form.buy_tickets.data or form.buy_hire.data or form.buy_other.data:
            if form.currency_code.data != get_user_currency():
                set_user_currency(form.currency_code.data)
                # Commit so we don't lose the currency change if an error occurs
                db.session.commit()
                # Reload the basket because set_user_currency has changed it under us
                basket = Basket.from_session(current_user, get_user_currency())

            for f in form.tiers:
                pt = f._tier
                if f.amount.data != basket.get(pt, 0):
                    app.logger.info('Adding %s %s tickets to basket', f.amount.data, pt.name)
                    basket[pt] = f.amount.data

            if not available:
                app.logger.warn('User has no reservations, enforcing unavailable state')
                basket.save_to_session()
                return redirect(url_for('tickets.main', flow=flow))

            if not any(basket.values()):
                empty_baskets.inc()
                if view.type == 'tickets':
                    flash("Please select at least one ticket to buy.")
                elif view.type == 'hire':
                    flash("Please select at least one item to hire.")
                else:
                    flash("Please select at least one item to buy.")

                basket.save_to_session()
                return redirect(url_for('tickets.main', flow=flow))

            app.logger.info('Basket %s', basket)

            try:
                basket.create_purchases()
                basket.ensure_purchase_capacity()

                db.session.commit()

            except CapacityException as e:
                # Damn, capacity's gone since we created the purchases
                # Redirect back to show what's currently in the basket
                db.session.rollback()
                no_capacity.inc()
                app.logger.warn('Limit exceeded creating tickets: %s', e)
                flash("We're very sorry, but there is not enough capacity available to "
                      "allocate these tickets. You may be able to try again with a smaller amount.")
                return redirect(url_for("tickets.main", flow=flow))

            basket.save_to_session()

            if basket.total != 0:
                # Send the user off to pay
                return redirect(url_for('tickets.pay', flow=flow))

            # Otherwise, the user is trying to buy free tickets.
            # They must be authenticated for this.
            if not current_user.is_authenticated:
                app.logger.warn("User is not authenticated, sending to login")
                flash("You must be logged in to buy additional free tickets")
                return redirect(url_for('users.login', next=url_for('tickets.main', flow=flow)))

            # We sell under-12 tickets to non-CfP users, to enforce capacity.
            # We don't let people order an under-12 ticket on its own.
            # However, CfP users need to be able to buy day and parking tickets.
            admissions_tickets = current_user.get_owned_tickets(type='admission_ticket')
            if not any(admissions_tickets) and not view.cfp_accepted_only:
                app.logger.warn("User trying to buy free add-ons without an admission ticket")
                flash("You must have an admissions ticket to buy additional free tickets")
                return redirect(url_for("tickets.main", flow=flow))

            basket.user = current_user
            basket.check_out_free()
            db.session.commit()

            Basket.clear_from_session()

            msg = Message("Your EMF ticket order",
                          sender=app.config['TICKETS_EMAIL'],
                          recipients=[current_user.email])

            already_emailed = set_tickets_emailed(current_user)
            msg.body = render_template("emails/tickets-ordered-email-free.txt",
                                       user=current_user, basket=basket,
                                       already_emailed=already_emailed)
            if feature_enabled('ISSUE_TICKETS'):
                attach_tickets(msg, current_user)

            mail.send(msg)

            if len(basket.purchases) == 1:
                flash("Your ticket has been confirmed")
            else:
                flash("Your tickets have been confirmed")

            return redirect(url_for('users.purchases'))


    if request.method == 'POST' and form.set_currency.data:
        if form.set_currency.validate(form):
            app.logger.info("Updating currency to %s only", form.set_currency.data)
            set_user_currency(form.set_currency.data)
            db.session.commit()

            for field in form:
                field.errors = []

    if capacity_gone:
        no_capacity.inc()
        flash("We're sorry, but there is not enough capacity available to "
              "allocate these tickets. You may be able to try again with a smaller amount.")

    form.currency_code.data = get_user_currency()
    return render_template("tickets-choose.html", form=form, flow=flow, view=view, available=available)
示例#13
0
def pay(flow=None):
    if flow is None:
        flow = 'main'

    view = ProductView.get_by_name(flow)
    if not view:
        abort(404)

    if view.token and session.get('ticket_token') != view.token:
        if not current_user.is_anonymous and current_user.has_permission('admin'):
            abort(404)

    if request.form.get("change_currency") in ('GBP', 'EUR'):
        set_user_currency(request.form.get("change_currency"))
        db.session.commit()

        return redirect(url_for('.pay', flow=flow))

    form = TicketPaymentForm()
    form.flow = flow

    if not current_user.is_anonymous:
        del form.email
        if current_user.name != current_user.email:
            del form.name

    basket = Basket.from_session(current_user, get_user_currency())
    if not any(basket.values()):
        empty_baskets.inc()
        if flow == 'main':
            flash("Please select at least one ticket to buy.")
        else:
            flash("Please select at least one item to buy.")
        return redirect(url_for('tickets.main'))

    if form.validate_on_submit():
        if Decimal(form.basket_total.data) != Decimal(basket.total):
            # Check that the user's basket approximately matches what we told them they were paying.
            price_changed.inc()
            app.logger.warn("User's basket has changed value %s -> %s", form.basket_total.data, basket.total)
            flash("""The tickets you selected have changed, possibly because you had two windows open.
                  Please verify that you've selected the correct tickets.""")
            return redirect(url_for('tickets.pay', flow=flow))

        user = current_user
        if user.is_anonymous:
            try:
                new_user = create_current_user(form.email.data, form.name.data)
            except IntegrityError as e:
                app.logger.warn('Adding user raised %r, possible double-click', e)
                return None

            user = new_user

        elif user.name == user.email:
            user.name = form.name.data

        if form.allow_promo.data:
            user.promo_opt_in = True

        if form.gocardless.data:
            payment_type = GoCardlessPayment
        elif form.banktransfer.data:
            payment_type = BankPayment
        elif form.stripe.data:
            payment_type = StripePayment

        basket.user = user
        payment = basket.create_payment(payment_type)
        basket.cancel_surplus_purchases()
        db.session.commit()

        Basket.clear_from_session()

        if not payment:
            empty_baskets.inc()
            app.logger.warn('User tried to pay for empty basket')
            flash("We're sorry, your session information has been lost. Please try ordering again.")
            return redirect(url_for('tickets.main', flow=flow))

        if payment_type == GoCardlessPayment:
            return gocardless_start(payment)
        elif payment_type == BankPayment:
            return transfer_start(payment)
        elif payment_type == StripePayment:
            return stripe_start(payment)

    form.basket_total.data = basket.total

    return render_template('payment-choose.html', form=form,
                           basket=basket, total=basket.total,
                           flow=flow)