Exemple #1
0
class PaymentTest(unittest.TestCase):
    """
    测试支付接口
    """
    def setUp(self):
        self.payment = Payment()

    def test_success(self):
        """
        测试支付成功
        :return:
        """
        self.payment.authe = mock.Mock(return_value=200)
        res = self.payment.pay(user_id=10001, card_num="123444", amount=1000)
        self.assertEqual("success", res)

    def test_fail(self):
        """
        测试支付成功
        :return:
        """
        self.payment.authe = mock.Mock(return_value=500)
        res = self.payment.pay(user_id=10002, card_num="1233444", amount=1000)
        self.assertEqual("fail", res)

    def test_retry_success(self):
        """
                测试支付失败重试在成功
                side_effect 可以为序列类型 异常类型,对象
                如果为序列类型 每次调用mock对象,会依次将side effcet中的元素返回
                :return:
                """
        self.payment.authe = mock.Mock(side_effect=[TimeoutError, 200])
        res = self.payment.pay(user_id=10003, card_num="1234444", amount=1000)
        self.assertEqual("success", res)
Exemple #2
0
def test_ExpensivePaymentGatewayRetriesOnCheapOne(mocker):
    amount = 25.23
    payment = Payment(creditCardNumber, cardHolder, expirationDate, securityCode, amount)
    mocked_func = mocker.patch('expensivePaymentGateway.ExpensivePaymentGateway.processPayment')
    mocked_func2 = mocker.patch('cheapPaymentGateway.CheapPaymentGateway.processPayment')
    payment.process()
    mocked_func.assert_called()
    mocked_func2.assert_called()
    def processExit(self, DigiTicket, gate):

        payment = Payment(DigiTicket)
        # get the calculated payment
        totlalPayment = payment.calculateCost(DigiTicket)
        # do the payment processing
        DigiTicket.processPayment(totlalPayment)
        print(repr(DigiTicket))
Exemple #4
0
 def __init__(self, num_floors, num_slots):
     self.lot = [[None for _ in range(num_slots)]
                 for _ in range(num_floors)]
     self.num_floors = num_floors
     self.num_slots = num_slots
     self.payment = Payment()
     self.filled = 0
     self.vehicles = VehicleFactory()
Exemple #5
0
    def __init__(self, ticket, tariff):
        Payment.__init__(self, ticket.payments)

        self._enabled = hasattr(tariff, 'calc')
        if not self._enabled:
            return

        self.ticket = ticket
        self.tariff = tariff
        self.now = datetime.now()
Exemple #6
0
    def __init__(self, card, tariff):
        Payment.__init__(self, card.payments)
        self.card = card

        self._enabled = hasattr(tariff, 'calc')
        if not self._enabled:
            return

        self.tariff = tariff
        self.result = self.tariff.calc(self.card.date_reg, self.card.date_end)
        if self.result is None:
            self._enabled = False
Exemple #7
0
def buy_cart(customer_obj, cart_obj):
    products = cart_obj.get_cart_items()
    total_price = cart_obj.get_total_price()
    print("Total price to be paid " + str(total_price))
    print("Payment details : ")
    card_type = input("Enter card type : ")
    card_num = input("Enter card number : ")
    payment_obj = Payment(customer_obj.get_id(), total_price, card_type,
                          card_num)
    success = customer_obj.buy_products_in_bulk(products, payment_obj)
    if success:
        print("Shipment successfully initiated. Payment reference ID = " +
              str(payment_obj.get_id()))
    else:
        print("Some problem occurred while transaction")
Exemple #8
0
 def buy(self, payment: Payment, kind_of_drink: Type[Drink]):
     try:
         return self._buy(payment, kind_of_drink)
     except Exception as e:
         print(e)
         self._change += payment.amount()
         return None
