Skip to content

Commit

Permalink
chore: add some easy type annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Feb 5, 2025
1 parent d166f10 commit 00fbc4d
Show file tree
Hide file tree
Showing 41 changed files with 208 additions and 208 deletions.
4 changes: 2 additions & 2 deletions scripts/list-translated-languages
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ URL = "https://hosted.weblate.org/exports/stats/weblate/website/"
THRESHOLD = 60


def print_language(lang, fmt="{0} ({1})"):
def print_language(lang, fmt="{0} ({1})") -> None:
"""Print language code with its name."""
locale = Locale(lang)
print(fmt.format(lang, locale.getDisplayName(locale).capitalize()))


def main():
def main() -> None:
# load data
handle = urlopen(URL, timeout=5) # noqa: S310
data = handle.read()
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class PostAdmin(admin.ModelAdmin):
ordering = ("-timestamp",)
date_hierarchy = "timestamp"

def save_model(self, request, obj, form, change):
def save_model(self, request, obj, form, change) -> None:
if getattr(obj, "author", None) is None:
obj.author = request.user
obj.save()
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from django.utils.translation import gettext as _


def discover():
def discover() -> None:
_(
"The largest Weblate server worldwide is home to hundreds of libre and "
"private projects. And Weblate itself! Love libre software? Your "
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class MethodForm(forms.Form):
required=True,
)

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.fields["method"].choices = [ # type: ignore[attr-defined]
(backend.name, backend.verbose) for backend in list_backends()
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/hetzner.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def get_directory_summary(

def create_storage_folder(
dirname: str, service: Service, customer: Customer, last_report: Report
):
) -> None:
# Create folder and SSH key
with sftp_client() as ftp:
ftp.mkdir(dirname)
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/invoices/management/commands/invoices_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def add_arguments(self, parser) -> None:
help="Refresh individual XML files",
)

def handle(self, refresh: bool, **kwargs):
def handle(self, refresh: bool, **kwargs) -> None:
if settings.INVOICES_COPY_PATH is None:
raise CommandError("Invoices output path is not configured!")
previous_month = now() - timedelta(days=28)
Expand Down
10 changes: 5 additions & 5 deletions weblate_web/invoices/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def __init__( # noqa: PLR0913
bic: str,
holder: str = "Weblate s.r.o.",
short_list: tuple[InfoType, ...],
):
) -> None:
self._number = number
self._bank = bank
self._iban = iban
Expand Down Expand Up @@ -332,7 +332,7 @@ def save( # type: ignore[override]
force_update: bool = False,
using=None,
update_fields=None,
):
) -> None:
extra_fields: list[str] = []
if not self.due_date:
self.due_date = self.issue_date + datetime.timedelta(
Expand Down Expand Up @@ -522,7 +522,7 @@ def add_element(root, name: str, text: str | Decimal | int | None = None):
added.text = str(text)
return added

def add_amounts(root, in_czk: bool = False):
def add_amounts(root, in_czk: bool = False) -> None:
dph = add_element(root, "SouhrnDPH")
if in_czk:
castka_zaklad = self.total_amount_no_vat_czk
Expand Down Expand Up @@ -789,7 +789,7 @@ def save( # type: ignore[override]
force_update: bool = False,
using=None,
update_fields=None,
):
) -> None:
from weblate_web.models import get_period_delta # noqa: PLC0415

extra_fields: list[str] = []
Expand Down Expand Up @@ -844,7 +844,7 @@ def get_date_range_display(self) -> str:
return f"{date_format(self.start_date)} - {date_format(self.end_date)}"
return ""

