Beispiel #1
0
def charge_up_front():
    jamlaApp = Jamla()
    jamla = jamlaApp.load(src=app.config['JAMLA_PATH'])
    charge = {}
    charge['amount'] = session['upfront_cost']
    charge['currency'] = "GBP"

    sid = session['sid']
    con = sqlite3.connect(app.config["DB_FULL_PATH"])
    cur = con.cursor()
    cur.execute("SELECT * FROM person p WHERE p.sid = ?", (sid, ))
    res = cur.fetchone()
    con.close()

    try:
        stripe.api_key = jamla['payment_providers']['stripe']['secret_key']
        customer = stripe.Customer.create(email=res[7],
                                          source=request.form['stripeToken'])

        charge = stripe.Charge.create(customer=customer.id,
                                      amount=charge['amount'],
                                      currency=charge['currency'],
                                      description='Subscribie')
    except stripe.error.AuthenticationError as e:
        return str(e)
    if jamlaApp.requires_subscription(session['package']):
        return redirect(url_for('establish_mandate'))
    else:
        return redirect(url_for('thankyou', _scheme='https', _external=True))
Beispiel #2
0
def get_transactions():
    """Return tuple list of transactions from SSOT"""
    from SSOT import SSOT
    payment_provider = PaymentProvider.query.first()
    access_token = payment_provider.gocardless_access_token
    gc_environment = payment_provider.gocardless_environment

    target_gateways = ({
        "name": "GoCardless",
        "construct": {
            "access_token": access_token,
            "environment": gc_environment
        }
    }, )
    try:
        SSOT = SSOT(target_gateways)
        transactions = SSOT.transactions
    except gocardless_pro.errors.InvalidApiUsageError as e:
        logging.error(e.type)
        logging.error(e.message)
        flash("Invalid GoCardless API token. Correct your GoCardless API key.")
        return redirect(url_for("admin.connect_gocardless_manually"))
    except ValueError as e:
        logging.error(e.message)
        if e.message == "No access_token provided":
            flash("You must connect your GoCardless account first.")
            return redirect(url_for("admin.connect_gocardless_manually"))
        else:
            raise
    return transactions
Beispiel #3
0
def onboard_user_refresh():
    if 'account_id' not in session:
        return redirect(url_for('admin.stripe_onboarding'))

    account_id = session['account_id']

    origin = ('https://'
              if request.is_secure else 'http://') + request.headers['host']
    account_link_url = _generate_account_link(account_id)
    return redirect(account_link_url)
Beispiel #4
0
def connect_stripe_manually():
    form = StripeConnectForm()
    jamlaApp = Jamla()
    jamla = jamlaApp.load(src=app.config['JAMLA_PATH'])
    if jamlaApp.has_connected('stripe'):
        stripe_connected = True
    else:
        stripe_connected = False
    if form.validate_on_submit():
        publishable_key = form.data['publishable_key']
        secret_key = form.data['secret_key']
        jamla['payment_providers']['stripe'][
            'publishable_key'] = publishable_key
        jamla['payment_providers']['stripe']['secret_key'] = secret_key
        # Overwrite jamla file with gocardless access_token
        fp = open(app.config['JAMLA_PATH'], 'w')
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        flask_login.current_user.stripe_publishable_key = publishable_key
        # Set stripe public key JS
        return redirect(url_for('dashboard'))
    else:
        return render_template('connect_stripe_manually.html',
                               form=form,
                               jamla=jamla,
                               stripe_connected=stripe_connected)
Beispiel #5
0
def validate_login(login_token):
    if len(login_token) < 10:
        return 'Invalid token'
    # Try to get email from login_token
    con = sqlite3.connect(app.config["DB_FULL_PATH"])
    con.row_factory = sqlite3.Row  # Dict based result set
    cur = con.cursor()
    cur.execute('SELECT email FROM user WHERE login_token=?', (login_token, ))
    result = cur.fetchone()
    con.close()
    if result is None:
        return "Invalid token"
    # Invaldate previous token
    new_login_token = urlsafe_b64encode(os.urandom(24))
    con = sqlite3.connect(app.config["DB_FULL_PATH"])
    cur = con.cursor()
    cur.execute('UPDATE user SET login_token=? WHERE login_token=?', (
        new_login_token,
        login_token,
    ))
    con.commit()
    con.close()

    email = result['email']
    user = User()
    user.id = email
    flask_login.login_user(user)
    return redirect(url_for('protected'))

    return "Code is %s" % login_token
