Esempio n. 1
0
def share_to_friends():
    phone_numbers = request.values.get('Nums')
    referrer = request.values.get('From')
    user = User.objects(phone_number=str(referrer)[-10:]).first()
    time = request.values.get('Timestamp')
    for phone_number in phone_numbers:
        referral = Referral(phone_number=str(phone_number)[-10:],
                            date_referred=datetime.datetime.fromtimestamp(
                                time / 1000.0))
        referral.save()
        user.referrals.append(referral)
    user.save()
    return jsonify(success=True)
Esempio n. 2
0
def referral(id):
    if request.method == 'GET':
        rewards = Referral.objects(itemid=id)
        return get_items(request, rewards)
    if request.method == 'POST':
        item = Referral.objects(itemid=id).first()
        if request_has_json():
            item.description = request.json['description']
            item.save()
            return 'Updated'
        else:
            form = ReferralForm(request.form)
            form.populate_obj(item)
            item.save()
            return render_template('list_referrals.html', items=[item])
Esempio n. 3
0
def referral_claim():
    if not use_referrals:
        return bad_request(web_utils.NOT_AVAILABLE)
    token, api_key, err_response = auth_request_get_single_param(db, "token")
    if err_response:
        return err_response
    if not api_key.user.has_role(
            Role.ROLE_ADMIN) and not api_key.user.has_role(
                Role.ROLE_REFERRAL_CLAIMER):
        return bad_request(web_utils.UNAUTHORIZED)
    ref = Referral.from_token(db.session, token)
    if not ref:
        return bad_request(web_utils.NOT_FOUND)
    if ref.status != ref.STATUS_CREATED:
        return bad_request(web_utils.NOT_FOUND)
    # send referral rewards
    category = Category.from_name(db.session, Category.CATEGORY_REFERRAL)
    if not category:
        return bad_request(web_utils.INVALID_CATEGORY)
    if ref.reward_sender <= 0:
        return bad_request(web_utils.INVALID_AMOUNT)
    if ref.reward_recipient_type == ref.REWARD_TYPE_FIXED and ref.reward_recipient <= 0:
        return bad_request(web_utils.INVALID_AMOUNT)
    reason = f'{ref.token}: reward for referral'
    _reward_create(api_key.user, reason, category, ref.recipient,
                   ref.reward_sender, 'Thank you for referring a friend')
    if ref.reward_recipient_type == ref.REWARD_TYPE_FIXED:
        _reward_create(api_key.user, reason, category, ref.recipient,
                       ref.reward_recipient, 'Thank you for using our service')
    ref.status = ref.STATUS_CLAIMED
    db.session.add(ref)
    db.session.commit()
    return jsonify(dict(referral=ref.to_json()))
Esempio n. 4
0
def referral_create():
    if not use_referrals:
        return bad_request(web_utils.NOT_AVAILABLE)
    recipient, api_key, err_response = auth_request_get_single_param(
        db, "recipient")
    if err_response:
        return err_response
    if not utils.is_email(recipient):
        return bad_request(web_utils.INVALID_EMAIL)
    recipient = recipient.lower()
    user = User.from_email(db.session, recipient)
    if user:
        time.sleep(5)
        return bad_request(web_utils.USER_EXISTS)
    reward_sender_type = app.config["REFERRAL_REWARD_TYPE_SENDER"]
    reward_sender = app.config["REFERRAL_REWARD_SENDER"]
    reward_recipient_type = app.config["REFERRAL_REWARD_TYPE_RECIPIENT"]
    reward_recipient = app.config["REFERRAL_REWARD_RECIPIENT"]
    recipient_min_spend = app.config["REFERRAL_RECIPIENT_MIN_SPEND"]
    ref = Referral(api_key.user, recipient, reward_sender_type, reward_sender,
                   reward_recipient_type, reward_recipient,
                   recipient_min_spend)
    utils.email_referral(logger, ref)
    db.session.add(ref)
    db.session.commit()
    return 'ok'
