Ejemplo n.º 1
0
def get_donation():
    if not session.get('current_building_id'):
        redirect(url_for('donation_address'))

    form = DonationForm()
    conn_error = request.args.get('conn_error')
    validate_campaign_status(current_user.team.campaign)
    if form.validate_on_submit():
        session['current_donation'] = {
            "amount": form.amount.data,
            "payment_type": form.payment_type.data,
            "team_id": current_user.team_id
        }
        if form.payment_type.data == 'bit':
            return redirect(url_for('bit_donation'))
        elif form.payment_type.data == 'PayPal':
            # Create a paypal payment and redirect to the authorization process via paypal's api
            try:
                payment = pp.create_payment(
                    form.amount.data,
                    f'{HOST_URL}donation_address/donation/paypal/execute_paypal_donation',
                    f'{HOST_URL}donation_address/donation')
                return redirect(pp.authorize_payment(payment))
            except (ConnectionError, RuntimeError):
                conn_error = True  # if there's a connection error / unexpected error, display an error in the donation page
                generate_automate_report('paypal')
        if not conn_error:
            return redirect(url_for('send_invoice'))
    return render_template('/donation.html', form=form, conn_error=conn_error)
Ejemplo n.º 2
0
def manage_campaign_neighborhoods(campaign_id):
    campaign = Campaign.query.get_or_404(campaign_id)
    form = AddNeighborhood()

    # Calling `validate` for the specific field due to flask forms not liking dynamic loaded selection field
    if form.is_submitted(
    ) and form.neighborhood_id.data and form.number_of_teams.validate(form):
        validate_campaign_status(campaign)
        teams_users_data = create_teams_and_users(
            campaign_id, int(form.neighborhood_id.data),
            int(form.number_of_teams.data))
        flash(json.dumps(teams_users_data), 'users_data')
        return redirect(
            url_for('manage_campaign_neighborhoods', campaign_id=campaign_id))

    # Getting the available and selected neighborhoods
    available_neighborhoods, campaign_neighborhoods = get_response_campaign_neighborhoods(
        campaign)

    # Building neighborhood selection choices
    form.neighborhood_id.choices = list(
        map(lambda x: (x['id'], x['name']), available_neighborhoods))
    # Set default number of teams
    form.number_of_teams.process_data(1)

    return render_template('/campaign_neighborhoods_selection.html',
                           campaign_neighborhoods=campaign_neighborhoods,
                           form=form,
                           campaign_id=campaign_id,
                           loads_json=json.loads)
Ejemplo n.º 3
0
def edit_campaign(campaign_id):
    return_url = request.referrer or '/'
    campaign = Campaign.query.get_or_404(campaign_id)
    form = CreateCampaignForm()
    city = campaign.city
    del form.city
    if form.validate_on_submit():
        validate_campaign_status(campaign)
        if validate_name(form.name.data, campaign.name):
            campaign.name = form.name.data
            campaign.start_date = form.start_date.data
            campaign.goal = form.goal.data
            db.session.commit()
            flash('!הקמפיין עודכן בהצלחה', 'success')
            return redirect(
                url_for('campaign_control_panel', campaign_id=campaign.id))
        form.name.errors.append('קמפיין בשם הזה כבר קיים, אנא בחר שם אחר.')
    elif request.method == 'GET':
        form.name.data = campaign.name
        form.start_date.data = campaign.start_date
        form.goal.data = campaign.goal
    return render_template('/create_campaign.html',
                           form=form,
                           city=city,
                           legend="עריכת קמפיין",
                           return_url=return_url)
Ejemplo n.º 4
0
def pp_execute():
    """ This route gets the payment authorization and execute the transaction itself via paypal's api """
    validate_campaign_status(current_user.team.campaign)

    pp_req = request.args.to_dict()
    if pp.execute_payment(pp_req):
        session['current_donation']['transaction_id'] = pp_req['paymentId']
        session.modified = True
        return redirect(url_for('send_invoice'))
    return redirect(url_for('get_donation', conn_error=True))
Ejemplo n.º 5
0
def bit_donation():
    if not session.get('current_building_id'):
        redirect(url_for('donation_address'))

    form = BitForm()
    if form.validate_on_submit():
        validate_campaign_status(current_user.team.campaign)
        session['current_donation'][
            'transaction_id'] = form.transaction_id.data
        session.modified = True
        return redirect(url_for('send_invoice'))
    return render_template('/bit_donation.html', form=form)
Ejemplo n.º 6
0
def create_new_team_for_route(campaign_id, neighborhood_id):
    # Safe guards
    campaign = Campaign.query.get_or_404(campaign_id)
    Neighborhood.query.get_or_404(neighborhood_id)

    validate_campaign_status(campaign)

    # Create 1 new team
    new_team_user_data = create_teams_and_users(campaign_id, neighborhood_id,
                                                1)[0]
    new_team_data = db.session.query(Team).join(User).filter(
        User.username == new_team_user_data['username']).first().serialize()

    return jsonify({'user': new_team_user_data, 'team': new_team_data})