Beispiel #6
0
def connect_gocardless_manually():
    form = GocardlessConnectForm()
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)
    if jamlaApp.has_connected("gocardless"):
        gocardless_connected = True
    else:
        gocardless_connected = False
    if form.validate_on_submit():
        access_token = form.data["access_token"]
        jamla["payment_providers"]["gocardless"]["access_token"] = access_token
        # Check if live or test api key was given
        if "live" in access_token:
            jamla["payment_providers"]["gocardless"]["environment"] = "live"
        else:
            jamla["payment_providers"]["gocardless"]["environment"] = "sandbox"

        fp = open(current_app.config["JAMLA_PATH"], "w")
        # Overwrite jamla file with gocardless access_token
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        # Set users current session to store access_token for instant access
        session["gocardless_access_token"] = access_token
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template(
            "admin/connect_gocardless_manually.html",
            form=form,
            jamla=jamla,
            gocardless_connected=gocardless_connected,
        )
Beispiel #7
0
def connect_gocardless_manually():
    payment_provider = PaymentProvider.query.first()
    form = GocardlessConnectForm()
    if payment_provider.gocardless_active:
        gocardless_connected = True
    else:
        gocardless_connected = False
    if form.validate_on_submit():
        access_token = form.data["access_token"]
        payment_provider.gocardless_access_token = access_token
        # Check if live or test api key was given
        if "live" in access_token:
            payment_provider.gocardless_environment = "live"
        else:
            payment_provider.gocardless_environment = "sandbox"

        payment_provider.gocardless_active = True
        database.session.commit()  # save changes

        return redirect(url_for("admin.dashboard"))
    else:
        return render_template(
            "admin/connect_gocardless_manually.html",
            form=form,
            gocardless_connected=gocardless_connected,
        )
Beispiel #8
0
def connect_stripe_manually():
    form = StripeConnectForm()
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)
    if jamlaApp.has_connected("stripe"):
        stripe_connected = True
    else:
        stripe_connected = False
    if form.validate_on_submit():
        publishable_key = form.data["publishable_key"].strip()
        secret_key = form.data["secret_key"].strip()
        jamla["payment_providers"]["stripe"][
            "publishable_key"] = publishable_key
        jamla["payment_providers"]["stripe"]["secret_key"] = secret_key
        # Overwrite jamla file with gocardless access_token
        fp = open(current_app.config["JAMLA_PATH"], "w")
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        session["stripe_publishable_key"] = publishable_key
        # Set stripe public key JS
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template(
            "admin/connect_stripe_manually.html",
            form=form,
            jamla=jamla,
            stripe_connected=stripe_connected,
        )
Beispiel #9
0
def gocardless_oauth_complete():
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)
    flow = OAuth2WebServerFlow(
        client_id=current_app.config["GOCARDLESS_CLIENT_ID"],
        client_secret=current_app.config["GOCARDLESS_CLIENT_SECRET"],
        scope="read_write",
        # You'll need to use exactly the same redirect URI as in the last
        # step
        redirect_uri="http://127.0.0.1:5000/connect/gocardless/oauth/complete",
        auth_uri="https://connect-sandbox.gocardless.com/oauth/authorize",
        token_uri="https://connect-sandbox.gocardless.com/oauth/access_token",
        initial_view="signup",
    )
    access_token = flow.step2_exchange(request.args.get("code"))

    jamla["payment_providers"]["gocardless"][
        "access_token"] = access_token.access_token
    fp = open(current_app.config["JAMLA_PATH"], "w")
    # Overwrite jamla file with gocardless access_token
    yaml.safe_dump(jamla, fp, default_flow_style=False)
    # Set users current session to store access_token for instant access
    session["gocardless_access_token"] = access_token.access_token
    session["gocardless_organisation_id"] = access_token.token_response[
        "organisation_id"]

    return redirect(url_for("admin.dashboard"))
