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
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 calctotal(self): totalcost=0 for order in self.orderitems: totalcost=totalcost + order.getitem().itemprice * order.quantity payment=Payment(totalcost) return payment
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))
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()
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
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)
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)
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
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")
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)
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
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
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
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")
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)
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
def subtotal(self): subtotal = 0.0 for o in self.orderinfoList: subtotal += o.getMenuItem().itemPrice * o.quantity payment = Payment(subtotal, 0.1) return payment
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 calcTotal(self): total = 0.0 for n in self.orderitems: total += n.itemprice * n.itemquantity payment = Payment(total) return payment
def setUp(self): self.payment = Payment('35.00')
def __init__(self): """Machine constructor """ self.__ticket = Ticket() self.__timer = Timer() self.__payment = Payment(0.233333333)
def payment(self, amount, date): self.payments.append(Payment(amount, date))
def setUp(self): self.payment = Payment()
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)
produto = Product('Game of Trones', 50, 'comum_book') # criando um novo pedido order = Order(foolano, '08012') # adicionando um produto order.add_product(produto) produto2 = Product('bela e a fera', 30, 'midia_digital') order.add_product(produto2) print('Valor total do pedido:', order.total_amount()) # cria um pagamento attributes = dict( order=order, payment_method=CreditCard.fetch_by_hashed('43567890-987654367')) # endereço de cobrança shipping_address = Address('90233') payment = Payment(attributes=attributes) payment.pay(shipping_address) print('Valor do pagamento:') print(payment.amount) # começa os envios if (payment.is_paid()): print('Métodos de envio') payment.order.send_orders() else: pass print('################################################') # Teste sem desconto cliente2 = {"name": "alynne", "cpf": "487845", "zipcode": "04574"} print('Teste Cliente normal') foolano2 = Customer(cliente2)
def calcTotal(self): total = 0.0 for o in self.orderitems: total += o.getItem().itemprice * o.quantity payment = Payment(total) return payment
return self.result if __name__ == "__main__": if not settings.DEV_MODE: raise Exception("Payment testing must be run in DEV_MODE") # Configure logging. if not logging.getLogger().handlers: import threading import logging.config threading.currentThread().setName('Pay') # Used by the logger logging.config.fileConfig('./logging.conf') _x_root = logging.getLogger() _x_root.setLevel(settings.DEBUG and logging.DEBUG or logging.INFO) _x = logging.getLogger('payment.processor.authorizedotnet') from django.contrib.auth.models import User from payment import TransactionData, Payment data = TransactionData() data.user = User.objects.get(username='******') data.payment = Payment(invoice_num='12345', total_amount='0.01', cc_num='4007000000027', expiration_date='0509', ccv='144') processor = PaymentProcessor() processor.prepare_data(data) results, reason_code, msg = processor.process() _x.info(results, "::", reason_code, "::", msg)