def transaction_equals(self):
        # success
        obj1 = models.Transaction()
        obj2 = models.Transaction()
        self.assertTrue(obj1 == obj2)

        # failure
        obj2.id = 532
        self.assertFalse(obj1 == obj2)
 def ParseLine(self, line_dict):
   date_str = line_dict[self.DATE_FIELD]
   date = datetime.datetime.strptime(date_str, self.DATE_FORMAT).date()
   amount = float(line_dict[self.AMOUNT_FIELD])
   description = line_dict[self.DESC_FIELD]
   type = line_dict[self.TYPE_FIELD] if self.TYPE_FIELD else None
   return models.Transaction(date, amount, description, type)
Beispiel #3
0
def show_depo_money():
    accntid = request.form['accntid']
    accountone = models.Account.query.filter_by(accntid=accntid).first()
    account = models.Account.query.filter_by(accntid=accntid).all()
    depositeamt = int(request.form['depositeamt'])
    temp = accountone.ammount + depositeamt
    accountone.ammount = temp
    db.session.commit()
    transaction = models.Transaction(accnt_id=accntid,
                                     customer_cid=accountone.customer_cid,
                                     ammount=depositeamt,
                                     transaction_date=datetime.now(),
                                     mode="Deposite",
                                     source_acc_type=accountone.accnt_type,
                                     target_acc_type=accountone.accnt_type)
    if (transaction is not None):
        db.session.add(transaction)
        db.session.commit()
        flash("Transaction Created successfully!", "success")
    else:
        flash("Transaction creation failed.", "danger")
        db.session.add(transaction)
        db.session.commit()

    flash("Ammount Deposited,Successfully", "sucess")
    return render_template("Cashier/show_acc_info.html", data=account)
Beispiel #4
0
    def action(self, profile, ledger):
        participant_profiles = ledger.participant_profiles()
        creditor_profile = models.Profile.get_by_key_name(
            self.request.get('creditor'))
        debtor_profile = models.Profile.get_by_key_name(
            self.request.get('debtor'))

        if not (creditor_profile and debtor_profile):
            return {'add_error': 'User can not be found'}
        if creditor_profile.key() == debtor_profile.key():
            return {'add_error': 'From and To profiles cannot be the same'}
        if not (any(creditor_profile.key() == p.key()
                    for p in participant_profiles)
                and any(debtor_profile.key() == p.key()
                        for p in participant_profiles)):
            return {'add_error': 'Profile is not a member of this ledger'}
        try:
            amount = decimal.Decimal(self.request.get('amount'))
            if amount <= 0:
                raise TypeError
        except (decimal.InvalidOperation, TypeError):
            return {'add_error': 'Invalid transaction amount'}
        else:
            models.Transaction(parent=ledger,
                               from_profile=creditor_profile,
                               to_profile=debtor_profile,
                               amount_cents=int(amount * 100),
                               notes=self.request.get('notes')).put()
Beispiel #5
0
def show_withdraw_money():
    accntid = request.form['accntid']
    accountone = models.Account.query.filter_by(accntid=accntid).first()
    account = models.Account.query.filter_by(accntid=accntid).all()
    withdrawamt = int(request.form['withdrawamt'])
    if withdrawamt > accountone.ammount:
        flash("Insufficient Balance Ammount for withdraw.", "danger")
        return render_template("Cashier/show_acc_info.html", data=account)
    else:
        transaction = models.Transaction.query.filter_by(
            transaction_date=datetime.now())
        temp = accountone.ammount - withdrawamt
        accountone.ammount = temp
        db.session.commit()
        transaction = models.Transaction(accnt_id=accntid,
                                         customer_cid=accountone.customer_cid,
                                         ammount=withdrawamt,
                                         transaction_date=datetime.now(),
                                         mode="withdraw",
                                         source_acc_type=accountone.accnt_type,
                                         target_acc_type=accountone.accnt_type)
        if (transaction is not None):
            db.session.add(transaction)
            db.session.commit()
            flash("Transaction Created successfully!", "success")
        else:
            flash("Transaction creation failed.", "danger")

        flash("Ammount Withdrawed Successfully", "sucess")
        return render_template("Cashier/show_acc_info.html", data=account)
