Skip to content

Commit

Permalink
Merge branch 'main' into pre-commit-ci-update-config
Browse files Browse the repository at this point in the history
  • Loading branch information
jace authored May 8, 2024
2 parents c0b35c1 + 3f8cea4 commit f610822
Show file tree
Hide file tree
Showing 89 changed files with 1,142 additions and 786 deletions.
46 changes: 5 additions & 41 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,48 +1,17 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.3
hooks:
- id: ruff
args: ['--fix', '--exit-non-zero-on-fix']
# Extra args, only after removing flake8 and yesqa: '--extend-select', 'RUF100'
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.2
hooks:
- id: pyupgrade
args: ['--keep-runtime-typing', '--py311-plus']
- repo: https://github.com/asottile/yesqa
rev: v1.5.0
hooks:
- id: yesqa
additional_dependencies: &flake8deps
- bandit
- flake8-assertive
- flake8-blind-except
- flake8-bugbear
- flake8-builtins
- flake8-comprehensions
- flake8-docstrings
- flake8-isort
- flake8-logging-format
- flake8-mutable
- flake8-plugin-utils
- flake8-print
- flake8-pytest-style
- pep8-naming
- toml
- tomli
- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
additional_dependencies:
- toml
- repo: https://github.com/psf/black
rev: 24.4.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.3
hooks:
- id: black
- id: ruff
args: ['--fix', '--exit-non-zero-on-fix']
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
Expand Down Expand Up @@ -87,11 +56,6 @@ repos:
- types-requests
- types-setuptools
- typing-extensions
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
additional_dependencies: *flake8deps
- repo: https://github.com/PyCQA/pylint
rev: v3.1.0
hooks:
Expand Down
2 changes: 1 addition & 1 deletion boxoffice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
from flask_rq2 import RQ
from pytz import timezone

import coaster.app
from baseframe import Version, baseframe
from baseframe.utils import JSONProvider
from coaster.assets import WebpackManifest
from flask_lastuser import Lastuser
from flask_lastuser.sqlalchemy import UserManager
import coaster.app

from ._version import __version__

Expand Down
2 changes: 1 addition & 1 deletion boxoffice/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


