Esempio n. 1
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
Esempio n. 2
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')
Esempio n. 3
0
def setup_tbl():
    Person.create_table(fail_silently=True)
    Company.create_table(fail_silently=True)
    Payment.create_table(fail_silently=True)
    Tariff.create_table(fail_silently=True)
    Point.create_table(fail_silently=True)
    Bike.create_table(fail_silently=True)
    ReservationState.create_table(fail_silently=True)
    Reservation.create_table(fail_silently=True)
Esempio n. 4
0
def confirmFormView(request, template_name="confirm.html"):

    if request.method == "POST" and "amount" in request.POST:
        amount = request.POST["amount"]
        payment = Payment(order_amount=amount)
        payment.save()
        payment_form = PaymentForm(instance=payment)

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Esempio n. 5
0
 def final_state(self, message, entry=False):
     texts = self.get_texts()
     user = self.get_user(message)
     if entry:
         if self.botType == "fi":
             messId = message.chat.id
             keybd = keyboards2
         elif self.botType == "sec":
             messId = message.from_user.id
             keybd = keyboards
         else:
             messId = ""
             keybd = ""
         bot = BotProfile.objects(id=self.bot_id).first()
         text = Payment.objects(
             id=user.payment.id).first().answer_text.replace(
                 '#wallet#', bot.wallet)
         self._bot.send_message(
             messId,
             text,
             reply_markup=keybd.set_keyboard(texts, [],
                                             back_btn=True,
                                             done_btn=True))
     else:
         if self.botType == "fi":
             messText = message.text
         elif self.botType == "sec":
             messText = message.data
         else:
             messText = ""
         if messText == texts['done_btn']:
             methods.create_order(self, user)
             self._go_to_state(message, self.districts_state)
         elif messText == texts['back_btn']:
             self._go_to_state(message, self.payment_state)
         else:
             if self.botType == "fi":
                 messId = message.chat.id
                 keybd = keyboards2
             elif self.botType == "sec":
                 messId = message.from_user.id
                 keybd = keyboards
             else:
                 messId = ""
                 keybd = ""
             text = Payment.objects(
                 id=user.payment.id).first().answer_on_payment
             self._bot.send_message(messId,
                                    text,
                                    reply_markup=keybd.set_keyboard(
                                        texts, [], back_btn=True))
             user.code = messText
             user.save()
             methods.create_order(self, user)
 def post(self):
     self.response.headers['Content-Type'] = 'application/json'
     jsonString = self.request.body       
     data = simplejson.loads(jsonString)
     contract = RentalContract()
     contract.createRentalContract(data)
     payment = Payment()
     payment.initializePayment(contract)
     #.createCheckinActivityRecord()          
     checkinResponse = {'checkinSuccessMessage':'Congratulations, you have checked in the room successfully!'}
     jsonCheckinResponse = simplejson.dumps(checkinResponse)
     return self.response.out.write(jsonCheckinResponse)
Esempio n. 7
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()
Esempio n. 8
0
 def create_payments(sale):
     for payment_index in self.payment_handler.payments_tree.get_children():
         payment_values = self.payment_handler.payments_tree.item(payment_index)['values']
         Payment.create(
             sale=sale,
             date=datetime.strptime(payment_values[2], DATE_FORMAT),
             type=Payment.TYPES[payment_values[3]],
             amount=string_to_float(payment_values[4]),
             currency=Payment.CURRENCIES[payment_values[5]],
             method=Payment.METHODS[payment_values[6]],
             rate= string_to_float(payment_values[7]),
             account=Payment.ACCOUNTS[payment_values[8]]
         )
