def read_and_process_donations(): global donations, repeats with open(FIELD_POSITIONS_FILE, 'r') as p_file: positions = json.load(p_file) with open(DONATIONS_FILE, 'r') as d_file: lines = d_file.readlines() for line in lines: line = line.split('|') new_donation = Donation( cmte_id=line[positions['CMTE_ID']], name=line[positions['NAME']], zip_code=line[positions['ZIP_CODE']], transaction_date=line[positions['TRANSACTION_DT']], transaction_amount=line[positions['TRANSACTION_AMT']], other_id=line[positions['OTHER_ID']] ) if new_donation.is_clean(): donations.append(new_donation) is_repeat = is_repeat_donor(new_donation) repeats.append(is_repeat) if is_repeat: add_related_donations(new_donation)
def append(self, donor, amount): """Add a donor name and an amount to db.""" # Reminder: Model(name=name).save(force_insert=True) is for the field # with non-autogenerated Primary Key. new_donor = Person(person_name=donor) # import ipdb; ipdb.set_trace() # Here I had a problem with save to db new_donor.save(force_insert=True) # Reminder: Model.create() means 'instatitate-then-save' Donation.create(person_name=donor, donation=amount)
def post(self, request): """ Create donation record in database :param request: Key value pair data :return: status & respective message """ data = request.data try: donation = Donation(**data) donation.save() LOGGER.info("Donation created successfully") except Exception, error: LOGGER.error("Error:%s", str(error)) return Response({"status": "FAILED", "message": str(error)})
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 donors(self): """Load donors from db and return it as a Donors class object.""" try: # Get donor info from db and convert it into Donors class which # a create_report() method to generate the report dict_donors_gifts = {} donors = Person.select().order_by(Person.person_name) donations = Donation.select() query = peewee.prefetch(donors, donations) # Iterate over the query and collect all data into a dict # with donors as keys and donations as lists of values for donor in query: dict_donors_gifts[donor.person_name] = [] for gift in donor.donations: dict_donors_gifts[donor.person_name].append( float(gift.donation)) # Convert the dict with donors as keys and donations as values into # a Donors class object return Donors([ SingleDonor(key, value) for key, value in dict_donors_gifts.items() ]) except Exception as e: print("Having a problems with loading the db because", e)
def add_donations(): DONATION_AMT = 0 LAST_NAME = 1 donations = [(1.0, 'Halpert'), (1000.0, 'Beesley'), (2000.0, 'Beesley'), (3000.0, 'Beesley'), (2.0, 'Shrute'), (3.0, 'Shrute'), (10.0, 'Scott'), (20.0, 'Scott'), (30.0, 'Scott'), (10.0, 'Bernard'), (20.0, 'Bernard'), (30.0, 'Bernard')] try: db.connect() for donation in donations: with db.transaction(): n = Donation.create( # noqa F403 donation=donation[DONATION_AMT], donor=donation[LAST_NAME]) n.save() logger.info('Donations added.') except Exception as e: logger.info(e) finally: logger.info('database closes') db.close()
def populate_db(): """Populate DB with initial donor and gifts data.""" # Populate db with donors - using Model(name=name).save(force_insert=True) person_name = 0 people = [("Bill Murray", ), ("Woody Harrelson", ), ("Jesse Eisenberg", )] try: for person in people: new_person = Person(person_name=person[person_name]) new_person.save(force_insert=True) print('add success') print('Person length:', len(Person), type(Person)) for person in Person: print('Added name to Person table:', person.person_name) except Exception as e: print("db probably already exist with these data because", e) return finally: print("In first finally clause") # Populate db with donations - using Model(name=name).save() method donor_person = 0 donation = 1 donations = [("Bill Murray", 125), ("Bill Murray", 1.0), ("Woody Harrelson", 71.5), ("Woody Harrelson", 1.25), ("Jesse Eisenberg", 99.99), ("Jesse Eisenberg", 1.75)] try: for gift in donations: new_gift = Donation(person_name=gift[donor_person], donation=gift[donation]) new_gift.save() print('add success') print('Donation length:', len(Donation), type(Person)) for gift in Donation: print('Added gift to Donation table:', gift.donation) except Exception as e: print(e) finally: print("in second finally clause")
def view_registry(cat, slug): category = REGISTRY_TYPES.get(cat, None) if not category: flash('The registry category does not exist', 'error') return redirect(url_for('.index')) registry = category.get_by_slug(slug) if not registry: flash('The registry does not exist', 'error') return redirect(url_for('.index')) if cat == 'weddings': form = DonationForm(request.form) if form.validate_on_submit(): tran = Transaction() form.populate_obj(tran) tran.total_amount = form.amount.data tran.payment_status = 'unpaid' tran.type = 'donation' tran.save() tran.generate_txn_number() tran.save() donation = Donation() donation.registry_id = registry.id donation.transaction_id = tran.id donation.amount = form.amount.data donation.save() # initialize payments paystack = PaystackPay() response = paystack.fetch_authorization_url( email=tran.email, amount=tran.total_amount) if response.status_code == 200: json_response = response.json() tran.update( payment_txn_number=json_response['data']['reference']) return redirect(json_response['data']['authorization_url']) else: flash('Something went wrong. Please try again', 'error') return render_template('frontend/registry.html', registry=registry, form=form, cat=cat) return render_template('frontend/registry.html', registry=registry, cat=cat)
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 mapObject(object, parent=None, root=False, depth_limit=2, climit=7, depth=0, omit_list=[]): ############################ INDENT ############################ if settings.map_object_logging: logging.info(' ') indent = '-' for i in range(0, depth): indent = indent + '-----' if settings.map_object_logging: logging.info(indent + 'MapObject: Requested ' + str(object) + ' at depth ' + str(depth)) opt = str(depth_limit) + '::' + str(climit) if settings.map_object_logging: logging.info(indent + '--parent: ' + str(parent)) if settings.map_object_logging: logging.info(indent + '--omit list: ' + str(omit_list)) if isinstance(object, db.Key) or isinstance(object, basestring): if settings.map_object_logging: logging.info(indent + '--object is a simple key. converting to object.') object = db.get(object) if str(object.key()) in struct_cache: if opt in struct_cache[str(object.key())]: if settings.map_object_logging: logging.info(indent + '--found object in struct cache at opt: ' + opt + '. returning.') return struct_cache[str(object.key())][opt] m = memcache.get('map_cache::' + str(object.key()) + '::' + opt) if m is not None: if settings.map_object_logging: logging.info(indent + '--found object in memcache at key: ' + 'map_cache::' + str(object.key()) + '::' + opt + '. returning.') return m res = {} res['key'] = str(object.key()) res['object'] = todict(object) res['object']['key'] = str(object.key()) res['object']['kind'] = str(object.kind()) res['object']['connections'] = [] res['kind'] = str(object.kind()) res['display_text'] = str(object.display_text) res['is_root'] = str(root) if depth < depth_limit: if settings.map_object_logging: logging.info(indent + '--depth greater than zero. mapping:') summary = OSum.get_by_key_name(str(object.key())) if summary is None: donations = Donation.gql( "WHERE " + str(object.kind()).lower() + " = :1 ORDER BY amount DESC", object) donations = donations.fetch(donations.count()) connections = {} i = 0 for donation in donations: if i == climit: break if str(object.kind()) == 'Candidate': fk = donation.contributor elif str(object.kind()) == 'Contributor': fk = donation.candidate if str(fk.key()) not in connections: connections[str(fk.key())] = fk i = i + 1 for connection in connections: if db.Key(connection) in omit_list: if settings.map_object_logging: logging.info(indent + '--connection: ' + str(connection)) continue else: if parent is not None: res['object']['connections'].append( mapObject( connection, object, False, depth_limit, climit, depth + 1, [parent.key(), object.key()])) else: res['object']['connections'].append( mapObject(connection, object, False, depth_limit, climit, depth + 1, [object.key()])) i = i + 1 else: if settings.map_object_logging: logging.info(indent + '--found OSum: ' + str(object.key())) for connection in summary.connections: if connection in omit_list: continue else: if parent is not None: res['object']['connections'].append( mapObject( connection, object, False, depth_limit, climit, depth + 1, [parent.key(), object.key()])) else: res['object']['connections'].append( mapObject(connection, object, False, depth_limit, climit, depth + 1, [object.key()])) struct_cache[str(object.key())] = {opt: res} memcache.set('map_cache::' + str(object.key()) + '::' + opt, res, time=7200) return res
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
that read the database." So I prepared this module in response to this suggestion. And I re-use it entirely in my mailroom project to load data from DB and convert it into one of my class objects to be able to apply my methods to manipulate the data. """ import peewee from models import Person, Donation from RELATIONALMAILROOM.mailroom import SingleDonor, Donors # Get donor info from db and convert it into Donors class which # the create_report() method will use to generate the report dict_donors_gifts = {} donors = Person.select().order_by(Person.person_name) donations = Donation.select() query = peewee.prefetch(donors, donations) # Iterate over the query and collect all data into a dict # with donors as keys and donations as lists of values for donor in query: dict_donors_gifts[donor.person_name] = [] for gift in donor.donations: dict_donors_gifts[donor.person_name].append(float(gift.donation)) # Convert the dict with donors as keys and donations as values into # a Donors class object class_donors = Donors( [SingleDonor(key, value) for key, value in dict_donors_gifts.items()]) # Now make use of the create_report() method of the Donors class object class_donors.create_report()
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)
from models import Donation from forms import DonationForm >>>>>>> 1506909a0a168091856c108e091a09dbc075cc7b from django.views.decorators.csrf import csrf_protect, csrf_exempt @csrf_exempt def donations_form(request): <<<<<<< HEAD if request.method == 'POST': data = request.POST new_donation = Donation(first_name=data.get('first_name'), last_name=data.get('last_name'), amount=data.get('amount'), card_number=data.get('card_number'), cvv=data.get('cvv'), message=data.get('message'), donation_made=timezone.now()) new_donation.save() return render(request, "donations/donation_form.html", {'donated': True}) else: return render(request, "donations/donation_form.html", {'donated': False}) ======= form = DonationForm(request.POST or None) context = Context({ 'donated': False, 'form': form }) if request.method == 'POST' and form.is_valid(): data = request.POST
def add_donation(self, amount): """Add a donation.""" # Reminder: Model.create() means 'instantiate-then-save' Donation.create(person_name=self.name, donation=amount)