Esempio n. 5
0
def read_all_admin_view(m: Type[M], **kwargs) -> List[M]:
    """
    Queries the database for all Patients or Referrals

    :param m: Type of the model to query for
    :param kwargs: limit, page, search, sortBy, sortDir

    :return: A list of models from the database
    """

    search_param = (None if kwargs.get("search", None) == "" else kwargs.get(
        "search", None))
    sql_str = SQL.get_sql_string(search_param, **kwargs)
    sql_str_table = SQL.get_sql_table_operations(m)

    if m.schema() == Patient.schema():
        if search_param is not None:
            return db_session.execute(sql_str_table + sql_str)
        else:
            return db_session.execute(sql_str_table + sql_str)

    if m.schema() == Referral.schema():
        if search_param is not None:
            return db_session.execute(sql_str_table + sql_str)
        else:
            return db_session.execute(sql_str_table + sql_str)
Esempio n. 6
0
def referral_list():
    if not use_referrals:
        return bad_request(web_utils.NOT_AVAILABLE)
    api_key, err_response = auth_request(db)
    if err_response:
        return err_response
    refs = Referral.from_user(db.session, api_key.user)
    refs = [ref.to_json() for ref in refs]
    return jsonify(dict(referrals=refs))
Esempio n. 7
0
def refer_referral():
    response = {'validity': 'invalid'}
    data = request.json or request.form
    data = dict(data)

    # legacy webhook format
    if 'flow_base_language' in data:
        code = data.get('text')[0]
        contact = data.get('contact')[0]
    else:
        code = data.get('results')['refcode']['value']
        contact = data.get('contact')['uuid']

    if RefCode.get_by_code(code):
        if not Referral.is_duplicate(contact, code):
            Referral.create(contact, code)
            response['validity'] = 'valid'
    return create_response(response)
Esempio n. 8
0
def refer_referral():
    response = {'validity': 'invalid'}
    data = request.json or request.form
    data = dict(data)

    # legacy webhook format
    if 'flow_base_language' in data:
        code = data.get('text')[0]
        contact = data.get('contact')[0]
    else:
        code = data.get('results')['refcode']['value']
        contact = data.get('contact')['uuid']

    if RefCode.get_by_code(code):
        if not Referral.is_duplicate(contact, code):
            Referral.create(contact, code)
            response['validity'] = 'valid'
    return create_response(response)
Esempio n. 9
0
def job_referral(jobid):
    if request.method == 'GET':
        job = Job.objects(jobid=jobid).first()
        referrals = Referral.objects(job=job)
        return render_template('_referrals.html', referrals=referrals)
    if request.method == 'POST':
        if request_has_json():
            try:
                job = Job.objects(jobid=int(request.json['job'])).first()
                request.json['job'] = str(job.id)
                model = Referral.from_json(
                    json.dumps(request.json, default=json_util.default))
                model.status = 'Submitted'
                model.save()
                return jsonify(item='Submitted')
            except ValidationError as e:
                return jsonify(item=str(e))
        else:
            print 'Request does not have JSON!'
Esempio n. 10
0
def referral_remind():
    if not use_referrals:
        return bad_request(web_utils.NOT_AVAILABLE)
    token, api_key, err_response = auth_request_get_single_param(db, "token")
    if err_response:
        return err_response
    ref = Referral.from_token_user(db.session, token, api_key.user)
    if not ref:
        return bad_request(web_utils.NOT_FOUND)
    if ref.status != ref.STATUS_CREATED:
        return bad_request(web_utils.NOT_FOUND)
    utils.email_referral(logger, ref)
    return 'ok'
Esempio n. 11
0
def referral_validate():
    if not use_referrals:
        return bad_request(web_utils.NOT_AVAILABLE)
    token, api_key, err_response = auth_request_get_single_param(db, "token")
    if err_response:
        return err_response
    if not api_key.user.has_role(
            Role.ROLE_ADMIN) and not api_key.user.has_role(
                Role.ROLE_REFERRAL_CLAIMER):
        return bad_request(web_utils.UNAUTHORIZED)
    ref = Referral.from_token(db.session, token)
    if not ref:
        return bad_request(web_utils.NOT_FOUND)
    if ref.status != ref.STATUS_CREATED:
        return bad_request(web_utils.NOT_FOUND)
    return jsonify(dict(referral=ref.to_json()))
