def generate_zipped_receipts():
    #email = session.get('email')
    #if email is None:
    #    raise Exception("Not Logged in")
    donor = Donor("*****@*****.**", "name", "contact", "address")
    donation = Donation(datetime.datetime.now(), 100, "cash")
    donor.donations.append(donation)
    db.session.add(donor)
    db.session.commit()
    donor = db.session.query(Donor).filter_by(email_address="*****@*****.**")
    donations = donor.first().donations.all()
    pdfFiles = []
    for donation in donations:
        data = {
            'Amount': donation.amount,
            'ReceiptNo': donation.id,
            'DonationDate': donation.date,
            'OrgName': "Team Everest",
            'OrgAddress': "chennai",
            'DonationMode': donation.mode,
            'DonorName': donor.first().name,
            'DonorAddress': donor.first().address,
            'Certification_Number': "213213dsfdaf3",
            "WordAmount": num2words(donation.amount)
        }
        pdf = makePdf(data)
        pdfFiles.append(pdf)
    s = zipFiles(pdfFiles)
    response_body = open(s).read()
    os.remove(s)
    headers = {"Content-Disposition": "attachment; filename=receipt.zip"}
    return make_response((response_body, '200', headers))
Example #2
0
def register(request):
    if request.method == "GET":
        if request.user.is_authenticated():
            return HttpResponseRedirect("/")
        else:
            return render(request, "register.html", {})
    else:
        username = request.POST.get("username")
        name = request.POST.get("name")
        email = request.POST.get("email")
        password = request.POST.get("password")
        try:
            user = User.objects.get(username = username)
        except User.DoesNotExist:
            pass
        else:
            return HttpResponse("Your username has already been used. Please choose another username.")
        try:
            user = User.objects.get(email = email)
        except User.DoesNotExist:
            pass
        else:
            return HttpResponse("Your email has already been used. Please choose another email.")
        new_user = User(username = username, first_name = name, email = email)
        new_user.set_password(password)
        new_user.active = False
        new_user.save()
        donor = Donor(person = new_user, stored_cash = 0)
        donor.save()
        return HttpResponse("You have been registered. Please log in.")
Example #3
0
 def new_donor(token):
     try:
         body = request.get_json()
         if body is None:
             abort(404)
         new_name = body.get('name')
         new_donation = body.get('donation')
         new_donor = Donor(name=new_name, donation=new_donation)
         new_donor.insert()
         new_donor = Donor.query.filter_by(id=new_donor.id).first()
         return jsonify({'success': True, 'donors': [new_donor.long()]})
     except AuthError:
         abort(422)
Example #4
0
    def _populate_donor_index(self, output_obj):
        """ Populates both donor-index and donor-country-index """

        if not self.country_donors:
            self.country_donors = self.get_and_sort(self.undp_export + '/country_donors_updated.csv', 'id')

        for donor in output_obj.findall("./participating-org[@role='Funding']"):
            obj = Donor()
            country_obj = CountryDonor()
            ref = donor.get(obj.id.key)
            if ref:

                for item in self.country_donors:
                    if ref == item['id']:

                        # Skip the loop if the ref already is added
                        if ref not in self.donorindex.pks:
                            obj.id.value = ref

                            obj.name.value = donor.text or "Unknown"

                            if item['donor_type_lvl1'] == 'PROG CTY' or item['donor_type_lvl1'] == 'NON_PROG CTY':
                                obj.country.value = item['donor_type_lvl3'].replace(" ", "")
                            elif item['donor_type_lvl1'] == 'MULTI_AGY':
                                obj.country.value = item['donor_type_lvl1'].replace(" ", "")
                            else:
                                obj.country.value = 'OTH'

                            self.donorindex.add(obj.id.value, obj)

                        if item['donor_type_lvl3'] not in self.countrydonorindex.pks:
                            country_obj.id.value = item['donor_type_lvl3']
                            country_obj.name.value = item['donor_type_lvl3_descr']

                            self.countrydonorindex.add(item['donor_type_lvl3'], country_obj)