@app.cli.command('dbconfig')
def dbconfig():
def dbconfig() -> None:
"""Show required database configuration."""
print( # noqa: T201
'''
Expand Down
92 changes: 48 additions & 44 deletions boxoffice/data/__init__.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,56 @@
from typing_extensions import TypedDict
from dataclasses import dataclass


class StateList(TypedDict):
@dataclass
class GstState:
name: str
short_code: int
short_code_text: str
title: str
code: int


indian_states: list[StateList] = [
{'short_code': 1, 'name': 'Jammu and Kashmir', 'short_code_text': 'JK'},
{'short_code': 2, 'name': 'Himachal Pradesh', 'short_code_text': 'HP'},
{'short_code': 3, 'name': 'Punjab', 'short_code_text': 'PB'},
{'short_code': 4, 'name': 'Chandigarh', 'short_code_text': 'CH'},
{'short_code': 5, 'name': 'Uttarakhand', 'short_code_text': 'UT'},
{'short_code': 6, 'name': 'Haryana', 'short_code_text': 'HR'},
{'short_code': 7, 'name': 'Delhi', 'short_code_text': 'DL'},
{'short_code': 8, 'name': 'Rajasthan', 'short_code_text': 'RJ'},
{'short_code': 9, 'name': 'Uttar Pradesh', 'short_code_text': 'UP'},
{'short_code': 10, 'name': 'Bihar', 'short_code_text': 'BR'},
{'short_code': 11, 'name': 'Sikkim', 'short_code_text': 'SK'},
{'short_code': 12, 'name': 'Arunachal Pradesh', 'short_code_text': 'AR'},
{'short_code': 13, 'name': 'Nagaland', 'short_code_text': 'NL'},
{'short_code': 14, 'name': 'Manipur', 'short_code_text': 'MN'},
{'short_code': 15, 'name': 'Mizoram', 'short_code_text': 'MZ'},
{'short_code': 16, 'name': 'Tripura', 'short_code_text': 'TR'},
{'short_code': 17, 'name': 'Meghalaya', 'short_code_text': 'ML'},
{'short_code': 18, 'name': 'Assam', 'short_code_text': 'AS'},
{'short_code': 19, 'name': 'West Bengal', 'short_code_text': 'WB'},
{'short_code': 20, 'name': 'Jharkhand', 'short_code_text': 'JH'},
{'short_code': 21, 'name': 'Odisha', 'short_code_text': 'OR'},
{'short_code': 22, 'name': 'Chhattisgarh', 'short_code_text': 'CT'},
{'short_code': 23, 'name': 'Madhya Pradesh', 'short_code_text': 'MP'},
{'short_code': 24, 'name': 'Gujarat', 'short_code_text': 'GJ'},
{'short_code': 25, 'name': 'Daman and Diu', 'short_code_text': 'DD'},
{'short_code': 26, 'name': 'Dadra and Nagar Haveli', 'short_code_text': 'DN'},
{'short_code': 27, 'name': 'Maharashtra', 'short_code_text': 'MH'},
{'short_code': 28, 'name': 'Andhra Pradesh (old)', 'short_code_text': 'AP'},
{'short_code': 29, 'name': 'Karnataka', 'short_code_text': 'KA'},
{'short_code': 30, 'name': 'Goa', 'short_code_text': 'GA'},
{'short_code': 31, 'name': 'Lakshadweep', 'short_code_text': 'LD'},
{'short_code': 32, 'name': 'Kerala', 'short_code_text': 'KL'},
{'short_code': 33, 'name': 'Tamil Nadu', 'short_code_text': 'TN'},
{'short_code': 34, 'name': 'Puducherry', 'short_code_text': 'PY'},
{'short_code': 35, 'name': 'Andaman and Nicobar Islands', 'short_code_text': 'AN'},
{'short_code': 36, 'name': 'Telangana', 'short_code_text': 'TG'},
{'short_code': 37, 'name': 'Andhra Pradesh', 'short_code_text': 'AD'},
indian_states: list[GstState] = [
GstState(code=1, name='JK', title='Jammu and Kashmir'),
GstState(code=2, name='HP', title='Himachal Pradesh'),
GstState(code=3, name='PB', title='Punjab'),
GstState(code=4, name='CH', title='Chandigarh'),
GstState(code=5, name='UT', title='Uttarakhand'),
GstState(code=6, name='HR', title='Haryana'),
GstState(code=7, name='DL', title='Delhi'),
GstState(code=8, name='RJ', title='Rajasthan'),
GstState(code=9, name='UP', title='Uttar Pradesh'),
GstState(code=10, name='BR', title='Bihar'),
GstState(code=11, name='SK', title='Sikkim'),
GstState(code=12, name='AR', title='Arunachal Pradesh'),
GstState(code=13, name='NL', title='Nagaland'),
GstState(code=14, name='MN', title='Manipur'),
GstState(code=15, name='MZ', title='Mizoram'),
GstState(code=16, name='TR', title='Tripura'),
GstState(code=17, name='ML', title='Meghalaya'),
GstState(code=18, name='AS', title='Assam'),
GstState(code=19, name='WB', title='West Bengal'),
GstState(code=20, name='JH', title='Jharkhand'),
GstState(code=21, name='OR', title='Odisha'),
GstState(code=22, name='CG', title='Chattisgarh'),
GstState(code=23, name='MP', title='Madhya Pradesh'),
GstState(code=24, name='GJ', title='Gujarat'),
GstState(code=25, name='DD', title='Daman and Diu (old)'),
GstState(code=26, name='DN', title='Dadra, Nagar Haveli, Daman and Diu'),
GstState(code=27, name='MH', title='Maharashtra'),
GstState(code=28, name='AP', title='Andhra Pradesh (old)'),
GstState(code=29, name='KA', title='Karnataka'),
GstState(code=30, name='GA', title='Goa'),
GstState(code=31, name='LD', title='Lakshadweep'),
GstState(code=32, name='KL', title='Kerala'),
GstState(code=33, name='TN', title='Tamil Nadu'),
GstState(code=34, name='PY', title='Puducherry'),
GstState(code=35, name='AN', title='Andaman and Nicobar Islands'),
GstState(code=36, name='TG', title='Telangana'),
GstState(code=37, name='AD', title='Andhra Pradesh'),
GstState(code=38, name='LA', title='Ladakh'),
]
indian_states.sort(key=lambda s: (s.title, s.code) if s.code < 90 else ('ZZ', s.code))

indian_states_dict = {d["short_code_text"]: d for d in indian_states}

short_codes = [state['short_code'] for state in indian_states]
indian_states_dict = {state.name: state for state in indian_states}

codes = [state.code for state in indian_states]
26 changes: 18 additions & 8 deletions boxoffice/extapi/razorpay.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from datetime import tzinfo
from decimal import Decimal
from typing import Any, TypedDict

import requests

from baseframe import localize_timezone
Expand All @@ -9,35 +13,38 @@
base_url = 'https://api.razorpay.com/v1'


def capture_payment(paymentid, amount):
class YearMonth(TypedDict):
year: int
month: int


def capture_payment(paymentid: str, amount: Decimal) -> requests.Response:
"""Attempt to capture the payment from Razorpay."""
verify_https = app.config.get('VERIFY_RAZORPAY_HTTPS', True)
url = f'{base_url}/payments/{paymentid}/capture'
# Razorpay requires the amount to be in paisa and of type integer
resp = requests.post(
return 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):
def refund_payment(paymentid: str, amount: Decimal) -> requests.Response:
"""Send a POST request to Razorpay to initiate a refund."""
url = f'{base_url}/payments/{paymentid}/refund'
# Razorpay requires the amount to be in paisa and of type integer
resp = requests.post(
return 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):
def get_settlements(date_range: YearMonth) -> Any:
url = f'{base_url}/settlements/recon/combined'
resp = requests.get(
url,
Expand All @@ -48,7 +55,9 @@ def get_settlements(date_range):
return resp.json()


def get_settled_transactions(date_range, tz=None):
def get_settled_transactions(
date_range: YearMonth, tz: str | tzinfo | None = None
) -> tuple[list[str], list]:
if not tz:
tz = app.config['TIMEZONE']
settled_transactions = get_settlements(date_range)
Expand Down Expand Up @@ -96,6 +105,7 @@ def get_settled_transactions(date_range, tz=None):
).one_or_none()
if payment:
order = payment.order
assert order.paid_at is not None # noqa: S101 # nosec B101
rows.append(
{
'settlement_id': settled_transaction['settlement_id'],
Expand Down
7 changes: 3 additions & 4 deletions boxoffice/forms/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class MenuForm(forms.Form):
__("State"),
description=__("State of supply"),
coerce=int,
default=indian_states_dict['KA']['short_code'],
default=indian_states_dict['KA'].code,
validators=[forms.validators.DataRequired(__("Please select a state"))],
)
place_supply_country_code = forms.SelectField(
Expand All @@ -39,10 +39,9 @@ class MenuForm(forms.Form):

def __post_init__(self) -> None:
self.place_supply_state_code.choices = [(0, '')] + [
(state['short_code'], state['name'])
for state in sorted(indian_states, key=lambda k: k['name'])
(state.code, state.title) for state in indian_states
]
self.place_supply_country_code.choices = [('', '')] + localized_country_list()
self.place_supply_country_code.choices = [('', ''), *localized_country_list()]

def validate_place_supply_state_code(self, field: forms.Field) -> None:
if field.data <= 0:
Expand Down
14 changes: 7 additions & 7 deletions boxoffice/forms/order.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from __future__ import annotations

from collections.abc import Callable
from typing import Any
from typing import Any, Self

from werkzeug.datastructures import ImmutableMultiDict

from baseframe import __, forms

from ..data import indian_states_dict, short_codes
from ..data import codes as gst_codes, indian_states_dict

__all__ = ['LineItemForm', 'BuyerForm', 'OrderSessionForm', 'InvoiceForm']

Expand Down Expand Up @@ -36,7 +36,7 @@ class LineItemForm(forms.Form):
)

@classmethod
def process_list(cls, line_items_json: list[Any]):
def process_list(cls, line_items_json: list[Any]) -> list[Self]:
"""
Return a list of LineItemForm objects.
Expand Down Expand Up @@ -88,18 +88,18 @@ class OrderSessionForm(forms.Form):
utm_term = forms.StringField(__("UTM Term"), filters=[trim(250)])
utm_content = forms.StringField(__("UTM Content"), filters=[trim(250)])
utm_id = forms.StringField(__("UTM Id"), filters=[trim(250)])
gclid = forms.StringField(__("Gclid"), filters=[trim(250)])
gclid = forms.StringField(__("Google Click Id"), filters=[trim(250)])
referrer = forms.StringField(__("Referrer"), filters=[trim(2083)])
host = forms.StringField(__("Host"), filters=[trim(2083)])


def validate_state_code(form, field: forms.Field) -> None:
def validate_state_code(form: InvoiceForm, field: forms.Field) -> None:
# Note: state_code is only a required field if the chosen country is India
if form.country_code.data == "IN" and field.data.upper() not in indian_states_dict:
raise forms.validators.StopValidation(__("Please select a state"))


def validate_gstin(_form, field: forms.Field) -> None:
def validate_gstin(_form: forms.Form, field: forms.Field) -> None:
"""
Raise a StopValidation exception if the supplied field's data is not a valid GSTIN.
Expand All @@ -115,7 +115,7 @@ def validate_gstin(_form, field: forms.Field) -> None:
# 15 length, first 2 digits, valid pan, checksum
if (
len(field.data) != 15
or int(field.data[:2]) not in short_codes
or int(field.data[:2]) not in gst_codes
or not field.data[2:12].isalnum()
or not field.data[-1].isalnum()
):
Expand Down
7 changes: 3 additions & 4 deletions boxoffice/forms/ticket.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class TicketForm(forms.Form):
__("State"),
description=__("State of supply"),
coerce=int,
default=indian_states_dict['KA']['short_code'],
default=indian_states_dict['KA'].code,
validators=[forms.validators.DataRequired(__("Please select a state"))],
)
place_supply_country_code = forms.SelectField(
Expand All @@ -93,10 +93,9 @@ class TicketForm(forms.Form):

def __post_init__(self) -> None:
self.place_supply_state_code.choices = [(0, '')] + [
(state['short_code'], state['name'])
for state in sorted(indian_states, key=lambda k: k['name'])
(state.code, state.title) for state in indian_states
]
self.place_supply_country_code.choices = [('', '')] + localized_country_list()
self.place_supply_country_code.choices = [('', ''), *localized_country_list()]
self.category.query = (
Category.query.join(Menu, Category.menu_id == Menu.id)
.filter(Category.menu == self.edit_parent)
Expand Down
Loading

0 comments on commit f610822

Please sign in to comment.