From db1cb5babeb8cb863a11bae2c5b43ee550c2225e Mon Sep 17 00:00:00 2001 From: Trullemans Gregory Date: Sat, 22 Feb 2020 11:08:26 +0100 Subject: [PATCH] Improving code lisibility. --- .pre-commit-config.yaml | 16 +++++ src/billing/views.py | 32 +++++----- src/comptaClub/settings.py | 8 +-- src/comptabilite/forms.py | 2 +- src/comptabilite/models.py | 4 ++ src/comptabilite/tools.py | 120 +++++++++++++++++++++++-------------- src/comptabilite/urls.py | 12 +++- src/comptabilite/utils.py | 1 + src/comptabilite/views.py | 102 ++++++++++++++++++++----------- 9 files changed, 196 insertions(+), 101 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..d63ded9 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,16 @@ +default_language_version: + python: python3.7 +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.3.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.5.0 + hooks: + - id: flake8 +- repo: https://github.com/psf/black + rev: 19.10b0 + hooks: + - id: black \ No newline at end of file diff --git a/src/billing/views.py b/src/billing/views.py index 37e899a..98af197 100644 --- a/src/billing/views.py +++ b/src/billing/views.py @@ -23,22 +23,23 @@ from .models import ( def contract_listing(request): - """ - Renvoie la liste de tous les contrats. - """ + """ Récupère la liste de tous les contrats. """ contract_list = Contract.objects.all() context = {"contract_list": contract_list} return render(request, "contract_listing.html", context) -def contract_detail(request, contractid): +def contract_detail(request, contract_id): """ - Renvoie toutes les informations relatives à un contrat, en ce y compris les prestations - relatives à celui-ci. + Récupère toutes les informations relatives à un contrat et les prestations relatives à + celui-ci. + + Args: + contract_id (int): identifiant d'un contract """ - contract = Contract.objects.get(pk=contractid) + contract = Contract.objects.get(pk=contract_id) prestation_list = contract.get_prestation.all() prestation_count = prestation_list.count() total = list(contract.get_prestation.all().aggregate(Sum("total_amount")).values())[ @@ -54,18 +55,14 @@ def contract_detail(request, contractid): def client_listing(request): - """ - Renvoie la liste de tous les clients. - """ + """ Récupère la liste de tous les clients. """ client_list = Client.objects.all() context = {"client_list": client_list} return render(request, "client_listing.html", context) def prestation_listing(request): - """ - Renvoie la liste de toutes les prestations. - """ + """ Récupère la liste de toutes les prestations. """ prestation_list = Prestation.objects.all() context = {"prestation_list": prestation_list} return render(request, "prestation_listing.html", context) @@ -345,16 +342,19 @@ class MyDocument(object): self.drawNewLine(INDENTED_X, "Facture payable au comptant.") self.drawNewLine( INDENTED_X, - "En cas de défaut de paiement à l'échéance, il est dû de plein droit et sans mise en demeure, un interêt fixé au taux de", + """En cas de défaut de paiement à l'échéance, il est dû de plein droit et sans mise en + demeure, un interêt fixé au taux de""", ) self.drawNewLine(INDENTED_X, "15% l'an.") self.drawNewLine( INDENTED_X, - "Tout réclamation, pour être admise, doit être faite dans les huit jours de la réception de la facture.", + """Tout réclamation, pour être admise, doit être faite dans les huit jours de la + réception de la facture.""", ) self.drawNewLine( INDENTED_X, - "En cas de litige concernant la présente facture, seuls les tribunaux de MONS seront compétents.", + """En cas de litige concernant la présente facture, seuls les tribunaux de MONS seront + compétents.""", ) def download(self): diff --git a/src/comptaClub/settings.py b/src/comptaClub/settings.py index a44ce23..11e0210 100644 --- a/src/comptaClub/settings.py +++ b/src/comptaClub/settings.py @@ -46,7 +46,7 @@ ROOT_URLCONF = "comptaClub.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", - "DIRS": [os.path.join(BASE_DIR, "templates"),], + "DIRS": [os.path.join(BASE_DIR, "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ @@ -81,9 +81,9 @@ AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, - {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",}, - {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",}, - {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",}, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] diff --git a/src/comptabilite/forms.py b/src/comptabilite/forms.py index 9da925f..525d840 100644 --- a/src/comptabilite/forms.py +++ b/src/comptabilite/forms.py @@ -256,7 +256,7 @@ def update_transaction_dict(current_dict): """ Par défaut on considère que le montant est positif et est donc une recette. Il faut donc corriger, si nécessaire, le type de transaction et d'autres informations. - id "Autre dépense" = 4 + id "Autre dépense" = 4 id "Autre recette" = 5 Args: diff --git a/src/comptabilite/models.py b/src/comptabilite/models.py index 6a47c09..0e1c6dc 100644 --- a/src/comptabilite/models.py +++ b/src/comptabilite/models.py @@ -63,6 +63,7 @@ class Annuality(models.Model): class ComptabilityManager(models.Manager): """ """ + def by_year(self, year): return super().get_queryset().filter(registrationDate__year=year) @@ -72,6 +73,7 @@ class Comptability(models.Model): Classe représentant les champs communs aux lignes de comptabilité, aux droits en engagements, … etc. """ + objects = ComptabilityManager() class Meta: @@ -185,12 +187,14 @@ class TransactionType(models.Model): class TransactionManager(ComptabilityManager): """ """ + def by_type(self, transaction_type): return super().get_queryset().filter(transaction_type=transaction_type) class Transaction(Comptability): """ Classe représentant un mouvement d'argent. """ + objects = TransactionManager() class Meta: diff --git a/src/comptabilite/tools.py b/src/comptabilite/tools.py index abc11a5..fab4baf 100644 --- a/src/comptabilite/tools.py +++ b/src/comptabilite/tools.py @@ -18,7 +18,7 @@ def get_transactions_and_sums_for_year_and_type(accounting_year, transaction_typ Récupère les transactions associées à une année et un type et additionne les valeurs obtenues. Args: - accounting_year (int): année + accounting_year (int): année comptable transaction_type_id (int): type de transaction Returns: @@ -46,13 +46,13 @@ def get_transactions_and_sums_for_year_and_type(accounting_year, transaction_typ } -def get_transactions_totalamount_sum_value(accounting_year, transaction_type): +def get_transactions_totalamount_sum_value_for_type(accounting_year, transaction_type): """ Récupère les transactions associées à une année et un type et additionne le montant total des records obtenus. Args: - accounting_year (int): année + accounting_year (int): année comptable transaction_type (id): type de transaction Returns: @@ -60,8 +60,35 @@ def get_transactions_totalamount_sum_value(accounting_year, transaction_type): """ return zero_or_value( list( - Transaction.objects.by_year(accounting_year).filter( - transaction_type=transaction_type, + Transaction.objects.by_year(accounting_year) + .filter( + transaction_type=transaction_type, is_simulated=False, is_done=True, + ) + .aggregate(Sum("totalAmount")) + .values() + )[0] + ) + + +def get_transactions_totalamount_sum_value_for_parenttype( + accounting_year, transaction_type +): + """ + Récupère les transactions associées à une année et un type et additionne le montant total des + records obtenus. + + Args: + accounting_year (int): année comptable + transaction_type (id): type de transaction + + Returns: + (int): somme totale + """ + return zero_or_value( + list( + Transaction.objects.by_year(accounting_year) + .filter( + transaction_type__parent=transaction_type, is_simulated=False, is_done=True, ) @@ -71,15 +98,17 @@ def get_transactions_totalamount_sum_value(accounting_year, transaction_type): ) -def get_transactiontypes_and_total_amount_transactions(accounting_year, transactiontype_id): +def get_transactiontypes_and_total_amount_transactions( + accounting_year, transactiontype_id +): """ Récupère tous les types de transactions qui existent pour, pour chacun d'eux récupère toutes les transactions qui sont `effectuées` et non `simulées` et va additionner les montants totaux par type de transaction. Args: - accounting_year (int): année - transaction_type_id (int): type de transaction + accounting_year (int): année comptable + transactiontype_id (int): type de transaction Returns: (dict): ensemble des types de transaction et somme totale @@ -95,7 +124,9 @@ def get_transactiontypes_and_total_amount_transactions(accounting_year, transact for transaction_type in transactiontypes_list: j = 0 - sum_value = get_transactions_totalamount_sum_value(accounting_year, transaction_type) + sum_value = get_transactions_totalamount_sum_value_for_type( + accounting_year, transaction_type + ) transactiontypes_info_list.append( { "label": transaction_type.label, @@ -111,7 +142,9 @@ def get_transactiontypes_and_total_amount_transactions(accounting_year, transact ).order_by("order") for subtype in transactiontype_subtype: - subtype_sum_value = get_transactions_totalamount_sum_value(accounting_year, subtype) + subtype_sum_value = get_transactions_totalamount_sum_value_for_type( + accounting_year, subtype + ) transactiontypes_info_list.append( { @@ -123,13 +156,20 @@ def get_transactiontypes_and_total_amount_transactions(accounting_year, transact } ) - transactiontypes_info_list[i]["total_transactiontypes_value"] += subtype_sum_value + transactiontypes_info_list[i][ + "total_transactiontypes_value" + ] += subtype_sum_value j += 1 - total_transactiontypes_value += transactiontypes_info_list[i]["total_transactiontypes_value"] + total_transactiontypes_value += transactiontypes_info_list[i][ + "total_transactiontypes_value" + ] i += j + 1 - return {"transactiontypes_info_list": transactiontypes_info_list, "total": total_transactiontypes_value} + return { + "transactiontypes_info_list": transactiontypes_info_list, + "total": total_transactiontypes_value, + } def get_transactiontype_and_sum_for_spf_export(accounting_year, transaction_type_id): @@ -140,49 +180,39 @@ def get_transactiontype_and_sum_for_spf_export(accounting_year, transaction_type du type de transaction. Args: - accounting_year (int): année + accounting_year (int): année comptable transaction_type_id (int): type de transaction Returns: (dict): ensemble des types de transaction et somme totale """ + sum_total_transaction = 0 transaction_type_info = [] transaction_type_list = TransactionType.objects.filter( transaction_type=transaction_type_id, parent=None ).order_by("order") for transaction_type in transaction_type_list: - # Somme du père - sum_value = get_transactions_totalamount_sum_value(accounting_year, transaction_type) - - # Selection des fils - sum_value += zero_or_value( - list( - Transaction.objects.by_year(accounting_year).filter( - transaction_type__parent=transaction_type, - is_simulated=False, - is_done=True, - ) - .aggregate(Sum("totalAmount")) - .values() - )[0] + sum_total_amount = get_transactions_totalamount_sum_value_for_type( + accounting_year, transaction_type + ) + get_transactions_totalamount_sum_value_for_parenttype( + accounting_year, transaction_type ) + sum_total_transaction += sum_total_amount transaction_type_info.append( - [ - transaction_type.label, - sum_value if sum_value != 0 else Decimal(0.00), - transaction_type.category, - ] + { + "label": transaction_type.label, + "sum_total_amount": sum_total_amount + if sum_total_amount != 0 + else Decimal(0.00), + "category": transaction_type.category, + } ) - sum_total_transaction = 0 - for transaction_type in transaction_type_info: - sum_total_transaction += transaction_type[1] - return { - "sum": transaction_type_info, + "transaction_type_info": transaction_type_info, "sum_total_transaction": sum_total_transaction, } @@ -193,7 +223,7 @@ def get_right_engagement_and_sump_spf(accounting_year, category): additionne les montants. Args: - accounting_year (int): année + accounting_year (int): année comptable category (int): choix de la catégorie (i.e. "droits" ou "engagements") Returns: @@ -207,7 +237,8 @@ def get_right_engagement_and_sump_spf(accounting_year, category): for right_engagement in right_engagement_list: tmp = list( - RightEngagement.objects.by_year(accounting_year).filter(r_e_type=right_engagement) + RightEngagement.objects.by_year(accounting_year) + .filter(r_e_type=right_engagement) .aggregate(Sum("amount")) .values() )[0] @@ -220,11 +251,11 @@ def get_right_engagement_and_sump_spf(accounting_year, category): def get_asset_liability_and_sump_spf(accounting_year, category): """ - Récupère tous les types de droits et dettes. Pour chacun de ces types, va chercher - l'ensemble lignes correspondantes et additionne les montants. + Récupère tous les types de droits et dettes. Pour chacun de ces types, va chercher l'ensemble + lignes correspondantes et additionne les montants. Args: - accounting_year (int): année + accounting_year (int): année comptable category (int): choix de la catégorie (i.e. "droits" ou "engagements") Returns: @@ -238,7 +269,8 @@ def get_asset_liability_and_sump_spf(accounting_year, category): for item in asset_liability_list: tmp = list( - Patrimony.objects.by_year(accounting_year).filter(patrimony_type=item) + Patrimony.objects.by_year(accounting_year) + .filter(patrimony_type=item) .aggregate(Sum("totalAmount")) .values() )[0] diff --git a/src/comptabilite/urls.py b/src/comptabilite/urls.py index 818e018..9e5a4ae 100644 --- a/src/comptabilite/urls.py +++ b/src/comptabilite/urls.py @@ -32,7 +32,11 @@ urlpatterns = [ name="transaction_listing_for_year_and_type", ), # http://127.0.0.1:8000/comptability/annual/listing/2017/3 - url(r"^listing/(?P[0-9]{4})$", transaction_by_year_listing, name="by_year"), + url( + r"^listing/(?P[0-9]{4})$", + transaction_by_year_listing, + name="by_year", + ), url( r"^details/(?P[0-9]+)", transaction_details, @@ -48,5 +52,9 @@ urlpatterns = [ comptability_export, name="export", ), - url(r"^export/pdf/(?P[0-9]{4})/", generate_pdf_for_spf, name="pdf_export"), + url( + r"^export/pdf/(?P[0-9]{4})/", + generate_pdf_for_spf, + name="pdf_export", + ), ] diff --git a/src/comptabilite/utils.py b/src/comptabilite/utils.py index 562ccd7..6e2a02d 100644 --- a/src/comptabilite/utils.py +++ b/src/comptabilite/utils.py @@ -1,5 +1,6 @@ from decimal import Decimal + def zero_or_value(value): """Retourne zéro si la valeur est nulle.""" return value if value else Decimal(0.00) diff --git a/src/comptabilite/views.py b/src/comptabilite/views.py index 8f752ad..f870f0d 100644 --- a/src/comptabilite/views.py +++ b/src/comptabilite/views.py @@ -35,6 +35,7 @@ import locale EXTENSES = 0 RECETTES = 1 + def comptability_export(request, accounting_year, export_type): """ Définit une fonction d'export. @@ -55,11 +56,15 @@ def comptability_export(request, accounting_year, export_type): def get_transaction_list_for_accountingyear_ooo(request, accounting_year): """ - Affichage et calcul des `Recettes` et `Dépenses` pour une année donnée dans deux tableaux l'un au - dessus de l'autre (one over other - ooo). + Affichage et calcul des `Recettes` et `Dépenses` pour une année donnée dans deux tableaux l'un + au dessus de l'autre (one over other - ooo). """ - transactions_list_expenses = get_transactions_and_sums_for_year_and_type(accounting_year, EXTENSES) - transactions_list_recettes = get_transactions_and_sums_for_year_and_type(accounting_year, RECETTES) + transactions_list_expenses = get_transactions_and_sums_for_year_and_type( + accounting_year, EXTENSES + ) + transactions_list_recettes = get_transactions_and_sums_for_year_and_type( + accounting_year, RECETTES + ) context = { "transactions_list_expenses": transactions_list_expenses, "accounting_year": accounting_year, @@ -69,18 +74,22 @@ def get_transaction_list_for_accountingyear_ooo(request, accounting_year): return render(request, "year_transaction_export_ooo.html", context) -#def two_table_side_by_side_export(request, accounting_year): +# def two_table_side_by_side_export(request, accounting_year): def get_transaction_list_for_accountingyear_sxs(request, accounting_year): """ Calcule et affiche la comptabilité d'une année passée en parametre dans un unique tableau (side by side). """ - expenses_transactiontypes_list = get_transactiontypes_and_total_amount_transactions(accounting_year, EXTENSES) - recettes_transactiontypes_list = get_transactiontypes_and_total_amount_transactions(accounting_year, RECETTES) + expenses_transactiontypes_list = get_transactiontypes_and_total_amount_transactions( + accounting_year, EXTENSES + ) + recettes_transactiontypes_list = get_transactiontypes_and_total_amount_transactions( + accounting_year, RECETTES + ) transactiontypes_list = zip_longest( recettes_transactiontypes_list["transactiontypes_info_list"], - expenses_transactiontypes_list["transactiontypes_info_list"] + expenses_transactiontypes_list["transactiontypes_info_list"], ) context = { @@ -102,8 +111,12 @@ def export_year_spf_finance(request, accounting_year): """ annuality = Annuality.objects.filter(year__year=accounting_year) - transactiontypes_list_expenses = get_transactiontype_and_sum_for_spf_export(accounting_year, EXTENSES) - transactiontypes_list_recettes = get_transactiontype_and_sum_for_spf_export(accounting_year, RECETTES) + transactiontypes_list_expenses = get_transactiontype_and_sum_for_spf_export( + accounting_year, EXTENSES + ) + transactiontypes_list_recettes = get_transactiontype_and_sum_for_spf_export( + accounting_year, RECETTES + ) list_sum = [ x for x in zip_longest( @@ -134,12 +147,11 @@ def export_year_spf_finance(request, accounting_year): ) liquidity = item[1] - liability_list = get_asset_liability_and_sump_spf(accounting_year, category=1) - asset_liability_sum = [x for x in zip_longest(assets_list, liability_list)] + asset_liability_list = get_asset_liability_and_sump_spf(accounting_year, category=1) + asset_liability_sum = [x for x in zip_longest(assets_list, asset_liability_list)] right_list = get_right_engagement_and_sump_spf(accounting_year, category=0) engagement_list = get_right_engagement_and_sump_spf(accounting_year, category=1) - # right_engagement_sum = zip_longest(right_list, engagement_list) right_engagement_sum = [x for x in zip_longest(right_list, engagement_list)] if len(right_engagement_sum) == 0: @@ -270,10 +282,16 @@ class MyDocument(object): def __display_table_transaction(self, accounting_year): self.__display_table_header("DEPENSES", "RECETTES") - transactions_extenses = get_transactiontype_and_sum_for_spf_export(accounting_year, EXTENSES) - transactions_recettes = get_transactiontype_and_sum_for_spf_export(accounting_year, RECETTES) + transactions_extenses = get_transactiontype_and_sum_for_spf_export( + accounting_year, EXTENSES + ) + transactions_recettes = get_transactiontype_and_sum_for_spf_export( + accounting_year, RECETTES + ) - self.__display_table_transaction_body(transactions_extenses, transactions_recettes) + self.__display_table_transaction_body( + transactions_extenses, transactions_recettes + ) self.__display_table_footer( int(transactions_extenses["sum_total_transaction"]), @@ -469,8 +487,12 @@ class MyDocument(object): self.drawNewLine(X, "4. Etat du patrimoine") annuality = Annuality.objects.filter(year__year=accounting_year) - tmp_compta_extenses = get_transactiontype_and_sum_for_spf_export(accounting_year, EXTENSES) - tmp_compta_recettes = get_transactiontype_and_sum_for_spf_export(accounting_year, RECETTES) + tmp_compta_extenses = get_transactiontype_and_sum_for_spf_export( + accounting_year, EXTENSES + ) + tmp_compta_recettes = get_transactiontype_and_sum_for_spf_export( + accounting_year, RECETTES + ) assets_list = get_asset_liability_and_sump_spf(accounting_year, category=0) for item in assets_list: @@ -551,7 +573,7 @@ def generate_pdf_for_spf(request, accounting_year): Args: accounting_year (int): année - + Returns: ??? """ @@ -571,19 +593,25 @@ def generate_pdf_for_spf(request, accounting_year): return response -def __get_transactions_for_accounting_year_and_kind(accounting_year, transaction_kind=None): +def __get_transactions_for_accounting_year_and_kind( + accounting_year, transaction_kind=None +): """ """ - transactions_list = Transaction.objects.by_year(accounting_year) + transactions_list = Transaction.objects.by_year(accounting_year) if transaction_kind == "bank": transaction_kind = "Banque" - transactions_list = transactions_list.filter(bkAmount__isnull=False).exclude(bkAmount=0) + transactions_list = transactions_list.filter(bkAmount__isnull=False).exclude( + bkAmount=0 + ) elif transaction_kind == "box": transaction_kind = "Caisse" - transactions_list = transactions_list.filter(bxAmount__isnull=False).exclude(bxAmount=0) + transactions_list = transactions_list.filter(bxAmount__isnull=False).exclude( + bxAmount=0 + ) else: transaction_kind = "Tous" @@ -598,10 +626,15 @@ def transaction_by_year_listing(request, accounting_year, transaction_kind=None) Args: accounting_year (int): année comptable - transaction_kind (string): + transaction_kind (string): """ - transactions_list, transaction_kind = __get_transactions_for_accounting_year_and_kind(accounting_year, transaction_kind) + ( + transactions_list, + transaction_kind, + ) = __get_transactions_for_accounting_year_and_kind( + accounting_year, transaction_kind + ) # pour mon dictionnaire date/total previous_date = None @@ -681,20 +714,17 @@ def year_listing(request): year_list = [] for year in years: - year_list.append( - ( - year.year, - Transaction.objects.by_year(year.year).count(), - ) - ) + year_list.append((year.year, Transaction.objects.by_year(year.year).count(),)) context = {"year_list": year_list} return render(request, "year_listing.html", context) -def transaction_listing_for_year_and_type(request, accounting_year, transaction_type_id): +def transaction_listing_for_year_and_type( + request, accounting_year, transaction_type_id +): """ - Liste toutes les transactions d'un `type de transaction` et pour une année (passés en paramètre). + Liste toutes les transactions d'un `type de transaction` et pour une année passés en paramètre. Args: request (???): @@ -709,7 +739,11 @@ def transaction_listing_for_year_and_type(request, accounting_year, transaction_ by_type_condition = Q(transaction_type=transaction_type_id) by_parent_type_condition = Q(transaction_type__parent=transaction_type_id) - transaction_list = Transaction.objects.by_year(accounting_year).filter((by_type_condition | by_parent_type_condition)).order_by("registrationDate") + transaction_list = ( + Transaction.objects.by_year(accounting_year) + .filter((by_type_condition | by_parent_type_condition)) + .order_by("registrationDate") + ) total = 0 total_simulated = 0