Beispiel #10
0
def connect_gocardless_manually():
    form = GocardlessConnectForm()
    jamlaApp = Jamla()
    jamla = jamlaApp.load(src=app.config['JAMLA_PATH'])
    if jamlaApp.has_connected('gocardless'):
        gocardless_connected = True
    else:
        gocardless_connected = False
    if form.validate_on_submit():
        access_token = form.data['access_token']
        jamla['payment_providers']['gocardless']['access_token'] = access_token
        # Check if live or test api key was given
        if "live" in access_token:
            jamla['payment_providers']['gocardless']['environment'] = 'live'
        else:
            jamla['payment_providers']['gocardless']['environment'] = 'sandbox'

        fp = open(app.config['JAMLA_PATH'], 'w')
        # Overwrite jamla file with gocardless access_token
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        # Set users current session to store access_token for instant access
        flask_login.current_user.gocardless_access_token = access_token
        return redirect(url_for('dashboard'))
    else:
        return render_template('connect_gocardless_manually.html',
                               form=form,
                               jamla=jamla,
                               gocardless_connected=gocardless_connected)
Beispiel #11
0
def gocardless_oauth_complete():
    jamlaApp = Jamla()
    jamla = jamlaApp.load(src=app.config['JAMLA_PATH'])
    flow = OAuth2WebServerFlow(
        client_id=app.config['GOCARDLESS_CLIENT_ID'],
        client_secret=app.config['GOCARDLESS_CLIENT_SECRET'],
        scope="read_write",
        # You'll need to use exactly the same redirect URI as in the last step
        redirect_uri="http://127.0.0.1:5000/connect/gocardless/oauth/complete",
        auth_uri="https://connect-sandbox.gocardless.com/oauth/authorize",
        token_uri="https://connect-sandbox.gocardless.com/oauth/access_token",
        initial_view="signup")
    access_token = flow.step2_exchange(request.args.get('code'))

    jamla['payment_providers']['gocardless'][
        'access_token'] = access_token.access_token
    fp = open(app.config['JAMLA_PATH'], 'w')
    # Overwrite jamla file with gocardless access_token
    yaml.safe_dump(jamla, fp, default_flow_style=False)
    # Set users current session to store access_token for instant access
    flask_login.current_user.gocardless_access_token = access_token.access_token
    flask_login.current_user.gocardless_organisation_id = access_token.token_response[
        'organisation_id']

    return redirect(url_for('dashboard'))
Beispiel #12
0
def remove_logo():
    """Remove logo from shop"""
    company = Company.query.first()
    company.logo_src = None
    database.session.commit()
    flash("Logo removed")
    # Return user to previous page
    return redirect(request.referrer)
Beispiel #13
0
def customers():
    jamla = get_jamla()
    from SSOT import SSOT

    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)

    target_gateways = ()

    if jamlaApp.has_connected("gocardless"):
        access_token = jamla["payment_providers"]["gocardless"]["access_token"]
        gc_environment = jamla["payment_providers"]["gocardless"][
            "environment"]
        target_gateways = target_gateways + ({
            "name": "GoCardless",
            "construct": {
                "access_token": access_token,
                "environment": gc_environment
            }
        }, )

    if jamlaApp.has_connected("stripe"):
        stripe_token = jamla["payment_providers"]["stripe"]["secret_key"]
        target_gateways = target_gateways + ({
            "name": "Stripe",
            "construct": stripe_token
        }, )

    try:
        SSOT = SSOT(target_gateways)
        partners = SSOT.partners
    except gocardless_pro.errors.InvalidApiUsageError as e:
        logging.error(e.type)
        logging.error(e.message)
        flash("Invalid GoCardless API token. Correct your GoCardless API key.")
        return redirect(url_for("admin.connect_gocardless_manually"))
    except ValueError as e:
        logging.error(e.message)
        if e.message == "No access_token provided":
            flash("You must connect your GoCardless account first.")
            return redirect(url_for("admin.connect_gocardless_manually"))
        else:
            raise
    return render_template("admin/customers.html",
                           jamla=jamla,
                           partners=partners)
