示例#1
0
    def setUp(self):
        # set up the test DB
        self.db = tested_db
        self.db.create_all()
        self.db.session.add(Person(id=1, name="Alice"))
        self.db.session.add(Person(id=2, name="Bob"))
        self.db.session.add(
            Payment(payment_id=1, payment_amount=10.5, client_id=1))
        self.db.session.add(
            Payment(payment_id=2, payment_amount=12.5, client_id=2))
        self.db.session.commit()

        self.app = tested_app.test_client()
示例#2
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        if not date_cursor: # If date_cursor is equal to the default value (None) or null, set it equal to the current date
            date_cursor = datetime.now().date()

        if not contact_id: # If there is no contact_id or it is equal to the default value (None), set it equal to the named insured of the policy
            try:
                contact_id = self.policy.named_insured
            except:
                pass

        payment = Payment(self.policy.id, # Create a payment using the method parameters
                          contact_id,
                          amount,
                          date_cursor)
        
        invoices = Invoice.query.filter_by(policy_id=self.policy.id).all() # Get a list of invoices

        for invoice in invoices: # For each invoice...
            if invoice.amount_due != 0: # That is not paid (i.e not equal to 0)...
               invoice.amount_due -= amount # Subtract the amount paid from the invoice amount due
               break # We want to execute the break statement because we found our invoice that was decremented and don't want to modify any other ones

        db.session.add(payment) # Add the payment to the database
        db.session.commit() # Commit the changes (save)

        return payment
示例#3
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        """
         Add new payment data to database.
         Use current date if date_cursor argument is not provided
         Use named insured id as contact id if not provided
        """
        if not date_cursor:
            date_cursor = datetime.now().date()

        if not contact_id:
            try:
                contact_id = self.policy.named_insured
            except:
                pass

        # If a policy is in cancellation pending due to non_pay, only an
        # agent should be able to make a payment on it
        if self.evaluate_cancellation_pending_due_to_non_pay(
                date_cursor) and contact_id is not self.policy.agent:
            print "Contact your agent for making payment"
            return None
        else:
            payment = Payment(self.policy.id, contact_id, amount, date_cursor)
            db.session.add(payment)
            db.session.commit()

        return payment
示例#4
0
def menu_charge(request, request_id=0):
    if request.method == "POST":
        stripe.api_key = settings.STRIPE_API_KEY
        card = request.POST.get("stripeToken")
        m = []
        food_request = get_request(request_id)
        payment = Payment()
        payment.amount = food_request.total
        payment.paidBy = request.user
        payment.description = "food delivery: "  #+ item_list
        x = payment.amount * 100  #Convert from dolars to cents
        y = (x / 100) * 2.9  #Adjust stripe fees
        print card
        success, instance = payment.charge(int((x + y) + 30), card)
        if not success:
            raise forms.ValidationError("Error: %s" % instance.message)

        else:
            instance.amount = payment.amount
            instance.save()
            food_request.paid = True
            food_request.save()
            return HttpResponseRedirect("/")

    else:
        context = {'user': request.user, 'stripe_key': settings.STRIPE_PUB_KEY}
        return render(request, 'pay.html', context)
示例#5
0
def create_payment():
    form = PaymentForm()
    if form.validate_on_submit():
        payment = request.get_json()

        if not is_exists_invoices(invoice_list=[
                payment['number_invoice_provider'],
                payment['number_invoice_reciever']
        ]):
            return send_response(
                content={'message': 'Invoices does not exists'},
                status_code=404)

        key = get_payment_key()
        code_confirm = randint(100, 1000)

        db.session.add(
            Payment(key=key,
                    amount_money=payment['amount_money'],
                    number_invoice_provider=payment['number_invoice_provider'],
                    number_invoice_reciever=payment['number_invoice_reciever'],
                    code_confirm=code_confirm,
                    status_id=1))
        db.session.commit()

        send_code_confirm_payment_to_client(code=code_confirm)

        return send_response(content={'message': 'ok'}, status_code=200)

    return send_response(content=form.errors, status_code=400)