def programNew(userInput):
    readyToSubmit = False
    while not readyToSubmit:
        printHeader("CREATING A NEW PAYMENT")
        # Request Payment Info
        paymentName = requestPaymentName(None)
        paymentValue = requestPaymentValue(None)
        paymentDate = requestPaymentDate(None)
        paymentReoccurence = requestPaymentReoccurence(paymentDate)

        # User Validation
        printHeader("CONFIRM PAYMENT CREATION")
        printUserInputs(paymentName, paymentValue, paymentDate,
                        paymentReoccurence)
        userValidation = userValidate("Are you okay with these values?")
        if not userValidation:
            readyToSubmit = False
            continue
        readyToSubmit = True

        # Create Payment and Append to paymentList
        newPayment = Payment(paymentName, paymentValue, paymentDate,
                             paymentReoccurence)
        if not newPayment:
            printHeader("NEW PAYMENT ERROR")
            printError("Failed to create new payment with given credentials.")
            return False
        paymentList.append(newPayment)

    # Closure
    printHeader("SUCCESSFULLY CREATED PAYMENT")
    printPayment(newPayment)
    return True
Exemple #10
0
 def test_paid_status(self):
     pmt: Payment = Payment()
     assert not pmt.paid
     assert pmt.paid_status == "not yet paid"
     pmt.paid = True
     assert pmt.paid
     assert pmt.paid_status == "paid"
 def check(self, db):
     return Payment.check(self, db) + _('date: %(now)s\n'
                                        '%(tariff)s: $%(price)s\n'
                                        '<hr />') % {
                                            'now': datetime.now().strftime(DATETIME_FORMAT_USER),
                                            'tariff': self.tariff.title,
                                            'price': self.price
                                        }
Exemple #12
0
def ProcessPayment():
    data = request.form
    creditCardNumber, cardHolder, expirationDate, securityCode, amount = SanitizeParameters(
        data)
    try:
        payment = Payment(creditCardNumber, cardHolder, expirationDate,
                          securityCode, amount)
        print("uptest")
        result = payment.process()
        print("test")
        if result.status_code == 200:
            return "Payment is processed : 200 OK", 200
    except (TypeError, ValueError) as e:
        return "The request is invalid: 400 bad request", 400
    except:
        return "500 internal server error", 500
    return "500 internal server error", 500
Exemple #13
0
    def calctotal(self):
        totalcost=0
        for order in self.orderitems:
            totalcost=totalcost + order.getitem().itemprice * order.quantity
                    
        payment=Payment(totalcost)

        return payment
Exemple #14
0
    def test_payable_within_2days(self):
        pmt: Payment = Payment(due_date=datetime.now())
        assert pmt.payable_within_2days
        pmt.paid = True
        assert not pmt.payable_within_2days

        pmt.paid = False
        pmt.due_date += timedelta(days=3)
        assert not pmt.payable_within_2days
def programEdit(userInput):
    if len(userInput) == 1 or userInput == "":
        printHeader("EDIT PAYMENT ERROR")
        printError("Edit must have a second parameter")
        return True

    # Find Payment in List
    printHeader("FINDING PAYMENT TO EDIT")
    paymentIndex = findPayment(userInput[1])
    if paymentIndex < 0:
        printError("'" + userInput[1] + "' does not exist.")
        return True
    foundPayment = paymentList[paymentIndex]

    # Validate Payment Selection
    printPayment(foundPayment)
    userValidation = userValidate("Do you want to edit this payment?")
    if not userValidation:
        return True

    readyToSubmit = False
    while not readyToSubmit:
        printHeader("UPDATING EXISTING PAYMENT")
        # Request Payment Info
        paymentName = requestPaymentName(foundPayment)
        paymentValue = requestPaymentValue(foundPayment)
        paymentDate = requestPaymentDate(foundPayment)
        paymentReoccurence = requestPaymentReoccurence(paymentDate)

        # User Validation
        printHeader("CONFIRM PAYMENT UPDATE")
        printUserInputs(paymentName, paymentValue, paymentDate,
                        paymentReoccurence)
        userValidation = userValidate("Are you okay with these values?")
        if not userValidation:
            readyToSubmit = False
            continue
        readyToSubmit = True

        # Update Payment in Payment List
        backupPayment = paymentList[paymentIndex]
        paymentList[paymentIndex] = Payment(paymentName, paymentValue,
                                            paymentDate, paymentReoccurence)
        foundPayment = paymentList[paymentIndex]
        if not foundPayment:
            printHeader("EDIT PAYMENT ERROR")
            printError(
                "Failed to update existing payment with given credentials. Returning to old values"
            )
            paymentList[paymentIndex] = backupPayment
            return False

    # Closure
    printHeader("SUCCESSFULLY EDITED PAYMENT")
    printPayment(foundPayment)
    return True