Beispiel #14
0
def store_customer():
    form = CustomerForm()
    if form.validate():
        given_name = form.data['given_name']
        family_name = form.data['family_name']
        address_line_one = form.data['address_line_one']
        city = form.data['city']
        postcode = form.data['postcode']
        email = form.data['email']
        mobile = form.data['mobile']
        now = datetime.datetime.now()
        # Store customer in session
        sid = session['sid']
        # Store email in session
        session['email'] = email

        # Store plan in session
        jamlaApp = Jamla()
        jamla = jamlaApp.load(src=app.config['JAMLA_PATH'])
        if jamlaApp.sku_exists(request.args.get('plan')):
            wants = request.args.get('plan')
            session['plan'] = wants
        print "##################"
        con = sqlite3.connect(app.config["DB_FULL_PATH"])
        cur = con.cursor()
        cur.execute(
            "INSERT INTO person VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (sid, now, given_name, family_name, address_line_one, city,
             postcode, email, mobile, wants, 'null', 'null', False))
        con.commit()
        con.close()

        if jamlaApp.requires_instantpayment(session['package']):
            return redirect(
                url_for('up_front',
                        _scheme='https',
                        _external=True,
                        sid=sid,
                        package=wants,
                        fname=given_name))
        if jamlaApp.requires_subscription(session['package']):
            return redirect(url_for('establish_mandate'))
        return redirect(url_for('thankyou', _scheme='https', _external=True))
    else:
        return "Oops, there was an error processing that form, please go back and try again."
Beispiel #15
0
def add_jamla_item():
    form = ItemsForm()
    jamla = get_jamla()
    if form.validate_on_submit():
        draftItem = {}
        draftItem["uuid"] = str(uuid.uuid4())
        draftItem["requirements"] = {}
        draftItem["primary_icon"] = {"src": "", "type": ""}
        draftItem["title"] = form.title.data[0].strip()
        draftItem["requirements"]["subscription"] = bool(
            form.subscription.data[0])
        draftItem["requirements"]["note_to_seller_required"] = bool(
            form.note_to_seller_required.data[0])
        draftItem["requirements"]["note_to_buyer_message"] = str(
            form.note_to_buyer_message.data[0])
        try:
            days_before_first_charge = int(
                form.days_before_first_charge.data[0])
        except ValueError:
            days_before_first_charge = 0

        draftItem["days_before_first_charge"] = days_before_first_charge

        if form.monthly_price.data[0] is None:
            draftItem["monthly_price"] = False
        else:
            draftItem["monthly_price"] = float(
                form.monthly_price.data[0]) * 100
        draftItem["requirements"]["instant_payment"] = bool(
            form.instant_payment.data[0])
        if form.sell_price.data[0] is None:
            draftItem["sell_price"] = False
        else:
            draftItem["sell_price"] = float(form.sell_price.data[0]) * 100
        draftItem["selling_points"] = form.selling_points.data[0]
        # Create SKU
        draftItem["sku"] = form.title.data[0].replace(" ", "").strip()
        # Primary icon image storage
        f = form.image.data[0]
        if f:
            images = UploadSet("images", IMAGES)
            filename = images.save(f)
            # symlink to active theme static directory
            img_src = "".join(
                [current_app.config["UPLOADED_IMAGES_DEST"], filename])
            link = "".join([current_app.config["STATIC_FOLDER"], filename])
            os.symlink(img_src, link)
            src = url_for("static", filename=filename)
            draftItem["primary_icon"] = {"src": src, "type": ""}
        jamla["items"].append(draftItem)
        fp = open(current_app.config["JAMLA_PATH"], "w")
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        flash("Item added.")
        return redirect(url_for("admin.dashboard"))
    return render_template("admin/add_jamla_item.html", jamla=jamla, form=form)