Beispiel #6
0
def get_txn_obj(txn):
    """
	get transaction object from dict
	"""
    kargs = dict((i, txn[i]) for i in txn.keys())
    del kargs['ac_id']
    return models.Transaction(**kargs)
 def ParseLine(self, line_parts):
   if not line_parts:
     return None
   date_str = line_parts[0]
   date = datetime.datetime.strptime(date_str, '%m/%d/%Y').date()
   description = line_parts[2]
   amount = float(line_parts[3])
   type = line_parts[4]
   return models.Transaction(date, amount, description, type)
 def ParseLine(self, line_dict):
   date = datetime.datetime.strptime(line_dict['交易日期'], '%Y-%m-%d').date()
   amount_str_out = self._Strip(line_dict['支出'])
   amount_str_in = self._Strip(line_dict['存入'])
   description = line_dict['交易类型'] + ' ' + line_dict['交易备注']
   if amount_str_out:
     amount = -float(amount_str_out)
   else:
     amount = float(amount_str_in)
   return models.Transaction(date, amount, description, None)
def deser_tx(f):
    if type(f) is not io.BytesIO:
        f = io.BytesIO(f)

    tx = models.Transaction()
    tx.version = deser_uint32(f.read(4))
    tx.inputs = deser_vector(f, models.TxIn)
    tx.outputs = deser_vector(f, models.TxOut)
    tx.locktime = deser_uint32(f)
    return tx
def transactions_bank_statement_review(request):
    """ Allow the user to change the data in the transactions before importing """
    def class_gen_with_kwarg(cls, **additionalkwargs):
        """
        class generator for subclasses with additional 'stored' parameters (in a closure)
        This is required to use a modelformset_factory with a form that needs additional 
        initialization parameters (see http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset)
        """
        class ClassWithKwargs(cls):
            def __init__(self, *args, **kwargs):
                kwargs.update(additionalkwargs)
                super(ClassWithKwargs, self).__init__(*args, **kwargs)

        return ClassWithKwargs

    # create the formset
    pending_imports = models.TransactionImportPending.objects.filter(
        owner=request.user)
    TransactionImportPendingFormset = modelformset_factory(models.TransactionImportPending, \
                                        form=class_gen_with_kwarg(forms.TransactionImportPendingForm, request=request), \
                                        fields=['date', 'amount', 'description', 'tenancy', 'building', 'person', 'category'],\
                                        extra=0)

    if request.method == 'POST':
        # save the user's changes
        formset = TransactionImportPendingFormset(request.POST)
        if formset.is_valid():
            formset.save()

            # convert transaction import pending to transactions
            if request.POST.get('import', False) != False:
                for record_data in formset.cleaned_data:
                    record_id = record_data.pop('id').id
                    record_data['owner'] = request.user
                    transaction = models.Transaction(**record_data)
                    transaction.save()
                    models.TransactionImportPending.objects.filter(
                        owner=request.user, id=record_id).delete()

                # redirect to transactions
                return HttpResponseRedirect(reverse('transactions'))
        return render(request,
                      'website/transactions_bank_statement_review.html',
                      {'formset': formset})
    else:
        # redirect to upload if no pending imports
        if not pending_imports:
            return HttpResponseRedirect(
                reverse('transactions_bank_statement_upload'))

        # show the unbound formset with all their pending imports
        formset = TransactionImportPendingFormset(queryset=pending_imports)
        return render(request,
                      'website/transactions_bank_statement_review.html',
                      {'formset': formset})
Beispiel #11
0
def _pay_any(debtors, creditors, d):
    '''Make payments to as many creditors as necessary to fully pay off the debtor's debt'''
    transactions = []
    for c in creditors:
        if creditors[c] > 0:
            if -debtors[d] < creditors[c]:
                transactions.append(
                    models.Transaction(from_profile=d,
                                       to_profile=c,
                                       amount_cents=-debtors[d]))
                debtors[d] = creditors[c] = 0
                return transactions
            transactions.append(
                models.Transaction(from_profile=d,
                                   to_profile=c,
                                   amount_cents=creditors[c]))
            debtors[d] += creditors[c]
            creditors[c] = 0
        if debtors[d] == 0:
            return transactions
    return transactions
Beispiel #12
0
def create_transaction(money, project_id, reasons=(), user_variables=()):
    m = Multipay(money, project_id, reasons, user_variables)
    response = m.execute()
    transaction = models.Transaction(transaction=response.transaction,
                                     payment_url=response.payment_url)
    transaction.save()
    for warning in response.warnings:
        w = models.Warning(code=warning.code, message=warning.code)
        w.save()
        transaction.warnings.add(w)
    transaction.save()
    return transaction
Beispiel #13
0
def __parse_tx(tx, block_id):
    out = {}
    out['gas_wanted'] = int(tx['gasWanted'])
    out['gas_used'] = int(tx['gasUsed'])
    out['log'] = tx['log']
    events = tx['events']
    if events:
        out['success'] = True
        out['events'] = parse_events(events, block_id)
    else:
        out['success'] = False
    return models.Transaction(**out)