Esempio n. 12
0
def referrals():
    if request.method == 'POST':
        form = ReferralForm(request.form)
        if request_has_json():
            try:
                json_data = json.dumps(request.json, default=json_util.default)
                model = Referral.from_json(json_data)
                model.save()
            except ValidationError as e:
                return jsonify(item=str(e))
        else:
            if form.validate():
                form.save()
            else:
                return render_template('add_referral.html', form=form)
        return list_referrals()
    else:
        return list_referrals()
Esempio n. 13
0
def create():
    """Create a new post for the current user."""
    db_session = current_app.config["db_session"]
    user = db_session.query(User).filter(User.id_ == session.get("user_id")).first()
    if request.method == 'POST':
        content = {}
        content["user_id"] = user.id_
        content["title"] = request.form['title']
        content["enum"] = request.form['enum']
        content["turnover"] = request.form['turnover']
        pdate = request.form['project_date']
        content["project_date"] = datetime.strptime(pdate, "%Y-%m-%d").date()
        content["budget"] = request.form['budget']
        content["description"] = request.form['desc']

        referral = Referral(**content)
        db_session.add(referral)
        db_session.commit()
        return redirect(url_for('index'))

    return render_template('blog/create.html', user=user)
Esempio n. 14
0
def job(jobid):
    if request.method == 'GET':
        job = Job.objects(jobid=int(jobid)).first()
        stages = Stage.objects(job=job)
        ref = Referral.objects(job=job)
        if request_wants_json():
            return mongodoc_jsonify(item=job.to_mongo())
        else:
            return render_template('list_job.html', job=job, referrals=ref, stages=stages)
    if request.method == 'PUT':
        job = Job.objects(jobid=int(jobid)).first()
        if request_has_json():
            json_data = json.dumps(request.json, default=json_util.default)
            model = Job.from_json(json_data)
            job.locationName = model.locationName
            job.title = model.title
            job.permOrCont = model.permOrCont
            job.remuneration = model.remuneration
            job.tSkill1 = model.tSkill1
            job.tSkill2 = model.tSkill2
            job.tSkill3 = model.tSkill3
            job.pSkill1 = model.pSkill1
            job.pSkill2 = model.pSkill2
            job.pSkill3 = model.pSkill3
            job.qalNeeded = model.qalNeeded
            job.qal = model.qal
            job.projChar1 = model.projChar1
            job.projChar2 = model.projChar2
            job.projChar3 = model.projChar3
            job.teamChar1 = model.teamChar1
            job.teamChar2 = model.teamChar2
            job.teamChar3 = model.teamChar3
            job.save()
            '''Job.objects(jobid=int(jobid)).first().update(json_data)'''
            return mongodoc_jsonify(item=job.reload().to_mongo())
        else:
            form = AddJobForm(request.form)
            form.populate_obj(job)
            job.save()
            return render_template('list_job.html', jobs=[job])
def get_sql_table_operations(m: Type[M]) -> str:
    if m.schema() == Patient.schema():
        return (
            "SELECT p.patientName, "
            "p.patientId, "
            "p.villageNumber, "
            "r.trafficLightStatus, "
            "r.dateTimeTaken"
            " FROM patient p LEFT JOIN reading r ON r.readingId = "
            "(SELECT r2.readingId FROM reading r2 WHERE r2.patientId=p.patientId"
            " ORDER BY r2.dateTimeTaken DESC LIMIT 1) ")

    elif m.schema() == Referral.schema():
        return ("SELECT p.patientId,"
                " p.patientName,"
                " p.villageNumber,"
                " rd.trafficLightStatus,"
                " rf.dateReferred,"
                " rf.isAssessed,"
                " rf.id"
                " FROM referral rf"
                " JOIN patient p ON rf.patientId=p.patientId"
                " JOIN reading rd ON rd.readingId=rf.readingId")
