app-MAIL-temp/app/dashboard/views/referral.py

76 lines
2.9 KiB
Python
Raw Normal View History

import re2 as re
2020-11-13 16:18:09 +01:00
2020-04-09 22:39:39 +02:00
from flask import render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.extensions import db
2021-05-10 13:03:44 +02:00
from app.models import Referral, Payout
2020-04-09 22:39:39 +02:00
2020-11-13 16:18:09 +01:00
_REFERRAL_PATTERN = r"[0-9a-z-_]{3,}"
2020-04-09 22:39:39 +02:00
@dashboard_bp.route("/referral", methods=["GET", "POST"])
@login_required
def referral_route():
if request.method == "POST":
2020-05-02 18:11:10 +02:00
if request.form.get("form-name") == "create":
2020-11-13 16:18:09 +01:00
code = request.form.get("code")
if re.fullmatch(_REFERRAL_PATTERN, code) is None:
flash(
"At least 3 characters. Only lowercase letters, "
"numbers, dashes (-) and underscores (_) are currently supported.",
"error",
)
return redirect(url_for("dashboard.referral_route"))
2020-05-02 18:11:10 +02:00
2020-11-13 16:18:09 +01:00
if Referral.get_by(code=code):
flash("Code already used", "error")
return redirect(url_for("dashboard.referral_route"))
2020-05-02 18:11:10 +02:00
name = request.form.get("name")
referral = Referral.create(user_id=current_user.id, code=code, name=name)
db.session.commit()
flash("A new referral code has been created", "success")
return redirect(
url_for("dashboard.referral_route", highlight_id=referral.id)
)
elif request.form.get("form-name") == "update":
referral_id = request.form.get("referral-id")
referral = Referral.get(referral_id)
if referral and referral.user_id == current_user.id:
referral.name = request.form.get("name")
db.session.commit()
flash("Referral name updated", "success")
return redirect(
url_for("dashboard.referral_route", highlight_id=referral.id)
2020-05-02 18:14:09 +02:00
)
elif request.form.get("form-name") == "delete":
referral_id = request.form.get("referral-id")
referral = Referral.get(referral_id)
if referral and referral.user_id == current_user.id:
Referral.delete(referral.id)
db.session.commit()
flash("Referral deleted", "success")
return redirect(url_for("dashboard.referral_route"))
2020-04-09 22:39:39 +02:00
# Highlight a referral
highlight_id = request.args.get("highlight_id")
if highlight_id:
highlight_id = int(highlight_id)
referrals = Referral.query.filter_by(user_id=current_user.id).all()
# make sure the highlighted referral is the first referral
highlight_index = None
for ix, referral in enumerate(referrals):
if referral.id == highlight_id:
highlight_index = ix
break
if highlight_index:
referrals.insert(0, referrals.pop(highlight_index))
2021-05-10 13:03:44 +02:00
payouts = Payout.query.filter_by(user_id=current_user.id).all()
2020-04-09 22:39:39 +02:00
return render_template("dashboard/referral.html", **locals())