Beispiel #14
0
def _pay_matching(debtors, creditors, d):
    '''Try to pay off two balances at the same time.'''
    transactions = []
    for c in creditors:
        if debtors[d] + creditors[c] == 0:
            transactions.append(
                models.Transaction(from_profile=d,
                                   to_profile=c,
                                   amount_cents=-debtors[d]))
            debtors[d] = creditors[c] = 0
            return transactions
    return transactions
Beispiel #15
0
    def testEntityCD(self):
        logging.debug('Testing entity create & delete...')
        sponsor = models.Sponsor()
        sponsor.name = 'Test Sponsor'
        sponsor.url = 'http://www.redcross.com'
        sponsor.address = '123 blaj blah, blah WA,USA'
        sponsor.phone = '(555)555-555'
        sponsor.put()
        assert sponsor.key()

        test_client = models.Client()
        test_client.set_defaults()
        test_client.displayName = "Bob"
        test_client.fullName = "Bob the builder"
        test_client.story = lorem_ipsum
        test_client.sponsor = sponsor
        test_client.imageURL = "http://www.test.org/img.png"
        test_client.put()
        assert test_client.key()

        test_donor = models.Donor()
        test_donor.address = "123 123 123"
        test_donor.name = "Donor"
        test_donor.phone = "(206)555-5555"
        test_donor.put()
        assert test_donor.key()

        test_user = models.User()
        test_user.user = users.get_current_user()
        test_user.isAdmin = True
        test_user.sponsor = sponsor
        test_user.put()
        assert test_user.key()

        tx = models.Transaction()
        fromAccount = 'stripe'
        toAccount = '%s/%s' % (sponsor.key(), test_client.key())
        amount = 1.00
        type = 'CREDIT'
        note = 'A donation from Bob'
        confirm = False
        tx.put()

        # clean up
        tx.delete()
        test_user.delete()
        test_client.delete()
        sponsor.delete()
        test_donor.delete()

        self.response.out.write("<html><body><p>Test Passed!</p></body></html>")
Beispiel #16
0
    def post(self):
        parameters = None
        if self.request.POST:
            parameters = self.request.POST.copy()
        if self.request.GET:
            parameters = self.request.GET.copy()

        if parameters:
            # Send the notification back to Paypal for verification
            parameters['cmd'] = '_notify-validate'
            params = urllib.urlencode(parameters)
            status = urlfetch.fetch(
                url=PP_URL,
                method=urlfetch.POST,
                payload=params,
            ).content

        payment = models.Transaction(
            receiver_email=parameters['receiver_email'],
            transaction_id=parameters['txn_id'],
            transaction_type=parameters['txn_type'],
            payment_type=parameters['payment_type'],
            payment_status=parameters['payment_status'],
            amount=parameters['mc_gross'],
            currency=parameters['mc_currency'],
            payer_email=parameters['payer_email'],
            first_name=parameters['first_name'],
            last_name=parameters['last_name'],
            verified=False)

        # Insert new transactions in the database.
        if models.Transaction.transaction_exists(payment.transaction_id,
                                                 payment.payment_status):
            # This transaction has already been verified and processed.
            logging.debug('Transaction already exists')

        # Verify that the payment is confirmed by PayPal and that it is going to the correct account
        elif status == "VERIFIED" and payment.receiver_email == ACCOUNT_EMAIL:

            if payment.payment_status == "Completed":
                payment.verified = True
                # Insert actions to take if a completed transaction is received here:

            else:
                payment.verified = False
                # Insert actions to take if a transaction with unverified payment is received here:

            # Insert new (verified) transactions in the database. You may wish to store/log unverified transactions as well as these may be malicious.
            payment.put()
            logging.debug('New transaction added to database')
Beispiel #17
0
def _pay_forward(debtors, creditors, d):
    '''Try to pay off one balance now, and set up the creditor to be paid off fully in the next transaction.'''
    transactions = []
    for other_debtor in debtors:
        if d is not other_debtor:
            for c in creditors:
                if debtors[d] + debtors[other_debtor] + creditors[c] == 0:
                    transactions.append(
                        models.Transaction(from_profile=d,
                                           to_profile=c,
                                           amount_cents=-debtors[d]))
                    creditors[c] += debtors[d]
                    debtors[d] = 0
                    return transactions
    return transactions