Example #5
0
def donor_add():

    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        donation = float(request.form['donation'])

        q = Queries()  # noqa F403
        d = Donor()  # noqa F403
        d.first_name = first_name
        d.last_name = last_name
        q.insert_donor_donation(d, float(donation))
        return redirect(url_for('donors_list'))

    if 'first_name' not in session or 'last_name' not in session:
        return render_template('donor_add.jinja2')
Example #6
0
def add_people():

    FIRST_NAME = 0
    LAST_NAME = 1

    donors = [('Jim', 'Halpert'), ('Pam', 'Beesley'), ('Dwight', 'Shrute'),
              ('Michael', 'Scott'), ('Andy', 'Bernard')]

    try:
        db.connect()
        for donor in donors:
            code = base64.b32encode(os.urandom(8)).decode().strip('=')
            with db.transaction():
                n = Donor.create(  # noqa F403
                    code=code,
                    first_name=donor[FIRST_NAME],
                    last_name=donor[LAST_NAME])
                n.save()

        logger.info('People added.')

    except Exception as e:
        logger.info(e)

    finally:
        logger.info('database closes')
        db.close()
def generate_zipped_receipts():
    #email = session.get('email')
    #if email is None:
    #    raise Exception("Not Logged in")
    donor = Donor("*****@*****.**","name","contact","address")
    donation = Donation(datetime.datetime.now(), 100, "cash")
    donor.donations.append(donation)
    db.session.add(donor)
    db.session.commit()
    donor = db.session.query(Donor).filter_by(email_address = "*****@*****.**")
    donations = donor.first().donations.all()
    pdfFiles = []
    for donation in donations:
        data = {'Amount':donation.amount, 'ReceiptNo':donation.id, 'DonationDate': donation.date, 'OrgName': "Team Everest", 'OrgAddress': "chennai", 'DonationMode': donation.mode, 'DonorName':donor.first().name, 'DonorAddress' : donor.first().address, 'Certification_Number' : "213213dsfdaf3", "WordAmount":num2words(donation.amount) }
        pdf = makePdf(data)
        pdfFiles.append(pdf)
    s = zipFiles(pdfFiles)
    response_body = open(s).read()
    os.remove(s)
    headers = {"Content-Disposition": "attachment; filename=receipt.zip"}
    return make_response((response_body,'200', headers))
def create_donor():
    print(request.form)
    donor = Donor.query.filter_by(email_address=request.form['email']).first()
    if donor is not None:
        abort(400)
    password = ''.join(
        random.choice(string.ascii_letters + string.digits) for _ in range(6))
    donor = Donor(email_address=request.form['email'],
                  password_sha256=hashlib.sha256(password).hexdigest(),
                  is_admin=False,
                  name=request.form['name'],
                  contact_number=request.form['contact_number'],
                  address=request.form['address'])
    db.session.add(donor)
    db.session.commit()
    sendEmail(donor.email_address, donor_created_text.format(password), None)
    return redirect(request.referrer)
def create_donation_in_db(form):
    donor = Donor.query.filter_by(email_address=form['donor']).first()
    if donor is None:
        password = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(6))
        donor = Donor(email_address=form['donor'],
                      password_sha256=hashlib.sha256(password).hexdigest(),
                      is_admin=False)
        db.session.add(donor)
        db.session.commit()
        sendEmail(donor.email_address, donor_created_text.format(password),
                  None)
    donation = Donation(date=form['donationDate'],
                        amount=form['donationAmount'],
                        mode=form['donationMode'],
                        cheque_number=form['chequeNumber'],
                        cheque_date=form['chequeDate'],
                        transcation_id=form['transactionId'])
    donor.donations.append(donation)
    db.session.add(donor)
    db.session.commit()
    return donation
