Skip to content

Commit

Permalink
Use f-strings, fix gettext calls, update Razorpay settlement URL (#432)
Browse files Browse the repository at this point in the history
  • Loading branch information
jace authored Feb 8, 2023
1 parent 10a7485 commit 02cb21a
Show file tree
Hide file tree
Showing 18 changed files with 76 additions and 73 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ repos:
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
rev: v1.0.0
hooks:
- id: mypy
additional_dependencies:
Expand Down
13 changes: 6 additions & 7 deletions boxoffice/extapi/razorpay.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,38 @@
def capture_payment(paymentid, amount):
"""Attempt to capture the payment from Razorpay."""
verify_https = False if app.config.get('VERIFY_RAZORPAY_HTTPS') is False else True
url = '{base_url}/payments/{paymentid}/capture'.format(
base_url=base_url, paymentid=paymentid
)
url = f'{base_url}/payments/{paymentid}/capture'
# Razorpay requires the amount to be in paisa and of type integer
resp = requests.post(
url,
data={'amount': int(amount * 100)},
auth=(app.config['RAZORPAY_KEY_ID'], app.config['RAZORPAY_KEY_SECRET']),
verify=verify_https,
timeout=30,
)
return resp


def refund_payment(paymentid, amount):
"""Send a POST request to Razorpay to initiate a refund."""
url = '{base_url}/payments/{paymentid}/refund'.format(
base_url=base_url, paymentid=paymentid
)
url = f'{base_url}/payments/{paymentid}/refund'
# Razorpay requires the amount to be in paisa and of type integer
resp = requests.post(
url,
data={'amount': int(amount * 100)},
auth=(app.config['RAZORPAY_KEY_ID'], app.config['RAZORPAY_KEY_SECRET']),
timeout=30,
)
return resp


def get_settlements(date_range):
url = '{base_url}/settlements/report/combined'.format(base_url=base_url)
url = f'{base_url}/settlements/recon/combined'
resp = requests.get(
url,
params={'year': date_range['year'], 'month': date_range['month']},
auth=(app.config['RAZORPAY_KEY_ID'], app.config['RAZORPAY_KEY_SECRET']),
timeout=30,
)
return resp.json()

Expand Down
13 changes: 6 additions & 7 deletions boxoffice/forms/order_refund.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from baseframe import __
from baseframe import _, __
from baseframe.forms.validators import StopValidation
import baseframe.forms as forms

Expand Down Expand Up @@ -45,12 +45,11 @@ def validate_amount(self, field):
requested_refund_amount = field.data
order = self.edit_parent
if not order.paid_amount:
raise StopValidation(__("Refunds can only be issued for paid orders"))
raise StopValidation(_("Refunds can only be issued for paid orders"))
if (order.refunded_amount + requested_refund_amount) > order.paid_amount:
raise StopValidation(
__(
"Invalid refund amount! Must be lesser than {amount}, the net amount paid for the order".format(
amount=order.net_amount
)
)
_(
"Invalid refund amount! Must be lesser than {amount}, the net"
" amount paid for the order"
).format(amount=order.net_amount)
)
12 changes: 6 additions & 6 deletions boxoffice/mailclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from html2text import html2text
from premailer import transform as email_transform

from baseframe import __
from baseframe import _

from . import app, mail, rq
from .models import CURRENCY_SYMBOL, LINE_ITEM_STATUS, Assignee, LineItem, Order
Expand Down Expand Up @@ -111,11 +111,11 @@ def send_line_item_cancellation_mail(
def send_order_refund_mail(order_id, refund_amount, note_to_user):
with app.test_request_context():
order = Order.query.get(order_id)
subject = __(
"{item_collection_title}: Refund for receipt no. {invoice_no}".format(
item_collection_title=order.item_collection.title,
invoice_no=order.invoice_no,
)
subject = _(
"{item_collection_title}: Refund for receipt no. {invoice_no}"
).format(
item_collection_title=order.item_collection.title,
invoice_no=order.invoice_no,
)
msg = Message(
subject=subject,
Expand Down
16 changes: 7 additions & 9 deletions boxoffice/models/discount_policy.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import secrets
import string

from sqlalchemy import DDL, event
from sqlalchemy.orm.exc import MultipleResultsFound
import sqlalchemy as sa

from itsdangerous import BadSignature, Signer
from werkzeug.utils import cached_property
Expand All @@ -22,7 +22,7 @@ class DISCOUNT_TYPE(LabeledEnum): # NOQA: N801
COUPON = (1, __("Coupon"))


item_discount_policy = db.Table(
item_discount_policy = sa.Table(
'item_discount_policy',
db.Model.metadata,
db.Column('item_id', None, db.ForeignKey('item.id'), primary_key=True),
Expand Down Expand Up @@ -139,9 +139,7 @@ def gen_signed_code(self, identifier=None):
if not identifier:
identifier = buid()
signer = Signer(self.secret)
key = "{base}.{identifier}".format(
base=self.discount_code_base, identifier=identifier
)
key = f'{self.discount_code_base}.{identifier}'
return signer.sign(key).decode('utf-8')

@staticmethod
Expand Down Expand Up @@ -265,8 +263,8 @@ def is_valid_access_coupon(cls, item, code_list):
return False


@event.listens_for(DiscountPolicy, 'before_update')
@event.listens_for(DiscountPolicy, 'before_insert')
@sa.event.listens_for(DiscountPolicy, 'before_update')
@sa.event.listens_for(DiscountPolicy, 'before_insert')
def validate_price_based_discount(mapper, connection, target):
if target.is_price_based and len(target.items) > 1:
raise ValueError("Price-based discounts MUST have only one associated item")
Expand Down Expand Up @@ -318,13 +316,13 @@ def update_used_count(self):
)


create_title_trgm_trigger = DDL(
create_title_trgm_trigger = sa.DDL(
'''
CREATE INDEX idx_discount_policy_title_trgm on discount_policy USING gin (title gin_trgm_ops);
'''
)

event.listen(
sa.event.listen(
DiscountPolicy.__table__,
'after_create',
create_title_trgm_trigger.execute_if(dialect='postgresql'),
Expand Down
11 changes: 5 additions & 6 deletions boxoffice/models/invoice.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from sqlalchemy.orm import validates
from sqlalchemy.sql import func, select
import sqlalchemy as sa

from baseframe import __
from baseframe import _, __
from coaster.utils import LabeledEnum, utcnow

from . import BaseMixin, UuidMixin, db
Expand All @@ -20,7 +19,7 @@ def gen_invoice_no(organization, jurisdiction, invoice_dt):
"""Generate a sequential invoice number for the organization and financial year."""
fy_start_at, fy_end_at = get_fiscal_year(jurisdiction, invoice_dt)
return (
select(func.coalesce(func.max(Invoice.invoice_no + 1), 1))
sa.select(sa.func.coalesce(sa.func.max(Invoice.invoice_no + 1), 1))
.where(Invoice.organization == organization)
.where(Invoice.invoiced_at >= fy_start_at)
.where(Invoice.invoiced_at < fy_end_at)
Expand Down Expand Up @@ -119,7 +118,7 @@ def __init__(self, *args, **kwargs):
def is_final(self):
return self.status == INVOICE_STATUS.FINAL

@validates(
@sa.orm.validates(
'invoicee_name',
'invoicee_company',
'invoicee_email',
Expand All @@ -140,7 +139,7 @@ def is_final(self):
def validate_immutable_final_invoice(self, key, val):
if self.status == INVOICE_STATUS.FINAL:
raise ValueError(
"`{attr}` cannot be modified in a finalized invoice".format(attr=key)
_("`{attr}` cannot be modified in a finalized invoice").format(attr=key)
)
return val

Expand Down
2 changes: 1 addition & 1 deletion boxoffice/models/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Item(BaseScopedNameMixin, db.Model):

discount_policies = db.relationship(
'DiscountPolicy',
secondary=item_discount_policy,
secondary=item_discount_policy, # type: ignore[has-type]
backref='items',
lazy='dynamic',
)
Expand Down
4 changes: 2 additions & 2 deletions boxoffice/views/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ def org_revenue(organization):
result = list(
calculate_weekly_refunds(item_collection_ids, user_timezone, year).items()
)
doc = _("Refunds per week for {year}".format(year=year))
doc = _("Refunds per week for {year}").format(year=year)
else:
# sales includes confirmed and cancelled line items
result = list(
calculate_weekly_sales(item_collection_ids, user_timezone, year).items()
)
doc = _("Revenue per week for {year}".format(year=year))
doc = _("Revenue per week for {year}").format(year=year)
return api_success(result=result, doc=doc, status_code=200)
7 changes: 3 additions & 4 deletions boxoffice/views/admin_discount.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ def jsonify_discount_policy(discount_policy):
details['dp_items'] = [
{
'id': str(item.id),
'title': "{ic_title}: {title}".format(
ic_title=item.item_collection.title, title=item.title
),
'title': f'{item.item_collection.title}: {item.title}',
}
for item in discount_policy.items
]
Expand Down Expand Up @@ -63,8 +61,9 @@ def admin_discount_policies(organization, search=None, page=1, size=None):

discount_policies = organization.discount_policies
if search:
# FIXME: quote search for LIKE format characters, and don't use LIKE at all
discount_policies = discount_policies.filter(
DiscountPolicy.title.ilike('%{query}%'.format(query=search))
DiscountPolicy.title.ilike(f'%{search}%')
)
paginated_discount_policies = discount_policies.paginate(
page=page, per_page=results_per_page
Expand Down
15 changes: 6 additions & 9 deletions boxoffice/views/admin_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ def items(organization, search=None):
.filter(
ItemCollection.organization == organization,
db.or_(
Item.title.ilike('%{query}%'.format(query=search)),
ItemCollection.title.ilike('%{query}%'.format(query=search)),
# FIXME: quote search for LIKE markup
Item.title.ilike(f'%{search}%'),
ItemCollection.title.ilike(f'%{search}%'),
),
)
.join(Item.item_collection)
Expand All @@ -41,9 +42,7 @@ def items(organization, search=None):
'items': [
{
'id': str(item_tuple[0].id),
'title': "{ic_title}: {title}".format(
ic_title=item_tuple[1].title, title=item_tuple[0].title
),
'title': f'{item_tuple[1].title}: {item_tuple[0].title}',
}
for item_tuple in filtered_items
]
Expand Down Expand Up @@ -198,9 +197,7 @@ def jsonify_new_price(data_dict):
if price_form.validate_on_submit():
price = Price(item=item)
price_form.populate_obj(price)
price.title = "{item_name}-price-{datetime}".format(
item_name=item.name, datetime=json_date_format(utcnow())
)
price.title = f'{item.name}-price-{json_date_format(utcnow())}'
if not price.name:
price.make_name()
db.session.add(price)
Expand Down Expand Up @@ -239,7 +236,7 @@ def jsonify_edit_price(data_dict):
db.session.commit()
return api_success(
result={'price': dict(price.current_access())},
doc=_("Update price {title}.".format(title=price.title)),
doc=_("Update price {title}.").format(title=price.title),
status_code=200,
)
return api_error(
Expand Down
4 changes: 2 additions & 2 deletions boxoffice/views/admin_item_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ def jsonify_edit_item_collection(item_collection_dict):
db.session.commit()
return api_success(
result={'item_collection': dict(item_collection.current_access())},
doc=_(
"Edited item collection {title}.".format(title=item_collection.title)
doc=_("Edited item collection {title}.").format(
title=item_collection.title
),
status_code=200,
)
Expand Down
5 changes: 2 additions & 3 deletions boxoffice/views/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ def lastuser_error(error, error_description=None, error_uri=None):
return render_message(
title=_("Error: {error}").format(error=error),
message=Markup(
"<p>{desc}</p><p>URI: {uri}</p>".format(
desc=escape(error_description or ''), uri=escape(error_uri or _('NA'))
)
f'<p>{escape(error_description or "")}</p>'
f'<p>URI: {escape(error_uri or _("NA"))}</p>'
),
)
33 changes: 21 additions & 12 deletions boxoffice/views/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,8 @@ def order(item_collection):
)

invalid_quantity_error_msg = _(
'Selected quantity for ‘{item}’ is not available. Please edit the order and update the quantity'
"Selected quantity for ‘{item}’ is not available. Please edit the order and"
" update the quantity"
)
item_dicts = Item.get_availability(
[line_item_form.data.get('item_id') for line_item_form in line_item_forms]
Expand Down Expand Up @@ -359,9 +360,9 @@ def free(order):
db.session.commit()
send_receipt_mail.queue(
order.id,
subject="{item_collection_title}: Your registration is confirmed!".format(
item_collection_title=order.item_collection.title
),
subject=_(
"{item_collection_title}: Your registration is confirmed!"
).format(item_collection_title=order.item_collection.title),
template='free_order_confirmation_mail.html.jinja2',
)
return api_success(
Expand Down Expand Up @@ -430,7 +431,9 @@ def payment(order):
db.session.commit()
send_receipt_mail.queue(
order.id,
subject="{item_collection_title}: Thank you for your order (#{invoice_no})!".format(
subject=_(
"{item_collection_title}: Thank you for your order (#{invoice_no})!"
).format(
item_collection_title=order.item_collection.title,
invoice_no=order.invoice_no,
),
Expand All @@ -445,11 +448,11 @@ def payment(order):
db.session.add(online_payment)
db.session.commit()
raise PaymentGatewayError(
"Online payment failed for order - {order} with the following details - {msg}".format(
_("Online payment failed for order #{order}: {msg}").format(
order=order.id, msg=rp_resp.content
),
424,
"Your payment failed. Please try again or contact us at {email}.".format(
_("Your payment failed. Try again, or contact us at {email}.").format(
email=order.organization.contact_email
),
)
Expand Down Expand Up @@ -745,18 +748,21 @@ def process_line_item_cancellation(line_item):
amount=refund_amount,
currency=CURRENCY.INR,
refunded_at=func.utcnow(),
refund_description="Refund: {line_item_title}".format(
refund_description=_("Refund: {line_item_title}").format(
line_item_title=line_item.item.title
),
)
)
else:
raise PaymentGatewayError(
"Cancellation failed for order - {order} with the following details - {msg}".format(
_("Cancellation failed for order #{order}: {msg}").format(
order=order.id, msg=rp_refund['error']['description']
),
424,
"Refund failed. {reason}. Please try again or write to us at {email}.".format(
_(
"Refund failed with “{reason}”. Try again, or write to us at"
" {email}."
).format(
reason=rp_refund['error']['description'],
email=line_item.order.organization.contact_email,
),
Expand Down Expand Up @@ -828,11 +834,14 @@ def process_partial_refund_for_order(data_dict):
)
else:
raise PaymentGatewayError(
"Refund failed for order - {order} with the following details - {msg}".format(
_("Refund failed for order #{order}: {msg}").format(
order=order.id, msg=rp_refund['error']['description']
),
424,
"Refund failed. {reason}. Please try again or contact support at {email}.".format(
_(
"Refund failed with “{reason}̦”. Try again, or contact support at"
" {email}."
).format(
reason=rp_refund['error']['description'],
email=order.organization.contact_email,
),
Expand Down
Loading

0 comments on commit 02cb21a

Please sign in to comment.