Esempio n. 16
0
def user_job_referrals(jobid, userid):
    job = Job.objects(jobid=int(jobid)).first()
    referrals = Referral.objects(job=job, user=userid)
    return jsonify(item=[(dict(itemid=ref.itemid, job=ref.job.jobid, user=ref.user, referenceName=ref.referenceName, reference=ref.reference, status=ref.status))for ref in referrals])
Esempio n. 17
0
def change_job_referral_status(jobid, refid, value):
    job = Job.objects(jobid=int(jobid)).first()
    referral = Referral.objects(job=job, itemid=refid).first()
    referral.status = value
    referral.save()
    return job_referral(jobid)
Esempio n. 18
0
def list_referrals():
    items = Referral.objects()
    print str(items)
    return render_template('list_referrals.html', items=items)
Esempio n. 19
0
def delete_all_refs():
    Referral.objects().delete()
    return list_referrals()
Esempio n. 20
0
def edit_referral_form(id):
    item = Referral.objects(itemid=id).first()
    form = ReferralForm(request.form, obj=item)
    return render_template('add_referral.html', form=form, edit=True)
Esempio n. 21
0
def change_referral_status(id, value):
    item = Referral.objects(itemid=id).first()
    item.status = value
    item.save()
    return 'Done'
Esempio n. 22
0
def register():
    from random import randint

    from sbb import application, db
    from lib.email2 import send_email
    from models import User, ReferralProgram, Account, Referral

    referral = None
    if 'referral' in session:
        referral = session['referral']

    if request.method == 'GET':
        session['a'] = randint(1, 10)
        session['b'] = randint(1, 10)
        referral = None
        if 'referral' in session:
            referral = session['referral']
        return render_template('home/register.html',
                               referral=referral,
                               a=session['a'],
                               b=session['b'])
    form = RegistrationForm(request.form)
    if form.validate_on_submit():
        captcha = form.captcha.data.strip()
        if captcha != '' and int(captcha) == session['a'] + session['b']:
            cur = User.query.filter_by(username=form.username.data).first()
            ecur = User.query.filter_by(email=form.email.data).first()

            if cur is None and ecur is None:

                # refereal program 521
                rp = ReferralProgram.query.filter_by(id=1).first()

                # Account User
                account = Account(0, 0)
                account.referralProgram = rp
                db.session.add(account)
                #db.session.commit()

                user = User(username=form.username.data,
                            password=form.password.data,
                            email=form.email.data)
                user.account = account
                if form.fb.data != '':
                    user.fb = form.fb.data
                if form.skype.data != '':
                    user.skype = form.skype.data
                user.pin = form.pin_number.data
                db.session.add(user)
                #db.session.commit()

                # referral account
                refUsername = form.refemail.data.strip()
                if refUsername != '':
                    refUser = User.query.filter_by(
                        username=refUsername).first()
                    if refUser:
                        referral = Referral(accountId=account.id)
                        referral.referralAccount = refUser.account
                        db.session.add(referral)
                    else:
                        flash("Wrong referral. Referral data skiped.")

                db.session.commit()

                token = generate_confirmation_token(user.email,
                                                    application.config)
                confirm_url = url_for('home.confirm_email',
                                      token=token,
                                      _external=True)
                html = render_template('home/activate_email.html',
                                       confirm_url=confirm_url)
                subject = "Please confirm your email"
                send_email(user.email, subject, html, application.config)

                login_user(user)
                flash('A confirmation email has been sent via email.',
                      'success')
                return redirect(url_for('home.unconfirmed'))
            else:
                flash('User with specified data already exists in a system',
                      'warning')
        else:
            flash("Wrong captcha")
    else:
        flash_errors(form)
    session['a'] = randint(1, 10)
    session['b'] = randint(1, 10)
    return render_template('home/register.html',
                           referral=referral,
                           a=session['a'],
                           b=session['b'])