Beispiel #16
0
def refresh_ssot(resource):
    """Refresh SSOT to fetch newest customers (aka partners) and transactions
  resource is either "customers" or "transactions"
  """
    jamla = get_jamla()
    from SSOT import SSOT

    access_token = jamla["payment_providers"]["gocardless"]["access_token"]
    gc_environment = jamla["payment_providers"]["gocardless"]["environment"]
    target_gateways = ({
        "name": "GoCardless",
        "construct": {
            "access_token": access_token,
            "environment": gc_environment
        }
    }, )
    try:
        SSOT = SSOT(target_gateways, refresh=True)
        partners = SSOT.partners
    except gocardless_pro.errors.InvalidApiUsageError as e:
        logging.error(e.type)
        logging.error(e.message)
        flash("Invalid GoCardless API token. Correct your GoCardless API key.")
        return redirect(url_for("admin.connect_gocardless_manually"))
    except ValueError as e:
        logging.error(e.message)
        if e.message == "No access_token provided":
            flash("You must connect your GoCardless account first.")
            return redirect(url_for("admin.connect_gocardless_manually"))
        else:
            raise
    if resource == "customers":
        flash("Customers refreshed")
        return redirect(url_for('admin.customers'))
    if resource == "transactions":
        flash("Customers refreshed")
        return redirect(url_for('admin.transactions'))
    # Fallback
    flask("Refreshed customers & transactions")
    return redirect(url_for('admin.dashboard'))
Beispiel #17
0
def customers():
    payment_provider = PaymentProvider.query.first()
    from SSOT import SSOT

    target_gateways = ()

    if payment_provider.gocardless_active:
        access_token = payment_provider.gocardless_access_token,
        gc_environment = payment_provider.gocardless_environment,
        target_gateways = target_gateways + ({
            "name": "GoCardless",
            "construct": {
                "access_token": access_token,
                "environment": gc_environment
            }
        }, )

    if payment_provider.stripe_active:
        stripe_token = payment_provider.stripe_secret_key
        target_gateways = target_gateways + ({
            "name": "Stripe",
            "construct": stripe_token
        }, )

    try:
        SSOT = SSOT(target_gateways)
        partners = SSOT.partners
    except gocardless_pro.errors.InvalidApiUsageError as e:
        logging.error(e.type)
        logging.error(e.message)
        flash("Invalid GoCardless API token. Correct your GoCardless API key.")
        return redirect(url_for("admin.connect_gocardless_manually"))
    except ValueError as e:
        logging.error(e.message)
        if e.message == "No access_token provided":
            flash("You must connect your GoCardless account first.")
            return redirect(url_for("admin.connect_gocardless_manually"))
        else:
            raise
    return render_template("admin/customers.html", partners=partners)
Beispiel #18
0
def add_item():
    form = ItemsForm()
    if form.validate_on_submit():
        draftItem = Item()
        database.session.add(draftItem)
        item_requirements = ItemRequirements()
        draftItem.requirements.append(item_requirements)

        draftItem.uuid = str(uuid.uuid4())
        draftItem.title = form.title.data[0].strip()
        item_requirements.subscription = bool(form.subscription.data[0])
        item_requirements.note_to_seller_required = bool(form.note_to_seller_required.data[0])
        item_requirements.note_to_buyer_message = str(form.note_to_buyer_message.data[0])
        try:
            days_before_first_charge = int(form.days_before_first_charge.data[0])
        except ValueError:
            days_before_first_charge = 0

        draftItem.days_before_first_charge = days_before_first_charge

        if form.monthly_price.data[0] is None:
            draftItem.monthly_price = 0
        else:
            draftItem.monthly_price = int(form.monthly_price.data[0]) * 100
        item_requirements.instant_payment = bool(
            form.instant_payment.data[0]
        )
        if form.sell_price.data[0] is None:
            draftItem.sell_price = 0
        else:
            draftItem.sell_price = int(form.sell_price.data[0]) * 100

        points = form.selling_points.data[0]

        for point in points:
            draftItem.selling_points.append(ItemSellingPoints(point=point))

        # Primary icon image storage
        f = form.image.data[0]
        if f:
            images = UploadSet("images", IMAGES)
            filename = images.save(f)
            # symlink to active theme static directory
            img_src = "".join([current_app.config["UPLOADED_IMAGES_DEST"], filename])
            link = "".join([current_app.config["STATIC_FOLDER"], filename])
            os.symlink(img_src, link)
            src = url_for("static", filename=filename)
            draftItem.primary_icon = src
        database.session.commit()
        flash("Item added.")
        return redirect(url_for("admin.dashboard"))
    return render_template("admin/add_item.html", form=form)