Beispiel #18
0
def create_transaction_record(
    db: Session,
    to_customer_wallet: models.CustomersWallet,
    to_amount: Decimal,
    from_amount: Decimal,
    from_currency: models.Currency,
    from_customer_wallet: models.CustomersWallet = None,
):
    db_transaction = models.Transaction(
        from_customer_wallet=from_customer_wallet,
        to_customer_wallet=to_customer_wallet,
        from_amount=from_amount,
        to_amount=to_amount,
        from_currency=from_currency,
    )

    db.add(db_transaction)
Beispiel #19
0
def show_transfer_money():
    accntid = request.form['accntid']
    cusid = request.form['cus_id']
    curracc = request.form['accnt_type']
    targetacc = request.form['targetaccnt_type']
    transferammount = int(request.form['transferamt'])
    accountcurr = models.Account.query.filter_by(customer_cid=cusid,
                                                 accnt_type=curracc).first()
    print(accountcurr)
    accounttarget = models.Account.query.filter_by(
        customer_cid=cusid, accnt_type=targetacc).first()
    print(accounttarget)
    account = models.Account.query.filter_by(customer_cid=cusid).all()
    if (accountcurr is None):
        flash('"first create"+{{curracc}}+" than transfer"')
        return render_template("Cashier/show_acc_info.html", data=account)
    elif (accounttarget is None):
        flash('"first create"+{{targetacc}}+"than transfer"')
        return render_template("Cashier/show_acc_info.html", data=account)
    elif (transferammount > accountcurr.ammount):
        flash("Insufficient Balance Ammount for withdraw.", "danger")
        return render_template("Cashier/show_acc_info.html", data=account)
    elif (accountcurr and accounttarget):
        # transaction=models.Transaction.query.filter_by(transaction_date=datetime.now())
        # if(transaction is None):
        transaction = models.Transaction(accnt_id=accntid,
                                         customer_cid=cusid,
                                         ammount=transferammount,
                                         transaction_date=datetime.now(),
                                         mode="Transfer",
                                         source_acc_type=curracc,
                                         target_acc_type=targetacc)
        if (transaction is not None):
            db.session.add(transaction)
            db.session.commit()
            flash("Transaction Created successfully!", "success")
        else:
            flash("Transaction creation failed.", "danger")
        withdraw = accountcurr.ammount - transferammount
        accountcurr.ammount = withdraw
        deposite = accounttarget.ammount + transferammount
        accounttarget.ammount = deposite
        db.session.commit()
        flash("Ammount transfered Successfully", "sucess")
        return render_template("Cashier/show_acc_info.html", data=account)
Beispiel #20
0
 def post(self):
     action = self.request.get('action')
     if action == 'add':
         transaction = models.Transaction()
         transaction.doc_id = users.get_current_user().user_id()
         transaction.product = 'Product XXXXXXX'
         transaction.rentee_id = 'John Carter'
         transaction.email = '*****@*****.**'
         transaction.phone_number = '514-123-4567'
         transaction.meet_point = '1111 Barclay # 1'
         transaction.pick_up_date = '20/4/2016'
         transaction.return_date = '20/4/2016'
         transaction.amount_paid = '90$'
         transaction.put()
         self.buildViewTransactionsPage(notification='Transaction Add')
     elif action == 'delete':
         models.Transaction.deleteTransactions()
         self.buildViewTransactionsPage(notification='Transaction Deleted')
Beispiel #21
0
    def action(self, profile, ledger):
        participant_profiles = ledger.participant_profiles()
        from_profile = models.Profile.get_by_key_name(self.request.get('from'))

        if not from_profile:
            return {'bill_error': 'Invalid profile'}
        if not any(from_profile.key() == p.key()
                   for p in participant_profiles):
            return {'bill_error': 'Profile is not a member of this ledger'}
        try:
            amount = decimal.Decimal(self.request.get('amount'))
            if amount <= 0:
                raise TypeError
        except (decimal.InvalidOperation, TypeError):
            return {'bill_error': 'Invalid transaction amount'}
        else:
            amount_cents = int(amount * 100 / len(participant_profiles))
            for to_profile in participant_profiles:
                if from_profile.key() != to_profile.key():
                    models.Transaction(parent=ledger,
                                       from_profile=from_profile,
                                       to_profile=to_profile,
                                       amount_cents=amount_cents,
                                       notes=self.request.get('notes')).put()