Ejemplo n.º 7
0
def delete_team_route(campaign_id, neighborhood_id, team_id):
    # Safe guards
    campaign = Campaign.query.get_or_404(campaign_id)
    Neighborhood.query.get_or_404(neighborhood_id)
    team = Team.query.get_or_404(team_id)

    validate_campaign_status(campaign)

    delete_team_dependencies(team)

    db.session.commit()
    db.session.delete(team)
    db.session.commit()

    return jsonify({'status': 'OK'})
Ejemplo n.º 8
0
def delete_neighborhood(campaign_id, neighborhood_id):
    # Safe guards
    campaign = Campaign.query.get_or_404(campaign_id)
    neighborhood = Neighborhood.query.get_or_404(neighborhood_id)

    validate_campaign_status(campaign)

    for team in neighborhood.teams:
        delete_team_dependencies(team)

    db.session.commit()
    for team in neighborhood.teams:
        db.session.delete(team)
    db.session.commit()

    return jsonify({'status': 'OK'})
Ejemplo n.º 9
0
def export_user_data(campaign_id, neighborhood_id):
    # Safe guards
    campaign = Campaign.query.get_or_404(campaign_id)
    Neighborhood.query.get_or_404(neighborhood_id)

    validate_campaign_status(campaign)

    users = db.session.query(User).join(Team).join(Campaign).join(
        Neighborhood).filter(Campaign.id == campaign_id).filter(
            Neighborhood.id == neighborhood_id)

    # Rest the users' passwords before exporting the file
    User.reset_passwords(users)
    db.session.commit()

    excel_data = export_neighborhood_to_excel(campaign_id, neighborhood_id,
                                              users)

    return send_file(excel_data,
                     attachment_filename="output.xlsx",
                     as_attachment=True)
Ejemplo n.º 10
0
def upsert_routes(campaign_id, neighborhood_id):
    # Validate the parameters
    campaign = Campaign.query.get_or_404(campaign_id)
    Neighborhood.query.get_or_404(neighborhood_id)
    body = request.get_json()

    validate_campaign_status(campaign)

    for team_id in body.keys():
        team = Team.query.get_or_404(team_id)
        if team.campaign_id != campaign_id:
            # The user wanted to change team for different campaign - blocking the changes
            return jsonify({"message": "Team not found"}), 404

        # Delete all the buildings
        team.buildings = []
        for building_id in body[team_id]:
            # If the building exists, add it to the team
            b = Building.query.get_or_404(building_id)
            team.buildings.append(b)

    db.session.commit()
    return jsonify({"status": "OK"})
Ejemplo n.º 11
0
def send_invoice():
    if not session.get('current_building_id'):
        redirect(url_for('donation_address'))

    paper_form = PaperInvoiceForm()
    digital_form = DigitalInvoiceForm()
    conn_error = False  # This way we make sure the conn error will appear only when there's an unexpected error.
    # first we'll check if the forms are validated, so we won't commit the donation with an invoice error.
    if paper_form.submit_p.data and paper_form.validate_on_submit() or \
            digital_form.submit_d.data and digital_form.validate_on_submit():
        validate_campaign_status(current_user.team.campaign)
        # create donation object:
        donation = Donation(
            amount=session['current_donation']['amount'],
            payment_type=session['current_donation']['payment_type'],
            team_id=session['current_donation']['team_id'],
            transaction_id=session['current_donation'].get('transaction_id'),
            building_id=session['current_building_id'])
        building = Building.query.get_or_404(session['current_building_id'])

        # checking what kind of invoice was requested, validate It's information and commit it:
        new_invoice = Invoice()
        try:
            if paper_form.submit_p.data:
                new_invoice.reference_id = paper_form.reference_id.data
                new_invoice.type = INVOICE_TYPES['PAPER']
            else:
                clean_address = building.address.split(",")[0].strip()
                clean_city = building.address.split(",")[1].strip()
                # Try to create a client in Green Invoice API and send the invoice to the client
                token = gi.get_bearer_token()
                client_id = gi.create_new_client(
                    token,
                    digital_form.donor_name.data,
                    digital_form.mail_address.data,
                    digital_form.donor_id.data,
                    address=clean_address,
                    city=clean_city)
                reference_id = gi.send_invoice(token,
                                               digital_form.mail_address.data,
                                               client_id, donation.amount,
                                               donation.payment_type)
                new_invoice.type = INVOICE_TYPES['DIGITAL']
                new_invoice.reference_id = reference_id
        except (ConnectionError, RuntimeError):
            conn_error = True  # if there's a connection error or unexpected error, display an error in the invoice page
            generate_automate_report('invoice')
        except ValueError:
            digital_form.donor_id.errors.append("מספר ת.ז אינו תקין")
        else:

            # If all went well, commit the donation.
            db.session.add(donation)
            db.session.commit()

            # after we committed the donation, we get it's id for the invoice FK and commit the invoice.
            new_invoice.donation_id = donation.id
            db.session.add(new_invoice)
            db.session.commit()
            return redirect(url_for('donation_end'))
    return render_template('/invoice.html',
                           paper_form=paper_form,
                           digital_form=digital_form,
                           conn_error=conn_error)