Beispiel #19
0
def connect_tawk_manually():
    integration = Integration.query.first()
    form = TawkConnectForm()
    if form.validate_on_submit():
        property_id = form.data["property_id"]
        integration.tawk_property_id = property_id
        integration.tawk_active = True
        database.session.commit()
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template("admin/connect_tawk_manually.html",
                               form=form,
                               integration=integration)
Beispiel #20
0
def connect_google_tag_manager_manually():
    integration = Integration.query.first()
    form = GoogleTagManagerConnectForm()
    if form.validate_on_submit():
        container_id = form.data["container_id"]
        integration.google_tag_manager_container_id = container_id
        integration.google_tag_manager_active = True
        database.session.commit()
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template(
            "admin/connect_google_tag_manager_manually.html",
            form=form,
            integration=integration)
Beispiel #21
0
def transactions():
    payment_provider = PaymentProvider.query.first()
    from SSOT import SSOT

    access_token = payment_provider.gocardless_access_token,
    target_gateways = ({"name": "GoCardless", "construct": access_token}, )
    try:
        SSOT = SSOT(target_gateways)
        transactions = SSOT.transactions
    except gocardless_pro.errors.InvalidApiUsageError as e:
        logging.error(e.type)
        logging(e.message)
        flash("Invalid GoCardless API token. Correct your GoCardless API key.")
        return redirect(url_for("admin.connect_gocardless_manually"))
    except ValueError as e:
        logging.error(e.message)
        if e.message == "No access_token provided":
            flash("You must connect your GoCardless account first.")
            return redirect(url_for("admin.connect_gocardless_manually"))
        else:
            raise
    return render_template("admin/transactions.html",
                           transactions=transactions)
Beispiel #22
0
def delete_file(uuid):
    # Remove from database file meta
    theFile = File.query.filter_by(uuid=uuid).first()
    if theFile is not None:
        database.session.delete(theFile)

    database.session.commit()
    # Remove from filesystem
    try:
        os.unlink(current_app.config['UPLOADED_FILES_DEST'] +
                  theFile.file_name)
    except Exception as e:
        print(e)
    flash(f"Deleted: {theFile.file_name}")
    return redirect(request.referrer)
Beispiel #23
0
def connect_tawk_manually():
    form = TawkConnectForm()
    jamla = get_jamla()
    jamlaApp = Jamla()
    jamlaApp.load(jamla=jamla)
    if form.validate_on_submit():
        property_id = form.data["property_id"]
        jamla["integrations"]["tawk"]["property_id"] = property_id
        jamla["integrations"]["tawk"]["active"] = True
        # Overwrite jamla file with google tag manager container_id
        fp = open(current_app.config["JAMLA_PATH"], "w")
        yaml.safe_dump(jamla, fp, default_flow_style=False)
        session["tawk_property_id"] = property_id
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template("admin/connect_tawk_manually.html",
                               form=form,
                               jamla=jamla)
Beispiel #24
0
def pause_gocardless_subscription(subscription_id):
    """Pause a GoCardless subscription"""
    payment_provider = PaymentProvider.query.first()        
    gocclient = gocardless_pro.Client(
      access_token=payment_provider.gocardless_access_token,
          environment=payment_provider.gocardless_environment,
    )

    try:
        req = gocclient.subscriptions.pause(subscription_id)
    except gocardless_pro.errors.InvalidStateError as e:
        return jsonify(error=e.message)

    flash("Subscription paused")

    if 'goback' in request.args:
        return redirect(request.referrer)
    return jsonify(message="Subscription paused", subscription_id=subscription_id)
Beispiel #25
0
def update_payment_fulfillment(gocardless_payment_id):
    """Update payment fulfillment stage"""

    transaction = Transaction.query.filter_by(external_id=gocardless_payment_id).first()
    if transaction is None:
        transaction = store_gocardless_transaction(gocardless_payment_id)

    # Update transactions fulfillment_state to the value specified
    fulfillment_state = request.args.get('state', '')
    # Check a valid fulfillment_state is passed (only one or empty at the moment)
    if fulfillment_state == '' or fulfillment_state == 'complete':
        transaction.fulfillment_state = fulfillment_state
        flash("Fulfillment state updated")

    database.session.add(transaction)
    database.session.commit() # Save/update transaction in transactions table

    # Go back to previous page
    return redirect(request.referrer)
