Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: connfigure ruff etc #99

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Since version 2.23 (released in August 2019), git-blame has a feature
# to ignore or bypass certain commits.
#
# This file contains a list of commits that are not likely what you
# are looking for in a blame, such as mass reformatting or renaming.
# You can set this file as a default ignore file for blame by running
# the following command.
#
# $ git config blame.ignoreRevsFile .git-blame-ignore-revs

# Ruff style the codebase
02510e3526de8aedd3dea6a693a86221922df7cb
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ tags
payments/docs/current
node_modules/
__pycache__/
.helix
.aider*
25 changes: 10 additions & 15 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,19 @@ repos:
- id: check-yaml
- id: debug-statements

- repo: https://github.com/asottile/pyupgrade
rev: v2.34.0
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.2.0
hooks:
- id: pyupgrade
args: ['--py310-plus']
- id: ruff
name: "Run ruff import sorter"
args: ["--select=I", "--fix"]

- repo: https://github.com/adityahase/black
rev: 9cb0a69f4d0030cdf687eddf314468b39ed54119
hooks:
- id: black
additional_dependencies: ['click==8.0.4']
- id: ruff
name: "Run ruff linter"

- id: ruff-format
name: "Run ruff formatter"

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies: ['flake8-bugbear',]
args: ['--config', '.github/helper/flake8.conf']

ci:
autoupdate_schedule: weekly
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


class BraintreeSettings(Document):
supported_currencies = [
supported_currencies = (
"AED",
"AMD",
"AOA",
Expand Down Expand Up @@ -150,7 +150,7 @@ class BraintreeSettings(Document):
"ZAR",
"ZMK",
"ZWD",
]
)

def validate(self):
if not self.flags.ignore_mandatory:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def set_status(event):

def set_mandate_status(event):
mandates = []
if isinstance(event["links"], (list,)):
if isinstance(event["links"], list):
for link in event["links"]:
mandates.append(link["mandate"])
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,15 @@


class GoCardlessSettings(Document):
supported_currencies = ["EUR", "DKK", "GBP", "SEK", "AUD", "NZD", "CAD", "USD"]
supported_currencies = ("EUR", "DKK", "GBP", "SEK", "AUD", "NZD", "CAD", "USD")

def validate(self):
self.initialize_client()

def initialize_client(self):
self.environment = self.get_environment()
try:
self.client = gocardless_pro.Client(
access_token=self.access_token, environment=self.environment
)
self.client = gocardless_pro.Client(access_token=self.access_token, environment=self.environment)
return self.client
except Exception as e:
frappe.throw(e)
Expand Down Expand Up @@ -64,7 +62,6 @@ def on_payment_request_submission(self, data):
return True

def check_mandate_validity(self, data):