Beispiel #22
0
    def get(self):
        """Do a document search for the given product id,
    and display the retrieved document fields."""

        params = self.parseParams()

        pid = params['pid']
        if not pid:
            # we should not reach this
            msg = 'Error: do not have product id.'
            url = '/'
            linktext = 'Go to product search page.'
            self.render_template(
                'notification.html',
                {'title': 'Error', 'msg': msg,
                 'goto_url': url, 'linktext': linktext})
            return
        doc = docs.Product.getDocFromPid(pid)
        logging.info(doc)
        if not doc:
            error_message = ('Document not found for pid %s.' % pid)
            return self.abort(404, error_message)
            logging.error(error_message)

        date_format = "%Y-%m-%d"
        pickupD = (datetime.strptime(self.request.get('pickupD'), date_format))
        returnD = (datetime.strptime(self.request.get('returnD'), date_format))
        logging.info("pickup: %s", pickupD)
        logging.info("return: %s", returnD)
        c = returnD - pickupD
        logging.info("c: %s", c)
        c = int(c.days)
        logging.info("days: %d", c)
        pdoc = docs.Product(doc)
        pname = pdoc.getName()
        price = pdoc.getPrice()
        ppacc = pdoc.getMerchant()
        amount_paid = float(price) * int(c)
        app_url = wsgiref.util.application_uri(self.request.environ)
        template_values = {
            'app_url': app_url,
            'pid': pid,
            'pname': pname,
            'price': price,
            'ppacc': ppacc,
            'pickupD': pickupD.date(),
            'returnD': returnD.date(),
            'amount_paid': amount_paid,
            'image_url': pdoc.getImageUrl(),
            'prod_doc': doc,
            # for this demo, 'admin' status simply equates to being logged in
            'user_is_admin': users.get_current_user()}
        logging.info("name: %s", pname)
        logging.info("name: %s", pickupD.date())
        logging.info("name: %s", returnD.date())
        logging.info("name: %s", amount_paid)
        user = users.get_current_user()
        userinfo = ndb.Key(models.UserInfo, pdoc.getUserId()).get()
        transaction = models.Transaction(
            t_id = uuid.uuid4().hex,  # auto-generate default UID
            rentee_id = user.user_id(),  # give id automatically to product
            renter_id = pdoc.getUserId(),
            amount_paid = amount_paid,
            pickupD = pickupD.date(),
            returnD = returnD.date(),
            meet_point = userinfo.meetPoint,
            doc_id = user.user_id(),
            product = pname,
            email = userinfo.email,
            #dateSent = '',
            #payment_status = ndb.StringProperty(),
            verified = False
        )
        transaction.put()
        logging.info('transaction saved')
        logging.info('template_values :')
        logging.info(template_values)
        self.render_template('order.html', template_values)
Beispiel #23
0
def _instantiate_transactions(sections):
    transactions = list()
    for _, section in sections.items():
        transactions.append(models.Transaction(section))

    return transactions
Beispiel #24
0
def purchase():
    # Create the form
    purchase_form = forms.PurchaseForm()

    # If a POST request
    if flask.request.method == 'POST' and purchase_form.validate_on_submit():
        pending_transaction = models.PendingTransaction.query.filter(
                models.PendingTransaction.barcode == 
                purchase_form.barcode.data)

        # If not found, we have an error - we would also confirm payment here
        if pending_transaction.count() < 1:
          data = {
              'barcode': pending_transaction.barcode,
              'status': 'fail'
          }
        else:
          pending_transaction = pending_transaction.first()

          # Update the status of the transaction
          pending_transaction.status = 2;

          # Create a transaction
          new_transaction = models.Transaction(
              user_id=login.current_user.id,
              company=pending_transaction.company,
              amount=pending_transaction.amount
          )
          db.session.add(new_transaction)
          db.session.commit()

          data = {
              'barcode': pending_transaction.barcode,
              'status': 'success'
          }

        # Let the Vendor agent know that the item has been paid for
        vendor = models.Vendor.query.filter(models.Vendor.id ==
            pending_transaction.company).first()
        data['secret'] = vendor.secret
        url = vendor.agent_url + '/dispense'
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(data), headers=headers)

        # Redirect to dashboard
        return flask.redirect(flask.url_for('dashboard'))

    # If not a post request
    # Create barcode and update form
    i2of5_code = ''.join(random.choice(string.digits) for x in range(10))
    purchase_form = forms.PurchaseForm(barcode=i2of5_code)

    # Add to list of pending transactions
    new_pending_transaction = models.PendingTransaction(
        user_id=login.current_user.id,
        barcode=i2of5_code 
    )
    db.session.add(new_pending_transaction)
    db.session.commit()

    # Get image URL
    url = 'http://www.barcodes4.me/barcode/i2of5/' + \
        i2of5_code + '.jpg'
    
    return flask.render_template('purchase.epy', user=login.current_user,
            purchase_form=purchase_form, barcode=i2of5_code, img_url=url)