示例#6
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        if not date_cursor:
            date_cursor = datetime.now().date()

        if not contact_id:
            try:
                contact_id = self.policy.named_insured
            except:
                logging.exception('Encountered an issue with generating insured name for make_payment')
                return None

        # If cancellation due to non pay, an agent must make the payment
        if self.evaluate_cancellation_pending_due_to_non_pay(date_cursor):
            contact = Contact.query.filter_by(id=contact_id)\
                                   .one()
            if contact.role != 'Agent':
                print 'Due to the current status of this policy, an agent is needed to make payment'
                return

        # Create payment
        payment = Payment(self.policy.id,
                          contact_id,
                          amount,
                          date_cursor)
        db.session.add(payment)
        db.session.commit()

        return payment
示例#7
0
def create_consult(request):
    if request.POST:
        aid = request.POST['id']
        a = Appointment.objects.filter(a_id=aid)
        a1 = Appointment.objects.get(a_id=aid)
        patient = a[0].user_id
        pname = a[0].patient_name
        doctor = a[0].doctor
        dept = a[0].dept
        dnm = a[0].doc_name
        a1.active = False
        a1.save()
        c = Consultation(c_id=uuid.uuid4(),
                         patient=patient,
                         patient_name=pname,
                         doctor=doctor,
                         dept=dept,
                         doc_name=dnm,
                         comments="Consultation started",
                         active=True)
        c.save()
        p = Payment(payment_id=uuid.uuid4(),
                    item_id="Consultation Fees",
                    user=patient,
                    payment_type="Debit Card",
                    status=0,
                    active=True,
                    date=date.today(),
                    amount=200)
        p.save()
        return render_to_response('consultsuccess.html')
示例#8
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        """ Make a payment against the policy """

        # Default to current date
        if not date_cursor:
            date_cursor = datetime.now().date()

        # If no contact_id was provided, assign contact to the
        # policy's name_insured. Will be used as the contact for the payment
        if not contact_id:
            try:
                contact_id = self.policy.named_insured
            except:
                pass
        # Create the payment
        payment = Payment(
            self.policy.id,  # policy
            contact_id,  # contact
            amount,  # amount paid
            date_cursor)  # transaction date
        # Commit changes to database
        db.session.add(payment)
        db.session.commit()

        return payment
示例#9
0
    def ExecutePayment(self, request, context):
        payment = None
        try:
            payment = paypalrestsdk.Payment.find(request.paymentId)
        except paypalrestsdk.ResourceNotFound:
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            context.set_details('Invalid payment id')
            return ExecutePaymentResponse()

        if not payment.execute({'payer_id': request.payerId}):
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            context.set_details('Invalid payer id')
            return ExecutePaymentResponse()

        session = self._Session()

        enrollment_id = self._get_sku_from_payment(payment)
        enrollment = session.query(Enrollment).\
            filter_by(id=enrollment_id).first()
        enrollment.payment = Payment()

        enrollment.course.creator.week_profit += enrollment.course.price

        session.add(enrollment)
        session.commit()
        session.close()

        return ExecutePaymentResponse()
示例#10
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        """
        if date_cursor is null
        then Initialize date_cursor with the current date
        """
        if not date_cursor:
            date_cursor = datetime.now().date()
        """
        If contact_id is NULL then contact_id = named_insured
        """
        if not contact_id:
            try:
                contact_id = self.policy.named_insured
            except:
                logging.exception("contact_id cannot be NULL")
                return

        if self.evaluate_cancellation_pending_due_to_non_pay(date_cursor):
            contact = Contact.query.filter_by(id=contact_id).one()
            if 'Agent' != contact.role:
                print 'At This Stage, Only an agent can make the payment.'
                return
        """
        Creating a new payment with the previous Information and persisting it
        """
        payment = Payment(self.policy.id, contact_id, amount, date_cursor)
        db.session.add(payment)
        db.session.commit()

        return payment
示例#11
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        """
        Create a new payment method,
        this method will evaluate each policy
        if it's cancellation pending only agents
        will be able to make payments.
        """

        if not date_cursor:
            date_cursor = datetime.now().date()

        if self.evaluate_cancellation_pending_due_to_non_pay(date_cursor):
            contact = Contact.query.get(contact_id)
            if contact.role != 'Agent':
                print
                'You need to be an agent to pay this policy.'
                return False

        else:
            if not contact_id:
                try:
                    contact_id = self.policy.named_insured
                except:
                    pass

        payment = Payment(self.policy.id, contact_id, amount, date_cursor)
        db.session.add(payment)
        db.session.commit()

        return payment