if frappe.db.exists("GoCardless Mandate", dict(customer=data.get("payer_name"), disabled=0)):
registered_mandate = frappe.db.get_value(
"GoCardless Mandate", dict(customer=data.get("payer_name"), disabled=0), "mandate"
Expand Down Expand Up @@ -124,9 +121,7 @@ def create_charge_on_gocardless(self):
redirect_to = self.data.get("redirect_to") or None
redirect_message = self.data.get("redirect_message") or None

reference_doc = frappe.get_doc(
self.data.get("reference_doctype"), self.data.get("reference_docname")
)
reference_doc = frappe.get_doc(self.data.get("reference_doctype"), self.data.get("reference_docname"))
self.initialize_client()

try:
Expand Down Expand Up @@ -172,7 +167,7 @@ def create_charge_on_gocardless(self):
frappe.log_error("Gocardless payment failed")
self.integration_request.db_set("error", payment.status, update_modified=False)

except Exception as e:
except Exception:
frappe.log_error("GoCardless Payment Error")

if self.flags.status_changed_to == "Completed":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,8 @@ def stk_push(
errorMessage(str): This is a predefined code that indicates the reason for request failure.
"""

time = (
str(datetime.datetime.now()).split(".")[0].replace("-", "").replace(" ", "").replace(":", "")
)
password = f"{str(business_shortcode)}{str(passcode)}{time}"
time = str(datetime.datetime.now()).split(".")[0].replace("-", "").replace(" ", "").replace(":", "")
password = f"{business_shortcode!s}{passcode!s}{time}"
encoded = base64.b64encode(bytes(password, encoding="utf8"))
payload = {
"BusinessShortCode": business_shortcode,
Expand All @@ -135,9 +133,7 @@ def stk_push(
"CallBackURL": callback_url,
"AccountReference": reference_code,
"TransactionDesc": description,
"TransactionType": "CustomerPayBillOnline"
if self.env == "sandbox"
else "CustomerBuyGoodsOnline",
"TransactionType": "CustomerPayBillOnline" if self.env == "sandbox" else "CustomerBuyGoodsOnline",
}
headers = {
"Authorization": f"Bearer {self.authentication_token}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


class MpesaSettings(Document):
supported_currencies = ["KES"]
supported_currencies = ("KES",)

def validate_transaction_currency(self, currency):
if currency not in self.supported_currencies:
Expand Down Expand Up @@ -51,7 +51,7 @@ def request_for_payment(self, **kwargs):
args = frappe._dict(kwargs)
request_amounts = self.split_request_amount_according_to_transaction_limit(args)

for i, amount in enumerate(request_amounts):
for _i, amount in enumerate(request_amounts):
args.request_amount = amount
if frappe.flags.in_test:
from payments.payment_gateways.doctype.mpesa_settings.test_mpesa_settings import (
Expand Down Expand Up @@ -104,8 +104,8 @@ def get_account_balance_info(self):
def handle_api_response(self, global_id, request_dict, response):
"""Response received from API calls returns a global identifier for each transaction, this code is returned during the callback."""
# check error response
if getattr(response, "requestId"):
req_name = getattr(response, "requestId")
if response.requestId:
req_name = response.requestId
error = response
else:
# global checkout id used as request name
Expand All @@ -116,7 +116,7 @@ def handle_api_response(self, global_id, request_dict, response):
create_request_log(request_dict, "Host", "Mpesa", req_name, error)

if error:
frappe.throw(_(getattr(response, "errorMessage")), title=_("Transaction Error"))
frappe.throw(_(response.errorMessage), title=_("Transaction Error"))


def generate_stk_push(**kwargs):
Expand Down Expand Up @@ -197,7 +197,7 @@ def verify_transaction(**kwargs):
)

total_paid = amount + sum(completed_payments)
mpesa_receipts = ", ".join(mpesa_receipts + [mpesa_receipt])
mpesa_receipts = ", ".join([*mpesa_receipts, mpesa_receipt])

if total_paid >= pr.grand_total:
pr.run_method("on_payment_authorized", "Completed")
Expand Down Expand Up @@ -318,9 +318,7 @@ def process_balance_info(**kwargs):
)
except Exception:
request.handle_failure(account_balance_response)
frappe.log_error(
title="Mpesa Account Balance Processing Error", message=account_balance_response
)
frappe.log_error(title="Mpesa Account Balance Processing Error", message=account_balance_response)
else:
request.handle_failure(account_balance_response)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,16 @@
from json import dumps

import frappe

from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_customer
from erpnext.accounts.doctype.pos_invoice.test_pos_invoice import create_pos_invoice
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
from erpnext.stock.doctype.item.test_item import make_item

from payments.payment_gateways.doctype.mpesa_settings.mpesa_settings import (
create_mode_of_payment,
process_balance_info,
verify_transaction,
)
from payments.payment_gateways.doctype.mpesa_settings.mpesa_settings import create_mode_of_payment


class TestMpesaSettings(unittest.TestCase):
Expand Down Expand Up @@ -120,9 +119,7 @@ def test_processing_of_callback_payload(self):
pluck="name",
)

callback_response = get_payment_callback_payload(
Amount=500, CheckoutRequestID=integration_req_ids[0]
)
callback_response = get_payment_callback_payload(Amount=500, CheckoutRequestID=integration_req_ids[0])
verify_transaction(**callback_response)
# test creation of integration request
integration_request = frappe.get_doc("Integration Request", integration_req_ids[0])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def on_payment_authorized(payment_status):


class PayPalSettings(Document):
supported_currencies = [
supported_currencies = (
"AUD",
"BRL",
"CAD",
Expand All @@ -105,14 +105,14 @@ class PayPalSettings(Document):
"THB",
"TRY",
"USD",
]
)

def __setup__(self):
setattr(self, "use_sandbox", 0)
self.use_sandbox = 0

def setup_sandbox_env(self, token):
data = json.loads(frappe.db.get_value("Integration Request", token, "data"))
setattr(self, "use_sandbox", cint(frappe._dict(data).use_sandbox) or 0)
self.use_sandbox = cint(frappe._dict(data).use_sandbox) or 0

def validate(self):
create_payment_gateway("PayPal")
Expand Down Expand Up @@ -171,7 +171,7 @@ def validate_paypal_credentails(self):
frappe.throw(_("Invalid payment gateway credentials"))

def get_payment_url(self, **kwargs):
setattr(self, "use_sandbox", cint(kwargs.get("use_sandbox", 0)))
self.use_sandbox = cint(kwargs.get("use_sandbox", 0))

response = self.execute_set_express_checkout(**kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


class PaytmSettings(Document):
supported_currencies = ["INR"]
supported_currencies = ("INR",)

def validate(self):
create_payment_gateway("Paytm")
Expand Down Expand Up @@ -75,7 +75,6 @@ def get_paytm_config():


def get_paytm_params(payment_details, order_id, paytm_config):

# initialize a dictionary
paytm_params = dict()

Expand Down Expand Up @@ -127,9 +126,7 @@ def verify_transaction(**paytm_params):
http_status_code=401,
indicator_color="red",
)
frappe.log_error(
"Order unsuccessful. Failed Response:" + cstr(paytm_params), "Paytm Payment Failed"
)
frappe.log_error("Order unsuccessful. Failed Response:" + cstr(paytm_params), "Paytm Payment Failed")


def verify_transaction_status(paytm_config, order_id):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def on_payment_authorized(payment_status):


class RazorpaySettings(Document):
supported_currencies = ["INR"]
supported_currencies = ("INR",)

def init_client(self):
if self.api_key:
Expand Down Expand Up @@ -251,8 +251,8 @@ def create_request(self, data):

def authorize_payment(self):
"""
An authorization is performed when users payment details are successfully authenticated by the bank.
The money is deducted from the customers account, but will not be transferred to the merchants account
An authorization is performed when user's payment details are successfully authenticated by the bank.
The money is deducted from the customer's account, but will not be transferred to the merchant's account
until it is explicitly captured by merchant.
"""
data = json.loads(self.integration_request.data)
Expand Down Expand Up @@ -306,8 +306,8 @@ def authorize_payment(self):
if custom_redirect_to:
redirect_to = custom_redirect_to

redirect_url = "payment-success?doctype={}&docname={}".format(
self.data.reference_doctype, self.data.reference_docname
redirect_url = (
f"payment-success?doctype={self.data.reference_doctype}&docname={self.data.reference_docname}"
)
else:
redirect_url = "payment-failed"
Expand Down Expand Up @@ -341,7 +341,7 @@ def cancel_subscription(self, subscription_id):
settings = self.get_settings({})

try:
resp = make_post_request(
make_post_request(
f"https://api.razorpay.com/v1/subscriptions/{subscription_id}/cancel",
auth=(settings.api_key, settings.api_secret),
)
Expand Down Expand Up @@ -393,7 +393,9 @@ def capture_payment(is_sandbox=False, sanbox_response=None):

if resp.get("status") == "authorized":
resp = make_post_request(
"https://api.razorpay.com/v1/payments/{}/capture".format(data.get("razorpay_payment_id")),
"https://api.razorpay.com/v1/payments/{}/capture".format(
data.get("razorpay_payment_id")
),
auth=(settings.api_key, settings.api_secret),
data={"amount": data.get("amount")},
)
Expand Down
Loading
Loading