Exemple #16
0
def get_payments_by_order_id(sql_connection, order_id):
    sql_cursor = sql_connection.cursor()
    sql_cursor.execute(GET_PAYMENTS_BY_ORDER_ID, (order_id, ))
    results = sql_cursor.fetchall()
    sql_cursor.close()
    payments = []
    for result in results:
        payment = Payment(result[0], result[1], result[2], result[3])
        payments.append(payment)

    return payments
Exemple #17
0
def main():
    customer1 = Customer("John Wick", "Makedonias 3")
    customer1.place_order(Order("20201215", Payment(100000)))
    customer1.place_order(Order("20201216", Payment(250000)))
    customer2 = Customer("Nemo", "MC Wallaby 42")
    customer2.place_order(
        Order("20201205", Credit(34235, "2349673", "20221010")))
    customer2.place_order(
        Order("20201205", Credit(5436, "2349673", "20221010")))
    customer3 = Customer("John Snow", "The Wall")
    customer3.place_order(Order("20201203", Payment(4234)))
    customer3.place_order(Order("20203905", Credit(5436, "746853",
                                                   "20221111")))
    customer3.place_order(
        Order("20203905", Check(654735, "555555", "20210203")))
    print(customer1)
    print("")
    print(customer2)
    print("")
    print(customer3)
Exemple #18
0
def buy_product(customer_obj):
    view_products(customer_obj)
    print()
    product_id = int(input("Enter the id of the product to buy : "))
    product_obj = database.get_product(product_id)
    if product_obj is None:
        print("Enter a valid product ID!")
        return
    quantity = int(input("Enter the quantity : "))
    price = product_obj.get_price() * quantity
    print("Total price to be paid " + str(price))
    print()
    print("PAYMENT DETAILS")
    card_type = input("Enter card type : ")
    card_num = input("Enter card number : ")
    payment_obj = Payment(customer_obj.get_id(), price, card_type, card_num)
    success = customer_obj.buy_product(product_obj, payment_obj, quantity)
    if success:
        print("Shipment successfully initiated. Payment reference ID = " +
              str(payment_obj.get_id()))
    else:
        print("Some problem occurred while transaction")
Exemple #19
0
    def refund(self, payment: Payment, price: int):
        currencies = payment.get_currencies()
        if len(currencies) != 1:
            raise RuntimeError('payment should be a currency')

        payment_amount = payment.amount()
        if (payment_amount != 100) and (payment_amount != 500):
            raise RuntimeError('payment should be 100 or 500')

        if payment_amount == 500 and self._currency_collections[Yen100Coin] < 4:
            raise RuntimeError('Not enouhg 100 coin for change')

        change = 0
        if payment_amount == 100:
            self._currency_collections[Yen100Coin] += 1
            change = 0

        if payment_amount == 500:
            self._currency_collections[Yen100Coin] -= (payment_amount - 100) / 100
            change += (payment.amount() - price)

        return change
Exemple #20
0
 def setUpClass(cls):
     print("testing start")
     cls.busSpace = 2
     cls.carSpace = 2
     cls.bikeSpace = 3
     cls.parkingLot = ParkingLot('Metro Station Parking',
                                 'Near Metro Station Parking')
     cls.floor = ParkingFloor('floor', cls.carSpace, cls.busSpace,
                              cls.bikeSpace)
     cls.parkingLot.addLevel(cls.floor)
     cls.gate = Gate(1)
     cls.vehicle = Vehicle(56, 'bus')
     cls.ticket = Ticket(cls.vehicle)
     cls.parkingLot.processEntry(cls.ticket, cls.gate)
     cls.payment = Payment(cls.ticket)