示例#12
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):

        # In case a date is not passed the current date is used
        if not date_cursor:
            date_cursor = datetime.now().date()

        # In case the contact id is not passed it uses the id referenced in the Policy table
        if not contact_id:
            try:

                if self.policy.named_insured:
                    contact_id = self.policy.named_insured
                else:
                    contact_id = self.policy.agent
            except:
                logging.info('No contact found during the payment')

        try:
            # Creates the payment object
            payment = Payment(self.policy.id, contact_id, amount, date_cursor)
            db.session.add(payment)
            db.session.commit()

            logging.info('Payment made')
            return payment

        except Exception as error:

            db.session.rollback()
            logging.error(error)
示例#13
0
def create_payment(booking, offerer, amount, author='test author', reimbursement_rule='remboursement à 100%',
                   reimbursement_rate=Decimal(0.5), payment_message=None, payment_message_name=None,
                   transaction_end_to_end_id=None,
                   transaction_label='pass Culture Pro - remboursement 2nde quinzaine 07-2018',
                   status=TransactionStatus.PENDING, idx=None, iban='FR7630007000111234567890144', bic='BDFEFR2LCCB'):
    payment = Payment()
    payment.booking = booking
    payment.amount = amount
    payment.author = author
    payment.iban = iban
    payment.bic = bic
    payment.recipientName = offerer.name
    payment.recipientSiren = offerer.siren
    payment_status = PaymentStatus()
    payment_status.status = status
    payment_status.date = datetime.utcnow()
    payment.statuses = [payment_status]
    payment.reimbursementRule = reimbursement_rule
    payment.reimbursementRate = reimbursement_rate

    if payment_message_name:
        payment.paymentMessage = create_payment_message(payment_message_name)
    elif payment_message:
        payment.paymentMessage = payment_message

    payment.transactionEndToEndId = transaction_end_to_end_id
    payment.transactionLabel = transaction_label
    payment.id = idx
    return payment
示例#14
0
    def _div_to_payment(self, div):
        price_xpath = './/span[contains(@data-pageobject,"price")]'
        cost_str = text_at_xpath(div, price_xpath)
        cost = text_to_cost(cost_str)

        def parse_date(date_str, format_str):
            return datetime.strptime(date_str, format_str).date()

        date_xpath = './/span[@data-pageobject="statement-date"]'
        date_str = text_at_xpath(div, date_xpath)
        date = parse_date(date_str, "%d/%m/%Y")

        p = Payment(cost, date)

        def has_element(d, xpath_str):
            return first(d.xpath(xpath_str)) is not None

        warning_xpath = './/img[contains(@class, "warning-icon")]'
        p.warning = has_element(div, warning_xpath)

        autocompleted_xpath = './/img[contains(@class, "autocompleted")]'
        p.autocompleted = has_element(div, autocompleted_xpath)

        capped_xpath = './/img[contains(@class, "capped")]'
        p.capped = has_element(div, capped_xpath)

        p.journeys = self._div_to_journeys(div)
        return p
示例#15
0
def fill_in_tables(num_records=1):
    for _ in range(num_records):
        person_rec, payment_rec = generate_user()
        p_1 = Person.objects.create(**person_rec)
        pay = Payment(**payment_rec)
        p_1.payment_set.add(pay, bulk=False)


# fill_in_tables()
示例#16
0
文件: utils.py 项目: jgpub/bcproject
def insert_data():
    #Contacts
    contacts = []
    mary_sue_client = Contact('Mary Sue', "Client")
    contacts.append(mary_sue_client)
    john_doe_agent = Contact('John Doe', 'Agent')
    contacts.append(john_doe_agent)
    john_doe_insured = Contact('John Doe', 'Named Insured')
    contacts.append(john_doe_insured)
    bob_smith = Contact('Bob Smith', 'Agent')
    contacts.append(bob_smith)
    anna_white = Contact('Anna White', 'Named Insured')
    contacts.append(anna_white)
    joe_lee = Contact('Joe Lee', 'Agent')
    contacts.append(joe_lee)
    ryan_bucket = Contact('Ryan Bucket', 'Named Insured')
    contacts.append(ryan_bucket)

    for contact in contacts:
        db.session.add(contact)
    db.session.commit()

    policies = []
    p1 = Policy('Policy One', date(2015, 1, 1), 365)
    p1.billing_schedule = 'Annual'
    p1.agent = bob_smith.id
    policies.append(p1)

    p2 = Policy('Policy Two', date(2015, 2, 1), 1600)
    p2.billing_schedule = 'Quarterly'
    p2.named_insured = anna_white.id
    p2.agent = joe_lee.id
    policies.append(p2)

    p3 = Policy('Policy Three', date(2015, 1, 1), 1200)
    p3.billing_schedule = 'Monthly'
    p3.named_insured = ryan_bucket.id
    p3.agent = john_doe_agent.id
    policies.append(p3)

    p4 = Policy("Policy Four", date(2015, 2, 1), 500)
    p4.billing_schedule = 'Two-Pay'
    p4.named_insured = ryan_bucket.id
    p4.agent = john_doe_agent.id
    policies.append(p4)

    for policy in policies:
        db.session.add(policy)
    db.session.commit()

    for policy in policies:
        PolicyAccounting(policy.id)

    payment_for_p2 = Payment(p2.id, anna_white.id, 400, date(2015, 2, 1))
    db.session.add(payment_for_p2)
    db.session.commit()