Beispiel #26
0
def cancel_mandates(email):
    """Cancel all mandates associated with a given email"""
    jamla = get_jamla()
    if "confirm" in request.args:
        # Get all mandates associated with <email>
        # Then cancel them
        transactions = get_transactions()
        partner_madates = []
        for transaction in transactions:
            # Match email to mandates
            if transaction.mandate['links']['customer']['email'] == email \
            and transaction.mandate['status'] == 'active':
                partner_madates.append(transaction.mandate)

        if len(partner_madates) > 0:
            gocclient = gocardless_pro.Client(
                access_token=jamla["payment_providers"]["gocardless"]
                ["access_token"],
                environment=jamla["payment_providers"]["gocardless"]
                ["environment"],
            )
            for mandate in partner_madates:  # Cancel each mandate for given email
                removed = False
                try:
                    req = gocclient.mandates.cancel(mandate['id'])
                    flash("Mandate canceled for {}".format(email))
                    flash("The mandate ID was: {}".format(mandate['id']))
                    removed = True
                except gocardless_pro.errors.InvalidStateError:
                    removed = True
                    flash("Mandate already canceled for {}".format(email))
                    flash("The mandate ID was: {}".format(mandate['id']))

                if removed:
                    # Remove from local mandates list
                    refresh_ssot(resource='customers')

            return redirect(url_for("admin.customers"))
    return render_template("admin/cancel_mandates_confirm.html",
                           email=email,
                           jamla=jamla)
Beispiel #27
0
def change_password():
    """Change password of existing user"""
    form = ChangePasswordForm()
    if request.method == "POST":
        email = session.get('user_id', None)
        if email is None:
            return "Email not found in session"

        if form.validate_on_submit():
            user = User.query.filter_by(email=email).first()
            if user is None:
                return "User not found with that email"
            else:
                user.set_password(request.form["password"])
                database.session.commit()
            flash("Password has been updated")
        else:
            return "Invalid password form submission"
        return redirect(url_for('admin.change_password'))
    else:
        return render_template("admin/change_password.html", form=form)
Beispiel #28
0
def add_shop_admin():
    """Add another shop admin"""
    form = AddShopAdminForm()
    if request.method == "POST":

        if form.validate_on_submit():
            # Check user dosent already exist
            email = request.form["email"]
            if User.query.filter_by(email=email).first() is not None:
                return f"Error, admin with email ({email}) already exists."

            user = User()
            user.email = email
            user.set_password(request.form["password"])
            database.session.add(user)
            database.session.commit()
            flash(f"A new shop admin with email {email} has been added")
        else:
            return "Invalid add shop admin form submission"
        return redirect(url_for('admin.add_shop_admin'))
    else:
        return render_template("admin/add_shop_admin.html", form=form)
Beispiel #29
0
def change_email():
    """Change email of existing user"""
    form = ChangeEmailForm()
    if request.method == "POST":
        email = session.get('user_id', None)
        if email is None:
            return "Email not found in session"

        if form.validate_on_submit():
            user = User.query.filter_by(email=email).first()
            if user is None:
                return "User not found with that email"
            else:
                new_email = request.form["email"]
                user.email = new_email
                database.session.commit()
            flash(f"Email has been updated to {new_email}. Please re-login")
        else:
            return "Invalid email form submission"
        return redirect(url_for('admin.change_email'))
    else:
        return render_template("admin/change_email.html", form=form)
Beispiel #30
0
def connect_stripe_manually():
    form = StripeConnectForm()
    payment_provider = PaymentProvider.query.first()

    if payment_provider.stripe_active:
        stripe_connected = True
    else:
        stripe_connected = False
    if form.validate_on_submit():
        publishable_key = form.data["publishable_key"].strip()
        secret_key = form.data["secret_key"].strip()
        payment_provider.stripe_publishable_key = publishable_key
        payment_provider.stripe_secret_key = secret_key
        payment_provider.stripe_active = True
        database.session.commit()  # Save changes
        return redirect(url_for("admin.dashboard"))
    else:
        return render_template(
            "admin/connect_stripe_manually.html",
            form=form,
            stripe_connected=stripe_connected,
        )