Exemple #21
0
def process_payment():
    response_object = dict()

    post_data = request.get_json()
    validobject = Validation(post_data)
    check_datatype = validobject.checkrequestdatatype()
    if check_datatype:
        check_param = validobject.validate_params()

        if check_param:
            payobject = Payment(post_data)
            if post_data['Amount'] < 20:
                response = payobject.CheapPaymentGateway()
                if response['ok']:
                    response_object['status'] = 'ok'
                    response_object['statusCode'] = '200'
                else:
                    response_object['status'] = 'internal server error'
                    response_object['statusCode'] = '500'

            elif post_data['Amount'] < 500:

                response = payobject.ExpensivePaymentGateway()
                if response['ok']:
                    response_object['status'] = 'ok'
                    response_object['statusCode'] = '200'

                else:
                    response = payobject.CheapPaymentGateway()
                    if response['ok']:
                        response_object['status'] = 'ok'
                        response_object['statusCode'] = '200'

                    else:
                        response_object['status'] = 'internal server error'
                        response_object['statusCode'] = '500'

            else:
                retry_counter = 3
                for _ in range(retry_counter + 1):
                    response = payobject.PremiumPaymentGateway()
                    if response['ok']:
                        response_object['status'] = 'ok'
                        response_object['statusCode'] = '200'
                        break
                    response_object['status'] = 'internal server error'
                    response_object['statusCode'] = '500'
        else:
            response_object['status'] = 'bad request'
            response_object['statusCode'] = '400'
    else:
        response_object['status'] = 'bad request'
        response_object['statusCode'] = '400'

    return jsonify(response_object)
Exemple #22
0
    def check(self, db):
        args = {
            'time_in': self.ticket.time_in.strftime(DATETIME_FORMAT_USER),
            'now': self.now.strftime(DATETIME_FORMAT_USER),
            'cost_info': self.tariff.cost_info_check,
            'duration': self.result.check_duration,
            'paid_until': self.paid_until.strftime(DATETIME_FORMAT_USER),
            'price': self.price,
            'bar': self.ticket.bar
        }

        return (Payment.check(self, db) + _('  entry time: %(time_in)s\n'
                                            'payment time: %(now)s\n'
                                            '      tariff: %(cost_info)s\n'
                                            'parking duration: %(duration)s\n'
                                            '  paid until: %(paid_until)s\n'
                                            '<hr />\n'
                                            'Price: $%(price)s\n'
                                            '<hr />\n'
                                            '<<%(bar)s>>') % args)
Exemple #23
0
    def check(self, db):
        args = {
            'sn': self.card.sn,
            'tariff': self.tariff.title,
            'cost_info': self.tariff.cost_info_check,
            'begin': self.card.date_reg.strftime(DATE_USER_FORMAT),
            'end': self.card.date_end.strftime(DATE_USER_FORMAT),
            'refill': _('_Refill for ') + self.tariff.interval_str_check(self.result.units, True),
            'new_begin': self.result.begin.strftime(DATE_USER_FORMAT),
            'new_end': self.result.end.strftime(DATE_USER_FORMAT),
            'price': self.price
        }

        return Payment.check(self, db) + _('Card %(sn)s\n'
                                           '%(tariff)s: %(cost_info)s\n'
                                           'Before refill: from %(begin)s to %(end)s\n'
                                           '%(refill)s\n'
                                           'After refill: from %(new_begin)s to %(new_end)s\n'
                                           '<hr />\n'
                                           'Price: %(price)s\n'
                                           '<hr />') % args