示例#17
0
def insert_data():
    # Contacts
    contacts = []
    john_doe_agent = Contact("John Doe", "Agent")
    contacts.append(john_doe_agent)
    john_doe_insured = Contact("John Doe", "Named Insured")
    contacts.append(john_doe_insured)
    bob_smith = Contact("Bob Smith", "Agent")
    contacts.append(bob_smith)
    anna_white = Contact("Anna White", "Named Insured")
    contacts.append(anna_white)
    joe_lee = Contact("Joe Lee", "Agent")
    contacts.append(joe_lee)
    ryan_bucket = Contact("Ryan Bucket", "Named Insured")
    contacts.append(ryan_bucket)

    for contact in contacts:
        db.session.add(contact)
    db.session.commit()

    policies = []
    p1 = Policy("Policy One", date(2015, 1, 1), 365)
    p1.billing_schedule = "Annual"
    p1.named_insured = john_doe_insured.id
    p1.agent = bob_smith.id
    policies.append(p1)

    p2 = Policy("Policy Two", date(2015, 2, 1), 1600)
    p2.billing_schedule = "Quarterly"
    p2.named_insured = anna_white.id
    p2.agent = joe_lee.id
    policies.append(p2)

    p3 = Policy("Policy Three", date(2015, 1, 1), 1200)
    p3.billing_schedule = "Monthly"
    p3.named_insured = ryan_bucket.id
    p3.agent = john_doe_agent.id
    policies.append(p3)

    p4 = Policy("Policy Four", date(2015, 2, 1), 500)
    p4.billing_schedule = "Two-Pay"
    p4.named_insured = ryan_bucket.id
    p4.agent = john_doe_agent.id
    policies.append(p4)

    for policy in policies:
        db.session.add(policy)
    db.session.commit()

    for policy in policies:
        PolicyAccounting(policy.id)

    payment_for_p2 = Payment(p2.id, anna_white.id, 400, date(2015, 2, 1))
    db.session.add(payment_for_p2)
    db.session.commit()
示例#18
0
def _reward_create(user, reason, category, recipient, amount, message):
    proposal = Proposal(user, reason)
    proposal.categories.append(category)
    proposal.authorize(user)
    db.session.add(proposal)
    email = recipient if utils.is_email(recipient) else None
    mobile = recipient if utils.is_mobile(recipient) else None
    address = recipient if utils.is_address(recipient) else None
    payment = Payment(proposal, mobile, email, address, message, amount)
    db.session.add(payment)
    return proposal, payment
示例#19
0
文件: tests.py 项目: rajanski/proprio
 def test_payments(self):
     payment = Payment(amount=100, date=date(2011, 6, 15))
     expected = [(payment.date, payment.amount)]
     actual = payments_to_cashflows(date(2011, 6, 15), [payment])
     actual2 = map(cashflow_to_tuple, list(actual))
     self.assertEqual(expected, actual2, "payments are counted as positive")
     self.assertEqual([],
                      list(
                          payments_to_cashflows(date(2011, 6, 14),
                                                [payment])),
                      "payments are counted only after current date")
示例#20
0
def payment():
        payment= request.get_json()
        payment = Payment(
        card_num =payment["card_num"],
        card_cvv = payment["card_cvv"],
        card_exp= payment ["card_exp"],
        card_name=payment["card_name"]
    )
        db.session.add(payment)
        db.session.commit()
        return 'payment was succesful'