Esempio n. 9
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
Esempio n. 10
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
Esempio n. 11
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)
Esempio n. 12
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()
Esempio n. 13
0
    def popup(self, pos):

        # from ui.ligne_edit import EditLigneViewWidget
        from ui.deleteview import DeleteViewWidget
        from data_helper import check_befor_update_payment

        if (len(self.data) -
                1) < self.selectionModel().selection().indexes()[0].row():
            return False
        menu = QMenu()
        editaction = menu.addAction("Modifier cette ligne")
        delaction = menu.addAction("Supprimer cette ligne")
        action = menu.exec_(self.mapToGlobal(pos))
        row = self.selectionModel().selection().indexes()[0].row()
        payment = Payment.get(id=self.data[row][-1])
        if action == editaction:
            self.parent.open_dialog(EditOrAddPaymentrDialog,
                                    modal=True,
                                    payment=payment,
                                    table_p=self)

        if action == delaction:
            self.parent.open_dialog(DeleteViewWidget,
                                    modal=True,
                                    table_p=self,
                                    obj=payment)
Esempio n. 14
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
Esempio n. 15
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
Esempio n. 16
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
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
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)
Esempio n. 20
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
Esempio n. 21
0
    def testAlarmWithPayment(self):
        # Create smartphone report sensor
        self.smartphone_sensor_type = SensorType.Create(self.e)
        schema = {'agreement': {'unit': '1-5 scale'}}
        self.smartphone_sensor_type.Update(name="Report Sensor",
                                           schema=json.dumps(schema))
        self.smartphone_sensor_type.put()

        self.smartphone_sensor = Sensor.Create(
            self.e, "1000",
            self.smartphone_sensor_type.key().id())
        self.smartphone_sensor.Update(
            sensortype_id=self.smartphone_sensor_type.key().id(),
            name="Smartphone Reports 1",
            contacts={"user": self.owner.key().id()})
        self.smartphone_sensor.put()

        # Create smartphone report rule with payment on any report
        PMNT_AMOUNT = 10.0
        self.any_report_rule = Rule.Create(self.e)
        self.any_report_rule.Update(
            name="Any Report",
            sensortype_id=self.smartphone_sensor_type.key().id(),
            column="agreement",
            trigger=RULE.ANY_DATA,
            payment_contacts=["user"],
            payment_amount=PMNT_AMOUNT,
            consecutive_limit=RULE.
            ANY,  # Deactivate immediately (should be == 1)
            duration=0)
        self.any_report_rule.put()

        self.assertTrue(self.any_report_rule.payments_enabled())

        self.process = ProcessTask.Create(self.e)
        self.process.Update(rule_ids=[self.any_report_rule.key().id()])
        self.process.put()

        # Apply our process to our sensor
        self.sp = SensorProcessTask.Create(self.e, self.process,
                                           self.smartphone_sensor)
        self.sp.put()

        BATCH_SIZE = 3
        BATCH_1 = {
            'agreement': [random.randint(1, 5) for x in range(BATCH_SIZE)],
        }
        self.__createNewRecords(BATCH_1,
                                first_dt=datetime.now(),
                                sensor=self.smartphone_sensor)
        self.__runProcessing()

        # This batch should have fired 3 alarms for any report, and created
        # 3 payments.

        pmnts = Payment.Fetch(self.owner)
        self.assertEqual(len(pmnts), 3)
        total_payments = BATCH_SIZE * PMNT_AMOUNT
        self.assertEqual(total_payments, sum([p.amount for p in pmnts]))
Esempio n. 22
0
 def delete_sale(self, sale_id):
     sale = Sale.get(sale_id)
     for payment in Payment.select().join(Sale).where(Sale.id==sale_id):
         payment.delete_instance()
     for order in Order.select().join(Sale).where(Sale.id==sale_id):
         order.delete_instance()
     sale.delete_instance()
     self.insert_into_daily_tree()
Esempio n. 23
0
 def set_data_for(self, *args):
     date_ = args[0]
     self.data = [
         (pay.date, pay.libelle, pay.debit, pay.credit, pay.balance, pay.id)
         for pay in Payment.filter(Payment.date > date_[0], Payment.date <
                                   date_[1]).order_by(Payment.date.desc())
     ]
     self.refresh()