Exemple #24
0
def Confirmation():
    import time
    from payment import Payment
    import payment

    #confirm = Selection()
    print('Please press "Y" to confirm or "N" to cancel')
    confirm = input().lower()
    value = ['y', 'yes']
    denyvalue = ['n', 'no']
    while confirm is not value:

        if confirm in value:
            Payment(sel)
            print('Please Wait')
            time.sleep(1)
            print('Your coffee is getting ready')
            time.sleep(1)
            break

        elif confirm in denyvalue:  # here something wrong
            print('Please made again your choice')
            confirm = Selection()
            print('Please press "Y" to confirm', sel, 'or "N" to cancel')
            confirm = input().lower()
            value = ['y', 'yes']
            denyvalue = ['n', 'no']

        else:
            print("Your selection hasn't been recognise ")
            print('Please press "Y" to confirm', sel, 'or "N" to cancel')
            confirm = input()
        continue
    time.sleep(2)
    print('Your coffie now is Ready')
    print('Your remaining credit is', payment.credit - 1)
    time.sleep(1)
    print('Please collect your change and enjoy your drink')
    time.sleep(4)
    credit = 0
Exemple #25
0
    def clean(self):
        super(DirectContributionForm, self).clean()
        if not self._errors and not self.campaign.is_free:
            #
            # ---- IMPORTANT -----
            #
            # Ideally, we would verify the CC here and post the transaction
            # later in save(). However, there isn't an efficient way to merely
            # verify a credit card without actually posting the CC transaction;
            # All that the ``CreditCardField`` validates that the CC number
            # abides by the Luhn-checksum but this could still not be a
            # legitimately issued CC number.
            #
            # Therefore, post the transaction here and produce validation errors
            # based on what the transaction processor returns.
            #
            # The end result is that if this method succeeds, the transaction has
            # already been posted.
            #

            # Save ``UserProfile`` and ``User`` fields to the database
            # because ``TransactionData`` needs to extract the payer's
            # name and address from the user instance.
            UserProfileForm.save(self, commit=True)
            data = TransactionData()
            data.user = self.user_profile.user
            payment = Payment()
            data.payment = payment
            payment.invoice_num = make_invoice_num(self.campaign, data.user)
            payment.total_amount = '%s' % self.campaign.contribution_amount * self.qty
            payment.cc_num = self.cleaned_data['cc_num']
            payment.expiration_date = self.cleaned_data['expiration_date']
            payment.ccv = self.cleaned_data['ccv']
            self.payment_processor = PaymentProcessor()
            extra = dict(x_description=self.campaign.title)
            self.payment_processor.prepare_data(data, extra_dict=extra)
            is_success, code, text = self.payment_processor.process()
            if not is_success:
                raise forms.ValidationError(escape(text))
        return self.cleaned_data
Exemple #26
0
    def populate_categories(self):
        active_row = self.get_active_row
        for column in self._monitored_cols:
            name = self._sheet[f"{column}1"].value
            item: PaymentCategory = PaymentCategory(name=name, column=column)
            amount = float(self._sheet[f"{column}{active_row}"].value)
            column_int = self._sheet[f"{column}{active_row}"].col_idx
            try:
                done = bool(
                    self._sheet.cell(column=column_int + 1,
                                     row=active_row).value)
            except ValueError:
                done = False

            due_date = self._sheet.cell(column=column_int + 2,
                                        row=active_row).value
            new_payment = Payment(paid=done,
                                  due_date=due_date,
                                  amount=amount,
                                  excel_row=active_row)
            item.payments.append(new_payment)

            self._categories.append(item)
Exemple #27
0
def generate_payment(payroll_path):
    nomina_path = payroll_path

    tree = ET.parse(nomina_path)
    root = tree.getroot()
    perceptions = {}
    deductions = {}
    tag = "{http://www.sat.gob.mx/nomina12}"  # TODO code a function to get tag

    for node in tree.iter():
        # TODO: create a dictionary with all strings keys
        if tag + "Percepcion" == node.tag:
            concept, amount = get_concept(node, "Concepto", "ImporteExento",
                                          "ImporteGravado")
            perceptions[concept] = amount

        elif tag + "Deduccion" == node.tag:
            concept, amount = get_concept(node, "Concepto", "Importe")
            deductions[concept] = amount

    date = get_date(root)
    payment = Payment(date, perceptions, deductions)
    return payment