示例#21
0
async def handler(message: types.Message):

    if message.text.isdigit():
        user = session.query(User).get(1)

        payment = Payment(amount=float(message.text),
                          user_id=user.id,
                          goal='soe')
        session.add(payment)
        session.commit()

    await message.answer([i.amount for i in session.query(Payment).all()])
示例#22
0
文件: task.py 项目: RazinDangol/gSewa
def command_execute(table, service_provider, service, service_name,
                    service_type, amount, status, date, time):
    if table == 'payment':
        db.session.add(
            Payment(service_provider, service, service_name, service_type,
                    float(amount), status, date, time))
    elif table == 'cashback':
        db.session.add(
            Cashback(service_provider, service, service_name, service_type,
                     float(amount), status, date, time))
    else:
        pass
示例#23
0
def pay_order(id):
    parser = reqparse.RequestParser()
    parser.add_argument('pay_type', type=str)
    parser.add_argument('amount', type=float)
    parser.add_argument('card_info', type=str)
    args = parser.parse_args()

    pay_type = args.get("pay_type")
    amount = args.get("amount")
    card_info = None

    if pay_type not in ['card', 'cash']:
        return jsonify(error='Wrong payment type. (card or cash)'), 400
    if pay_type == 'card':
        card_info = args.get("card_info")
    # print(pay_type, amount, card_info)
    for order in orders:
        if order.order_id == id:
            if order.status == "Cancelled":
                return jsonify(error="You order has been cancelled."), 409
            for p in payments:
                if p.order_id == id:
                    return jsonify(
                        error="You already paid for your coffee."), 409
            else:
                if amount == order.cost:
                    pay_time = time.ctime()
                    payments.append(
                        Payment(id, pay_type, amount, pay_time, card_info))
                    if pay_type == 'card':
                        order.payment = {
                            "pay_time": pay_time,
                            "pay_type": pay_type,
                            "card_info": card_info
                        }
                        return jsonify(order_id=id,
                                       pay_type=pay_type,
                                       amount=amount,
                                       pay_time=pay_time,
                                       card_info=card_info), 201
                    else:
                        order.payment = {
                            "pay_time": pay_time,
                            "pay_type": pay_type
                        }
                        return jsonify(order_id=id,
                                       pay_type=pay_type,
                                       amount=amount,
                                       pay_time=pay_time), 201
                else:
                    return jsonify(
                        error="Sorry. The cost is not correct."), 400
    return jsonify(order_id=False), 404
示例#24
0
def add_payment_in_db(update, context):
    """ Add new record with payment in db """
    existing_user = identify_user(update)

    new_payment = Payment(
        price=context.user_data['price'],
        payment_info=context.user_data['payment_info'],
        category=context.user_data['category'],
        date=datetime.today()
    )

    existing_user.payments.append(new_payment)
    existing_user.save()
示例#25
0
	def update_client(self, client):
		count = 0
		newClient = False

		clientObj = Client.get_by_id(client.auth.email) 

		if (  clientObj is None ):
			newClient = True
			for c in client.child_list:
				d = datetime.datetime.now()
				next_month = datetime.datetime(d.year, d.month+1, 1)
				next_month_string =  next_month.isoformat() + '.0000'
				pay = Payment()
				pay.start_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				pay.end_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				pay.pay_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				c.payment = pay.put()
				

		client.key = ndb.Key(Client, client.auth.email)	
		client.email = client.auth.email

		for c in client.child_list:			
		 	KindergartenKey =  ndb.Key(Kindergarten, c.kindergarten_id)
		 	c.kindergarten_key = KindergartenKey
		 	c.parent_id = client.email 
		 	#c.put()
		 	kindergarten = Kindergarten.get_by_id(c.kindergarten_id)
		 	for kc in kindergarten.child_list:
		 	 	if ( client.email  == kc.parent_id ):
		 	 		kindergarten.child_list.remove(kc)


		client.put()



		for c in client.child_list:
			count = count +1			
			kindergarten = Kindergarten.get_by_id(c.kindergarten_id)
			# c.client_email =  client.auth.email
			# c.put()

			kindergarten.child_list.append(c)

			if ( count == len( client.child_list) ):				
				kindergarten.put()



		return client