def clean(self):
def clean(self) -> None:
if not self.description and not self.package:
raise ValidationError(
{"description": "Description needs to be provided if not using package"}
Expand Down
24 changes: 12 additions & 12 deletions weblate_web/invoices/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,25 +108,25 @@ def validate_invoice(self, invoice: Invoice) -> None:
xml_doc = etree.parse(invoice.xml_path) # noqa: S320
S3_SCHEMA.assertValid(xml_doc)

def test_total(self):
def test_total(self) -> None:
invoice = self.create_invoice(vat="CZ8003280318")
self.assertEqual(invoice.total_amount, 100)
self.validate_invoice(invoice)

def test_total_vat(self):
def test_total_vat(self) -> None:
invoice = self.create_invoice(vat_rate=21, customer_reference="PO123456")
self.assertEqual(invoice.total_amount, 121)
self.validate_invoice(invoice)

def test_total_items(self):
def test_total_items(self) -> None:
invoice = self.create_invoice()
invoice.invoiceitem_set.create(
description="Other item", unit_price=1000, quantity=4
)
self.assertEqual(invoice.total_amount, 4100)
self.validate_invoice(invoice)

def test_total_items_hours(self):
def test_total_items_hours(self) -> None:
invoice = self.create_invoice()
invoice.invoiceitem_set.create(
description="Other item",
Expand All @@ -137,7 +137,7 @@ def test_total_items_hours(self):
self.assertEqual(invoice.total_amount, 4100)
self.validate_invoice(invoice)

def test_total_items_hour(self):
def test_total_items_hour(self) -> None:
invoice = self.create_invoice()
invoice.invoiceitem_set.create(
description="Other item",
Expand All @@ -148,49 +148,49 @@ def test_total_items_hour(self):
self.assertEqual(invoice.total_amount, 1100)
self.validate_invoice(invoice)

def test_discount(self):
def test_discount(self) -> None:
invoice = self.create_invoice(
discount=Discount.objects.create(description="Test discount", percents=50)
)
self.assertEqual(invoice.total_amount, 50)
self.validate_invoice(invoice)

def test_discount_negative(self):
def test_discount_negative(self) -> None:
invoice = self.create_invoice(
discount=Discount.objects.create(description="Test discount", percents=50)
)
invoice.invoiceitem_set.create(description="Prepaid amount", unit_price=-10)
self.assertEqual(invoice.total_amount, 40)
self.validate_invoice(invoice)

def test_discount_vat(self):
def test_discount_vat(self) -> None:
invoice = self.create_invoice(
discount=Discount.objects.create(description="Test discount", percents=50),
vat_rate=21,
)
self.assertEqual(invoice.total_amount, Decimal("60.50"))
self.validate_invoice(invoice)

def test_package(self):
def test_package(self) -> None:
invoice = self.create_invoice_package()
self.assertEqual(invoice.total_amount, Decimal(100))
self.validate_invoice(invoice)

def test_package_usd(self):
def test_package_usd(self) -> None:
invoice = self.create_invoice_package(currency=Currency.USD)
self.assertEqual(
invoice.total_amount,
round(Decimal(100) * invoice.exchange_rate_eur * Decimal("1.05"), 0),
)
self.validate_invoice(invoice)

def test_invoice_kinds(self):
def test_invoice_kinds(self) -> None:
for kind in InvoiceKind.values:
invoice = self.create_invoice(kind=InvoiceKind(kind))
self.validate_invoice(invoice)

@override_settings(PAYMENT_DEBUG=True)
def test_pay_link(self):
def test_pay_link(self) -> None:
invoice = self.create_invoice_package()
self.validate_invoice(invoice)
url = cast("str", invoice.get_payment_url())
Expand Down
4 changes: 2 additions & 2 deletions weblate_web/legal/management/commands/generate_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Command(BaseCommand):
help = "generates legal document"
client = None

def add_arguments(self, parser):
def add_arguments(self, parser) -> None:
parser.add_argument(
"document",
type=Path,
Expand All @@ -50,7 +50,7 @@ def add_arguments(self, parser):
help="Output PDF file",
)

def handle(self, document: Path, params: Path, output: Path, **kwargs):
def handle(self, document: Path, params: Path, output: Path, **kwargs) -> None:
yaml = YAML()
configuration = yaml.load(document)
template = document.with_suffix(".html")
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/legal/management/commands/generate_terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def add_arguments(self, parser) -> None:
help="Output directory",
)

def handle(self, output: Path, *args, **options):
def handle(self, output: Path, *args, **options) -> None:
render_pdf(
html=render_to_string(
"pdf/terms.html",
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/legal/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def save( # type: ignore[override]
force_update: bool = False,
using=None,
update_fields=None,
):
) -> None:
super().save(
force_insert=force_insert,
force_update=force_update,
Expand Down
4 changes: 2 additions & 2 deletions weblate_web/legal/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ def create_customer(self, *, vat: str = "") -> Customer:
vat=vat,
)

def test_agreement(self):
def test_agreement(self) -> None:
agreement = Agreement.objects.create(
customer=self.create_customer(), kind=AgreementKind.DPA
)
self.assertTrue(agreement.path.exists())
self.assertIn("DPA", str(agreement))

def test_generate_terms(self):
def test_generate_terms(self) -> None:
tempdir = mkdtemp()
try:
call_command("generate_terms", output=Path(tempdir))
Expand Down
4 changes: 2 additions & 2 deletions weblate_web/management/commands/background_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@
class Command(BaseCommand):
help = "refreshes remote data"

def disable_stale_services(self):
def disable_stale_services(self) -> None:
threshold = timezone.now() - timedelta(days=3)
for service in Service.objects.filter(discoverable=True):
if service.last_report and service.last_report.timestamp < threshold:
service.discoverable = False
service.save(update_fields=["discoverable"])
self.stdout.write(f"Disabling disoverable for {service}")

def handle(self, *args, **options):
def handle(self, *args, **options) -> None:
self.disable_stale_services()
get_contributors(force=True)
get_activity(force=True)
Expand Down
4 changes: 2 additions & 2 deletions weblate_web/management/commands/background_vat.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@
class Command(BaseCommand):
help = "refreshes VAT caches"

def add_arguments(self, parser):
def add_arguments(self, parser) -> None:
parser.add_argument(
"--all",
default=False,
action="store_true",
help="Fetch all VAT caches",
)

def handle(self, *args, **options):
def handle(self, *args, **options) -> None:
fetch_vat_info(fetch_all=options["all"])
2 changes: 1 addition & 1 deletion weblate_web/management/commands/backups_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def check_unpaid(self, backup_services: dict[str, Service]) -> None:
self.stderr.write(f" size: {service.backup_size}")
self.stderr.write(f" mtime: {service.backup_timestamp}")

def handle(self, delete: bool, skip_scan: bool, **kwargs):
def handle(self, delete: bool, skip_scan: bool, **kwargs) -> None:
backup_services: dict[str, Service] = {
service.backup_repository: service
for service in Service.objects.exclude(backup_repository="")
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/management/commands/cleanup_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def add_arguments(self, parser) -> None:
help="Delete stale services",
)

def handle(self, delete: bool, **kwargs):
def handle(self, delete: bool, **kwargs) -> None:
# Remove services without subscription and report older than 30 days
for service in Service.objects.filter(
subscription__isnull=True,
Expand Down
2 changes: 1 addition & 1 deletion weblate_web/management/commands/list_contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
class Command(BaseCommand):
help = "lists contacts"

def handle(self, *args, **options):
def handle(self, *args, **options) -> None:
emails = set()
for service in Service.objects.filter(
status__in={"hosted", "shared", "basic", "extended", "premium"}
Expand Down
8 changes: 4 additions & 4 deletions weblate_web/management/commands/process_payments.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,22 @@
class Command(BaseCommand):
help = "processes pending payments"

def add_arguments(self, parser):
def add_arguments(self, parser) -> None:
parser.add_argument(
"--from-date",
default=None,
help="Date for parsing bank statements",
)

def handle(self, *args, **options):
def handle(self, *args, **options) -> None:
if settings.FIO_TOKEN:
with transaction.atomic():
FioBank.fetch_payments(from_date=options["from_date"])
with transaction.atomic():
self.pending()
self.active()

def pending(self):
def pending(self) -> None:
# Process pending ones
payments = Payment.objects.filter(state=Payment.ACCEPTED).select_for_update()
for payment in payments:
Expand All @@ -58,7 +58,7 @@ def pending(self):
self.stderr.write(f"Could not process payment: {payment}")

@staticmethod
def active():
def active() -> None:
# Adjust active flag
Donation.objects.filter(active=True, expires__lt=timezone.now()).update(
active=False
Expand Down
Loading

0 comments on commit 00fbc4d

Please sign in to comment.