Exemple #28
0
    def clean(self):
        super(DirectContributionForm, self).clean()
        if not self._errors and not self.campaign.is_free:
            #
            # ---- IMPORTANT -----
            #
            # Ideally, we would verify the CC here and post the transaction
            # later in save(). However, there isn't an efficient way to merely
            # verify a credit card without actually posting the CC transaction; 
            # All that the ``CreditCardField`` validates that the CC number 
            # abides by the Luhn-checksum but this could still not be a 
            # legitimately issued CC number.
            #
            # Therefore, post the transaction here and produce validation errors 
            # based on what the transaction processor returns.
            #
            # The end result is that if this method succeeds, the transaction has 
            # already been posted.
            #

            # Save ``UserProfile`` and ``User`` fields to the database
            # because ``TransactionData`` needs to extract the payer's
            # name and address from the user instance.
            UserProfileForm.save(self, commit=True)
            data = TransactionData()
            data.user = self.user_profile.user
            payment = Payment()
            data.payment = payment
            payment.invoice_num = make_invoice_num(self.campaign, data.user)
            payment.total_amount = '%s' % self.campaign.contribution_amount * self.qty
            payment.cc_num = self.cleaned_data['cc_num']
            payment.expiration_date = self.cleaned_data['expiration_date']
            payment.ccv = self.cleaned_data['ccv']
            self.payment_processor = PaymentProcessor()
            extra = dict(x_description=self.campaign.title)
            self.payment_processor.prepare_data(data, extra_dict=extra)
            is_success, code, text = self.payment_processor.process()
            if not is_success:
                raise forms.ValidationError(escape(text))
        return self.cleaned_data
Exemple #29
0
from flask import Flask, request, render_template
from core import Core
from payment import Payment

application = Flask(__name__)
core = Core()
payment = Payment()


@application.route('/', methods=['POST', 'GET'])
@application.route('/index', methods=['POST', 'GET'])
def index():
    publicKey = request.form.get('publicKey')
    privateKey = request.form.get('privateKey')
    validPublicKey = core.checkWallet(publicKey, privateKey)
    if validPublicKey:
        core.createUser(publicKey, privateKey)
        services = core.getServicesWithStates(publicKey)
        return render_template('index.html',
                               publicKey=publicKey,
                               services=services)
    else:
        return render_template('index.html')


@application.route('/subscribe', methods=['POST'])
def subscribe():
    publicKey = request.form.get('publicKey')
    serviceId = request.form.get('serviceId')
    core.subscribe(publicKey, serviceId)
    services = core.getServicesWithStates(publicKey)
 def setUp(self):
     self.payment = Payment('35.00')
Exemple #31
0
 def __init__(self):
     """Machine constructor
     """
     self.__ticket = Ticket()
     self.__timer = Timer()
     self.__payment = Payment(0.233333333)
Exemple #32
0
	def get_received(self):
		if self.entrance_address == '':
			return 0.0
		p = Payment()
		return p.get_address_received(self.entrance_address)
 def payment(self, amount, date):
     self.payments.append(Payment(amount, date))
Exemple #34
0
 def __init__(self, card):
     Payment.__init__(self, card.payments)
     self.card = card
Exemple #35
0
shop1 = ShoppingCart(1, customer1)

# h) Adding new online orders (only for testing)

order1 = OnlineOrders(2, shop1.products, shop1.customer)
toy_store.add_new_onlineOrders(order1)

# i) Adding new delivery company

company_postal_service = DeliveryCompany("Postal Office", 1, 222)
toy_store.add_new_delivery_company(company_postal_service)

company_in_house_courier = DeliveryCompany("In-house courier", 2, 333)
toy_store.add_new_delivery_company(company_in_house_courier)

# j) Adding new Loyalty_Schemes:

christmas_card = LoyaltySchemes("Christmas", 1, "Gift Card", 5)
toy_store.add_new_loyalty_schemes(christmas_card)

new_year_card = LoyaltySchemes("New Year", 2, "Promotional Code", 5)
toy_store.add_new_loyalty_schemes(new_year_card)

# l) Adding new order details: (only for testing)
order_details1 = OrderDetails(order1)
toy_store.add_new_order_details(order_details1)

# m) Adding new payment: (only for testing)

paym1 = Payment(1, 2, 1, toy_store.current_user)
Exemple #36
0
 def __init__(self, ticket):
     Payment.__init__(self, ticket.payments)
     self.ticket = ticket
Exemple #37
0
	def withdraw(self, amount, address):
		p = Payment()
		return p.withdraw(amount, address)
Exemple #38
0
 def subtotal(self):
     subtotal = 0.0
     for o in self.orderinfoList:
         subtotal += o.getMenuItem().itemPrice * o.quantity
     payment = Payment(subtotal, 0.1)
     return payment
Exemple #39
0
 def setUp(self):
     self.payment = Payment()
 def __init__(self, payable, tariff):
     Payment.__init__(self, payable.payments)
     self.tariff = tariff
Exemple #41
0
class Machine:
    """This class offers funcionalities to register the entrance, exit and payments when someone wants to park a vehicle.
    """
    def __init__(self):
        """Machine constructor
        """
        self.__ticket = Ticket()
        self.__timer = Timer()
        self.__payment = Payment(0.233333333)

    def register_entrance(self, car_id, time_in):
        """This function calls the register_ticket function to create a new ticket
    
        Args:
            car_id (int): This is the ID of each vehicle (Placa).
            time_in (string): This is the time when the vehicle enter to the parking.
        """
        self.__ticket.register_ticket(car_id, time_in)

    def register_exit(self, ticket, time_exit):
        """This function register the time when a vehicle is leaving the parking
    
        Args:
            ticket (dictionary): This argument contains the info of the vehicle.
            time_exit (string): This argument is the time when the vehicle is leaving.
        """
        self.__ticket.set_time_exit(ticket, time_exit)

    def print_list_cars(self):
        """This functions prints all tickets created.
        """
        self.__ticket.print_all_tickets()

    def payment(self, car_id, time_exit):
        """This function calls to the register_exit, payment and print_ticket functions
        """
        ticket = self.__ticket.search_ticket(car_id)
        if (ticket == None):
            self.print_ticket(ticket)
        else:
            self.register_exit(ticket, time_exit)
            self.__payment.register_payment(ticket, self.__ticket)
            self.print_ticket(ticket)

    def print_ticket(self, ticket):
        """This function prints two differente tickets
        When not registered it prints: Unregistered Vehicle
        if exists, it prints the ticket in detail.
        """
        if (ticket == None):
            text = """
            ----------------------------
                Unregistered vehicle
            ----------------------------
            """
        else:
            today = self.__timer.get_date_today()
            text = """
            ----------------------------
                    PAID PARKING        
            ----------------------------
            Date: {0}
            From: {1}
            To: {2}
            Paid: Bs. {3}
            ----------------------------
            Thank you and lucky road!
            ----------------------------
            """.format(today, self.__ticket.get_time_in(ticket),
                       self.__ticket.get_time_exit(ticket),
                       self.__ticket.get_cost(ticket))
        print(text)
 def __init__(self, payable):
     Payment.__init__(self, payable.payments)
def calculate_payment(email):
    total_earned = Payment.calculate(email)
    num_games = Payment.num_games_contributed(email)
    return f"Your estimated earnings are ${total_earned:.2f}.<br><br>You contributed to {num_games} games."
Exemple #44
0
 def calcTotal(self):
     total = 0.0
     for o in self.orderitems:
         total += o.getItem().itemprice * o.quantity
     payment = Payment(total)
     return payment
Exemple #45
0
	def get_new_address(self):
		p = Payment()
		addr = p.get_new_address()
		self.entrance_address = addr
		return addr