示例#26
0
 def create_payment(self, commit=True, *args, **kwargs):
     '''
     Creates a new payment. Always use this method instead of manually
     creating a Payment instance directly.
     
     All arguments are passed directly to Payment constructor.
     
     When implementing a new payment provider, you may overload this method
     to return a specialized version of Payment instead.
     '''
     from models import Payment
     payment = Payment(variant=self._variant, *args, **kwargs)
     if commit:
         payment.save()
     return payment
示例#27
0
    def make_payment(self, contact_id=None, date_cursor=None, amount=0):
        if not date_cursor:
            date_cursor = datetime.now().date()

        if not contact_id:
            try:
                contact_id = self.policy.named_insured
            except:
                pass

        payment = Payment(self.policy.id, contact_id, amount, date_cursor)
        db.session.add(payment)
        db.session.commit()

        return payment
示例#28
0
    def __init__(self, table_p, parent, type_=None, payment=None, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.type_ = type_
        self.payment = payment
        self.parent = parent
        self.table_p = table_p

        if self.payment:
            self.new = False
            self.type_ = payment.type_
            self.payment_date_field = FormatDate(self.payment.date)
            self.payment_date_field.setEnabled(False)
            self.title = u"Modification de {} {}".format(self.payment.type_,
                                                         self.payment.libelle)
            self.succes_msg = u"{} a été bien mise à jour".format(
                self.payment.type_)

            if self.type_ == Payment.CREDIT:
                amount = payment.credit
            elif self.type_ == Payment.DEBIT:
                amount = payment.debit
        else:
            self.new = True
            amount = ""
            self.payment_date_field = FormatDate(QDate.currentDate())
            self.succes_msg = u"Client a été bien enregistré"
            self.title = u"Création d'un nouvel client"
            self.payment = Payment()
        self.setWindowTitle(self.title)

        self.amount_field = IntLineEdit(unicode(amount))
        self.libelle_field = QTextEdit(self.payment.libelle)

        vbox = QVBoxLayout()

        formbox = QFormLayout()
        formbox.addRow(FormLabel(u"Date : *"), self.payment_date_field)
        formbox.addRow(FormLabel(u"Libelle :"), self.libelle_field)
        formbox.addRow(FormLabel(u"Montant : *"), self.amount_field)

        butt = ButtonSave(u"Enregistrer")
        butt.clicked.connect(self.save_edit)
        formbox.addRow("", butt)

        vbox.addLayout(formbox)
        self.setLayout(vbox)
示例#29
0
def payments(id=None):
    if request.method == 'GET':
        if id is not None:
            payment = Payment.query.get(
                id)  # None por defecto si no consigue el registro
            if payment:
                return jsonify(payment.serialize()), 200
            return jsonify({"msg": "Financing Agreement not found"}), 404
        else:
            payment = Payment.query.all()
            payment = list(map(lambda payment: payment.serialize(), payment))
            return jsonify(payment), 200

    if request.method == 'POST':

        urlPDF = request.json.get("urlPDF", None)
        amount = request.json.get("amount", None)
        bank = request.json.get("bank", None)
        payment_method = request.json.get("payment_method", None)
        rut = request.json.get("rut", None)

        if not urlPDF:
            return jsonify({"msg": "URL is required"}), 400
        if not amount:
            return jsonify({"msg": "Amount is required"}), 400
        if not bank:
            return jsonify({"msg": "Bank is required"}), 400
        if not payment_method:
            return jsonify({"msg": "Payment Method is required"}), 400
        if not rut:
            return jsonify({"msg": "RUT is required"}), 400

        payment = Payment.query.filter_by(id=id).first()
        if payment:
            return jsonify({"msg": "Payment already exists"}), 400

        payment = Payment()
        payment.urlPDF = urlPDF
        payment.amount = amount
        payment.bank = bank
        payment.payment_method = payment_method
        payment.rut = rut

        payment.save()

        return jsonify({"success": "Payment Register Successfully"}), 200
示例#30
0
def payment():
    form = PaymentForm(request.form)
    users = User.query.filter(User.activated).order_by(User.email.asc())

    if request.method == 'POST' and form.validate():
        user = User.query.filter(User.id == request.form['user_id']).first()
        payment = Payment(user, form.value.data)
        dbs.add(payment)
        dbs.commit()
        flash('Payment added successfully.', 'alert alert-success')
        return redirect(url_for('payment'))
    else:
        data = {'nav_urls': get_urls(), 'active_url': url_for('payment')}
        return render_template('payment_add.html',
                               data=data,
                               form=form,
                               users=users)