def _create_or_replace_payment(lead, plan_slug, instalments):
	plan = Plan.find_by_slug(plan_slug)
	payment = Payment.find_open(lead.key, plan.key)

	if payment is None:
		payment = Payment()

	payment.lead = lead.key
	payment.plan = plan.key
	payment.status = 'PENDING'
	payment.message = 'Pending processing'
	payment.instalments = instalments
	payment.iframe_url = ''
	payment.put()

	_enqueue_payment_message(lead, payment)

	return payment
Esempio n. 25
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()
Esempio n. 26
0
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()
Esempio n. 27
0
def pay_for_reservation(event_id, reservation_token) -> Response:
    payment_token = request.json['payment_token']
    ticket = db.session.query(Ticket).filter_by(
        token=reservation_token).first()
    reservation = ticket.reservations[0]
    payment = Payment(reservation=reservation)

    try:
        payment_result = PaymentGateway().charge(100, payment_token)
        payment.completed = True
    except (CardError, PaymentError, CurrencyError):
        pass
    db.session.add(payment)
    db.session.commit()
    return jsonify({
        "paid": payment.completed,
        "event": ticket.event.to_dict(),
        "ticket_type": ticket.ticket_type.name
    })
Esempio n. 28
0
 def __init__(self, payments):
   self.user = payments[0].user
   self.items_offset = 0.03
   self.payments = payments
   self.context = None
   self.width = 0
   self.height = 0
   self.settings = None
   if os.path.isfile('print_settings'): self.settings = gtk.print_settings_new_from_file('print_settings')
   self.receipt_number = Payment.last_receipt_number()+1
Esempio n. 29
0
def ProcessPayment():
    if request.method == "GET":
        return render_template("pay.html")
    else:
        try:
            valid_data = validate(request)
        except Exception as e:
            return Response(e.__str__() + " <br><a href='/pay'>Go back</a>",
                            status=400)

        payment = Payment(valid_data)
        try:
            payment.execute_payment()
        except Exception as e:
            return Response(e.__str__(), status=400)

        return Response(
            "Payment was successful.<br><a href='/pay'>New payment'</a>",
            status=200)
Esempio n. 30
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()
Esempio n. 31
0
 def PaymentStatus(self,token):
     q = Payment.all()
     q.filter("token = ",token)
     p = q.fetch(1)[0]
     
     resp = {
         "token" : token,
         "isComplete" : p.complete
     }
     
     self.response.out.write(json.dumps(resp))
Esempio n. 32
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
Esempio n. 33
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'
Esempio n. 34
0
def get_debts_to_pay(student):
    debts = Debt.select()
    debts = [
        debt for debt in debts
        if student.entrou < datetime(debt.year, debt.month, 1) < student.saiu
    ]
    if not student.drink_coffee:
        debts = [debt for debt in debts if debt.type == 1]
    payments = Payment.filter(Payment.student_id == student.id)
    paid_debts = [pay.debt for pay in payments]
    return [debt for debt in debts if not debt in paid_debts]
Esempio n. 35
0
 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")
Esempio n. 36
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
Esempio n. 37
0
def get_filtered_payments(args):
    pid = args.get("id")
    name = args.get("name")
    payments = Payment.select()

    if pid:
        payments = payments.where(Payment.id == pid)

    if name:
        payments = payments.where(Payment.name == name)

    return payments.order_by(Payment.id.desc())
def open_pay(id):
	if 'plan' not in request.args:
		abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })

	lead = _get_lead(int(id))
	plan = Plan.find_by_slug(request.args['plan'])
	payment = Payment.find_last(lead.key, plan.key)

	if payment is not None:
		return jsonify(data=payment.to_json()), 200
	else:
		abort(404, {'message': 'Payment not found'})
Esempio n. 39
0
 def FetchPayment(self,token):
     q = Payment.all()
     q.filter("token =", token)
     p = q.fetch(1)[0]
 
     values = {
         "company" : p.company,
         "amount" : p.amount,
         "token" : p.token
     }
     
     path = os.path.join(os.path.dirname(__file__), 'templates/payment_details.html')
     self.response.out.write(template.render(path, values))