def readExcel(inputFile):
    donation_ids = []
    fields = {
        "DonationDate": "date",
        "Amount": "amount",
        "DonationMode": "mode",
        "ModeDescription": "mode_description",
        "DonorEmail": "email_address",
        "Name": "name",
        "ContactNo": "contact_number",
        "Address": "address"
    }
    order_of_fields = {}
    workbook = xlrd.open_workbook(inputFile)
    worksheet = workbook.sheet_by_index(0)
    num_rows = worksheet.nrows - 1
    num_cells = worksheet.ncols - 1
    curr_row = -1
    if num_cells > 0:
        curr_row += 1
        curr_cell = -1
        while curr_cell < num_cells:
            curr_cell += 1
            cell_value = worksheet.cell_value(curr_row, curr_cell)
            order_of_fields[cell_value] = curr_cell
    while curr_row < num_rows:
        row = []
        curr_row += 1
        row = worksheet.row(curr_row)
        print 'Row:', curr_row
        curr_cell = -1
        while curr_cell < num_cells:
            curr_cell += 1
            cell_type = worksheet.cell_type(curr_row, curr_cell)
            cell_value = worksheet.cell_value(curr_row, curr_cell)
            if (cell_type > 4 or cell_type == 0):
                row.append(None)
            elif (cell_type == 3):
                year, month, day, hour, minute, second = xlrd.xldate_as_tuple(
                    cell_value, workbook.datemode)
                row.append(
                    datetime.datetime(year, month, day, hour, minute, second))
            else:
                row.append(cell_value)

        email = row[order_of_fields["DonorEmail"]].value
        if not email:
            raise Exception("no email")
        donor = get_donor_by_email(email)
        is_new_donor = False
        if not donor:
            password = ''.join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(6))
            name = row[order_of_fields["Name"]].value
            address = row[order_of_fields["Address"]].value
            contact_number = row[order_of_fields["ContactNo"]].value
            donor = Donor(email_address=email,
                          password_sha256=hashlib.sha256(password).hexdigest(),
                          is_admin=False,
                          name=name,
                          contact_number=contact_number,
                          address=address)
            is_new_donor = True
        date = row[order_of_fields["DonationDate"]].value
        year, month, day, hour, minute, second = xlrd.xldate_as_tuple(
            date, workbook.datemode)
        date = datetime.datetime(year, month, day, hour, minute, second)
        amount = row[order_of_fields["Amount"]].value
        mode = row[order_of_fields["DonationMode"]].value
        mode_description = row[order_of_fields["ModeDescription"]].value
        donation = Donation(date, amount, mode, mode_description)
        donor.donations.append(donation)
        db.session.add(donor)
        db.session.commit()
        if is_new_donor:
            sendEmail(donor.email_address, donor_created_text.format(password),
                      None)
        donation_ids.append(donation.id)
    return donation_ids
Example #11
0
 def createDonor(self, props): 
     donor = Donor()
     donor.name = "%s %s" % (props['first_name'], props['last_name'])
     donor.email = urllib.unquote( props['payer_email'] )
     donor.put()
     return donor 
Example #12
0
 def getDonor(self, email):
     return Donor.all().filter('email', email).get()
from blueprints.frontend import frontend
from blueprints.backend import backend

from models import db, Donor
from login_manager import lm

app = Flask(__name__)
app.config.from_object('default_settings')
app.config.from_envvar('EVEREST_SETTINGS', silent=True)
app.register_blueprint(frontend, url_prefix='/')
app.register_blueprint(backend, url_prefix='/backend/')
app.secret_key = 'why would I tell you my secret key?'
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = set(['xls', 'xlsx', 'csv'])

db.init_app(app)
lm.init_app(app)
lm.login_view = '/login'

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        if Donor.query.filter_by(
                email_address="*****@*****.**").first() is None:
            donor = Donor(email_address='*****@*****.**',
                          password_sha256=hashlib.sha256('1111').hexdigest(),
                          is_admin=True)
            db.session.add(donor)
            db.session.commit()
    app.run(host='0.0.0.0', port=8000)
Example #14
0
 def createDonor(self, props):
     donor = Donor()
     donor.name = "%s %s" % (props['first_name'], props['last_name'])
     donor.email = urllib.unquote(props['payer_email'])
     donor.put()
     return donor
Example #15
0
 def getDonor(self, email):
     return Donor.all().filter('email', email).get()