Esempio n. 40
0
 def DoPayment(self,token):        
     q = Payment.all()
     q.filter("token = ",token)
     p = q.fetch(1)[0]
     
     if p:
         p.complete = True
         p.put()
     
     values = {
         "confirmation_code" : str(self.GenerateToken())
     }
     
     path = os.path.join(os.path.dirname(__file__), 'templates/payment_complete.html')
     self.response.out.write(template.render(path, values))
Esempio n. 41
0
 def CreatePayment(self,details):
                     
     p = Payment()
     p.amount = details["amount"]
     p.company = details["company"]
     p.complete = False
     p.token = str(self.GenerateToken())        
     p.put()
     
     resp = {
         "success" : True ,
         "token" : p.token
     }        
     self.response.out.write(json.dumps(resp))
             
     return True
 def get(self):
     payment_key = self.request.get('payment_key')
     payment = Payment.get(payment_key)
     transactions_list = payment.getTenantTransactions()
     transactions_list_json = json.dumps(transactions_list)
     self.response.out.write(transactions_list_json)
def _enqueue_payment_message(lead, payment):
	params = {
		'lead_id': lead.key.id(),
		'payment_id': payment.key.id()
	}
	Payment.enqueue(params)
Esempio n. 44
0
 def clean_shopId(self):
     shop_id = self.cleaned_data["shopId"]
     if shop_id != settings.YANDEX_MONEY_SHOP_ID and not shop_id in Payment.get_used_shop_ids():
         raise forms.ValidationError(self.error_messages[self.ERROR_MESSAGE_CODES.BAD_SHOP_ID])
     return shop_id
Esempio n. 45
0
def generate_payment():
    payment_method = session.user.default_payment_method
    payment = Payment.generate(user=session.user, payment_method=payment_method)
    return jsonify(payment=payment.json)
def process_payment():
	lead_id = request.form['lead_id']
	payment_id = request.form['payment_id']

	logging.debug('###### BACKGROUND PROCESSING!')
	logging.debug('Lead Id: %s' % lead_id)
	logging.debug('Payment Id: %s' % payment_id)

	lead = _get_lead(int(lead_id))
	payment = Payment.get_by_id(int(payment_id))
	plan = payment.plan.get()

	property_owner = lead.property_owner.get()
	customer_data = property_owner.to_json()
	email = customer_data['email']
	credit_card_brand = customer_data['credit_card_brand']

	logging.debug('trying to find customer %s' % email)
	fc_result = superlogica.find_customer(email)
	payment.update_status('PENDING', 'Creating customer')

	customer_id = None
	if fc_result is not None:
		if len(fc_result['body']) > 0:
			pprint.pprint(fc_result)
			customer_id = fc_result['body'][0]['id_sacado_sac']
			logging.debug('customer %s found' % customer_id)
		else:
			logging.debug('customer not found.')

	if customer_id is None:
		logging.debug('customer not found. lets create a new one')
		customer_result = _try_create_customer(customer_data)
		customer_id = customer_result['id_sacado_sac']
		logging.debug('customer %s created' % customer_id)


	payment.update_status('PENDING', 'Creating billing')
	if customer_id is not None:
		logging.debug('creating billing')
		bl_result = superlogica.create_billing(customer_id, plan.price, payment.instalments, plan.erp_id)
		logging.debug('registering creditcard')

		billing = Billing()
		billing.erp_result = bl_result
		billing.lead = lead.key
		billing.put()

		payment.update_status('PENDING', 'Creating credit card')
		callback_url = URL_CALLBACK % plan.slug
		cc_result = superlogica.register_creditcard(email, credit_card_brand.lower(), callback_url)

		url = cc_result['body']['url']
		payment.iframe_url = url
		payment.put()
		payment.update_status('SUCCESS', 'Done')

		lead.status = 'PENDING_PAYMENT'
		lead.put()

		create_activity('LEAD_PENDING_PAYMENT', lead=lead)
	else:
		payment.update_status('ERROR', 'Cannot create customer or billing at ERP')

	return '', 200