From a3b0ea9b8d15311539fc0df460be83f9adea5209 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 11:06:48 +0100 Subject: [PATCH 01/22] Fetch transfers in `history_json` --- kfet/views.py | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/kfet/views.py b/kfet/views.py index 655e856d..1b8fc0dc 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -12,7 +12,7 @@ from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.models import Permission, User from django.contrib.messages.views import SuccessMessageMixin from django.db import transaction -from django.db.models import Count, F, Prefetch, Sum +from django.db.models import Count, F, Prefetch, Q, Sum from django.forms import formset_factory from django.http import Http404, JsonResponse from django.shortcuts import get_object_or_404, redirect, render @@ -1416,42 +1416,73 @@ def history_json(request): # Récupération des paramètres from_date = request.POST.get("from", None) to_date = request.POST.get("to", None) - limit = request.POST.get("limit", None) checkouts = request.POST.getlist("checkouts[]", None) accounts = request.POST.getlist("accounts[]", None) + transfers_only = request.POST.get("transfersonly", None) + opes_only = request.POST.get("opesonly", None) # Construction de la requête (sur les opérations) pour le prefetch - queryset_prefetch = Operation.objects.select_related( + ope_queryset_prefetch = Operation.objects.select_related( "article", "canceled_by", "addcost_for" ) + ope_prefetch = Prefetch("opes", queryset=ope_queryset_prefetch) + + transfer_queryset_prefetch = Transfer.objects.select_related( + "from_acc", "to_acc", "canceled_by" + ) + + if accounts: + transfer_queryset_prefetch = transfer_queryset_prefetch.filter( + Q(from_acc__trigramme__in=accounts) | Q(to_acc__trigramme__in=accounts) + ) + + if not request.user.has_perm("kfet.is_team"): + acc = request.user.profile.account_kfet + transfer_queryset_prefetch = transfer_queryset_prefetch.filter( + Q(from_acc=acc) | Q(to_acc=acc) + ) + + transfer_prefetch = Prefetch( + "transfers", queryset=transfer_queryset_prefetch, to_attr="filtered_transfers" + ) # Construction de la requête principale opegroups = ( - OperationGroup.objects.prefetch_related( - Prefetch("opes", queryset=queryset_prefetch) - ) + OperationGroup.objects.prefetch_related(ope_prefetch) .select_related("on_acc", "valid_by") .order_by("at") ) + transfergroups = ( + TransferGroup.objects.prefetch_related(transfer_prefetch) + .select_related("valid_by") + .order_by("at") + ) + # Application des filtres if from_date: opegroups = opegroups.filter(at__gte=from_date) + transfergroups = transfergroups.filter(at__gte=from_date) if to_date: opegroups = opegroups.filter(at__lt=to_date) + transfergroups = transfergroups.filter(at__lt=to_date) if checkouts: opegroups = opegroups.filter(checkout_id__in=checkouts) + transfergroups = TransferGroup.objects.none() + if transfers_only: + opegroups = OperationGroup.objects.none() + if opes_only: + transfergroups = TransferGroup.objects.none() if accounts: opegroups = opegroups.filter(on_acc_id__in=accounts) # Un non-membre de l'équipe n'a que accès à son historique if not request.user.has_perm("kfet.is_team"): opegroups = opegroups.filter(on_acc=request.user.profile.account_kfet) - if limit: - opegroups = opegroups[:limit] # Construction de la réponse opegroups_list = [] for opegroup in opegroups: opegroup_dict = { + "type": "opegroup", "id": opegroup.id, "amount": opegroup.amount, "at": opegroup.at, From bf117ec070fa832daa48cf750d802b7fdf6be9d6 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 11:07:02 +0100 Subject: [PATCH 02/22] Renvoie les transferts dans l'historique --- kfet/views.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/kfet/views.py b/kfet/views.py index 1b8fc0dc..cb35cca8 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1515,6 +1515,37 @@ def history_json(request): ) opegroup_dict["opes"].append(ope_dict) opegroups_list.append(opegroup_dict) + for transfergroup in transfergroups: + if transfergroup.filtered_transfers: + transfergroup_dict = { + "type": "transfergroup", + "id": transfergroup.id, + "at": transfergroup.at, + "comment": transfergroup.comment, + "opes": [], + } + if request.user.has_perm("kfet.is_team"): + transfergroup_dict["valid_by__trigramme"] = ( + transfergroup.valid_by and transfergroup.valid_by.trigramme or None + ) + + for transfer in transfergroup.filtered_transfers: + transfer_dict = { + "id": transfer.id, + "amount": transfer.amount, + "canceled_at": transfer.canceled_at, + "from_acc": transfer.from_acc.trigramme, + "to_acc": transfer.to_acc.trigramme, + } + if request.user.has_perm("kfet.is_team"): + transfer_dict["canceled_by__trigramme"] = ( + transfer.canceled_by and transfer.canceled_by.trigramme or None + ) + transfergroup_dict["opes"].append(transfer_dict) + opegroups_list.append(transfergroup_dict) + + opegroups_list.sort(key=lambda group: group["at"]) + return JsonResponse({"opegroups": opegroups_list}) From c3b5de336a23fe86b9514092bca92ecaf52f900c Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 11:30:25 +0100 Subject: [PATCH 03/22] =?UTF-8?q?G=C3=A8re=20l'affichage=20des=20transfert?= =?UTF-8?q?s=20dans=20l'historique?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/static/kfet/css/history.css | 9 ++++ kfet/static/kfet/js/history.js | 78 ++++++++++++++++++++++++++------ 2 files changed, 73 insertions(+), 14 deletions(-) diff --git a/kfet/static/kfet/css/history.css b/kfet/static/kfet/css/history.css index 9cd4cd28..e1e1ab42 100644 --- a/kfet/static/kfet/css/history.css +++ b/kfet/static/kfet/css/history.css @@ -108,3 +108,12 @@ #history .transfer .from_acc { padding-left:10px; } + +#history .opegroup .infos { + text-align:center; + width:145px; +} + +#history .ope .glyphicon { + padding-left:15px; +} diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index a7372b87..cb9399b2 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -19,10 +19,22 @@ function KHistory(options = {}) { var trigramme = opegroup['on_acc_trigramme']; var is_cof = opegroup['is_cof']; - for (var i = 0; i < opegroup['opes'].length; i++) { - var $ope = this._opeHtml(opegroup['opes'][i], is_cof, trigramme); - $ope.data('opegroup', opegroup['id']); - $opegroup.after($ope); + var type = opegroup['type'] + switch (type) { + case 'opegroup': + for (let ope of opegroup['opes']) { + var $ope = this._opeHtml(ope, is_cof, trigramme); + $ope.data('opegroup', opegroup['id']); + $opegroup.after($ope); + } + break; + case 'transfergroup': + for (let transfer of opegroup['opes']) { + var $transfer = this._transferHtml(transfer); + $transfer.data('transfergroup', opegroup['id']); + $opegroup.after($transfer); + } + break; } } @@ -54,7 +66,8 @@ function KHistory(options = {}) { } $ope_html - .data('ope', ope['id']) + .data('type', 'ope') + .data('id', ope['id']) .find('.amount').text(amount).end() .find('.infos1').text(infos1).end() .find('.infos2').text(infos2).end(); @@ -62,7 +75,7 @@ function KHistory(options = {}) { var addcost_for = ope['addcost_for__trigramme']; if (addcost_for) { var addcost_amount = parseFloat(ope['addcost_amount']); - $ope_html.find('.addcost').text('(' + amountDisplay(addcost_amount, is_cof) + 'UKF pour ' + addcost_for + ')'); + $ope_html.find('.addcost').text('(' + amountDisplay(addcost_amount, is_cof) + ' UKF pour ' + addcost_for + ')'); } if (ope['canceled_at']) @@ -71,9 +84,28 @@ function KHistory(options = {}) { return $ope_html; } + this._transferHtml = function (transfer) { + var $transfer_html = $(this.template_transfer); + var parsed_amount = parseFloat(transfer['amount']); + var amount = parsed_amount.toFixed(2) + '€'; + + $transfer_html + .data('type', 'transfer') + .data('id', transfer['id']) + .find('.amount').text(amount).end() + .find('.infos1').text(transfer['from_acc']).end() + .find('.infos2').text(transfer['to_acc']).end(); + + if (transfer['canceled_at']) + this.cancelOpe(transfer, $transfer_html); + + return $transfer_html; + } + + this.cancelOpe = function (ope, $ope = null) { if (!$ope) - $ope = this.findOpe(ope['id']); + $ope = this.findOpe(ope['id'], ope["type"]); var cancel = 'Annulé'; var canceled_at = dateUTCToParis(ope['canceled_at']); @@ -85,16 +117,31 @@ function KHistory(options = {}) { } this._opeGroupHtml = function (opegroup) { - var $opegroup_html = $(this.template_opegroup); + var type = opegroup['type']; + + + switch (type) { + case 'opegroup': + var $opegroup_html = $(this.template_opegroup); + var trigramme = opegroup['on_acc__trigramme']; + var amount = amountDisplay( + parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); + break; + case 'transfergroup': + var $opegroup_html = $(this.template_transfergroup); + $opegroup_html.find('.infos').text('Transferts').end() + var trigramme = ''; + var amount = ''; + break; + } + var at = dateUTCToParis(opegroup['at']).format('HH:mm:ss'); - var trigramme = opegroup['on_acc__trigramme']; - var amount = amountDisplay( - parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); var comment = opegroup['comment'] || ''; $opegroup_html - .data('opegroup', opegroup['id']) + .data('type', type) + .data('id', opegroup['id']) .find('.time').text(at).end() .find('.amount').text(amount).end() .find('.comment').text(comment).end() @@ -102,6 +149,7 @@ function KHistory(options = {}) { if (!this.display_trigramme) $opegroup_html.find('.trigramme').remove(); + $opegroup_html.find('.info').remove(); if (opegroup['valid_by__trigramme']) $opegroup_html.find('.valid_by').text('Par ' + opegroup['valid_by__trigramme']); @@ -127,9 +175,9 @@ function KHistory(options = {}) { }); } - this.findOpe = function (id) { + this.findOpe = function (id, type = 'ope') { return this.$container.find('.ope').filter(function () { - return $(this).data('ope') == id + return ($(this).data('id') == id && $(this).data('type') == type) }); } @@ -147,6 +195,8 @@ KHistory.default_options = { container: '#history', template_day: '
', template_opegroup: '
', + template_transfergroup: '
', template_ope: '
', + template_transfer: '
', display_trigramme: true, } From 9b2c4c1f9853fc6351ee381265758d5756b0a651 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 11:34:08 +0100 Subject: [PATCH 04/22] Change l'affichage de la date dans l'historique Fixes #233 --- kfet/static/kfet/js/history.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index cb9399b2..c087d56a 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -166,7 +166,7 @@ function KHistory(options = {}) { if ($day.length == 1) return $day; var $day = $(this.template_day).prependTo(this.$container); - return $day.data('date', at_ser).text(at.format('D MMMM')); + return $day.data('date', at_ser).text(at.format('D MMMM YYYY')); } this.findOpeGroup = function (id) { From 36d6a4a1cd80fe8248c7cbe9c2b138264cd11b67 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 12:54:30 +0100 Subject: [PATCH 05/22] =?UTF-8?q?D=C3=A9place=20la=20logique=20de=20l'hist?= =?UTF-8?q?orique=20dans=20`history.js`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On change le lock en `window.lock` pour y avoir accès partout --- kfet/static/kfet/js/history.js | 71 ++++++++++++++++++++++ kfet/templates/kfet/kpsul.html | 104 ++++----------------------------- 2 files changed, 83 insertions(+), 92 deletions(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index c087d56a..2869ea86 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -7,6 +7,20 @@ function KHistory(options = {}) { this.$container = $(this.container); + this.$container.selectable({ + filter: 'div.opegroup, div.ope', + selected: function (e, ui) { + $(ui.selected).each(function () { + if ($(this).hasClass('opegroup')) { + var opegroup = $(this).data('id'); + $(this).siblings('.ope').filter(function () { + return $(this).data('opegroup') == opegroup + }).addClass('ui-selected'); + } + }); + }, + }); + this.reset = function () { this.$container.html(''); }; @@ -189,6 +203,63 @@ function KHistory(options = {}) { $opegroup.find('.amount').text(amount); } + this.fetch = function (fetch_options) { + options = $.extend({}, this.fetch_options, fetch_options); + var that = this; + $.ajax({ + dataType: "json", + url: django_urls["kfet.history.json"](), + method: "POST", + data: options, + }).done(function (data) { + for (let opegroup of data['opegroups']) { + that.addOpeGroup(opegroup); + } + }); + } + + this.cancel_opes = function (opes, password = "") { + if (window.lock == 1) + return false + window.lock = 1; + $.ajax({ + dataType: "json", + url: django_urls["kfet.kpsul.cancel_operations"](), + method: "POST", + data: { + 'operations': opes + }, + beforeSend: function ($xhr) { + $xhr.setRequestHeader("X-CSRFToken", csrftoken); + if (password != '') + $xhr.setRequestHeader("KFetPassword", password); + }, + + }).done(function (data) { + window.lock = 0; + }).fail(function ($xhr) { + var data = $xhr.responseJSON; + switch ($xhr.status) { + case 403: + requestAuth(data, function (password) { + this.cancel(opes, password); + }); + break; + case 400: + displayErrors(getErrorsHtml(data)); + break; + } + window.lock = 0; + }); + } + + this.cancel_selected = function () { + var opes_to_cancel = this.$container.find('.ope.ui-selected').map(function () { + return $(this).data('id'); + }).toArray(); + if (opes_to_cancel.length > 0) + this.cancel(opes_to_cancel); + } } KHistory.default_options = { diff --git a/kfet/templates/kfet/kpsul.html b/kfet/templates/kfet/kpsul.html index 171c7030..c745d598 100644 --- a/kfet/templates/kfet/kpsul.html +++ b/kfet/templates/kfet/kpsul.html @@ -189,7 +189,7 @@ $(document).ready(function() { // ----- // Lock to avoid multiple requests - lock = 0; + window.lock = 0; // Retrieve settings @@ -479,9 +479,9 @@ $(document).ready(function() { var operations = $('#operation_formset'); function performOperations(password = '') { - if (lock == 1) + if (window.lock == 1) return false; - lock = 1; + window.lock = 1; var data = operationGroup.serialize() + '&' + operations.serialize(); $.ajax({ dataType: "json", @@ -497,7 +497,7 @@ $(document).ready(function() { .done(function(data) { updatePreviousOp(); coolReset(); - lock = 0; + window.lock = 0; }) .fail(function($xhr) { var data = $xhr.responseJSON; @@ -513,7 +513,7 @@ $(document).ready(function() { } break; } - lock = 0; + window.lock = 0; }); } @@ -522,55 +522,6 @@ $(document).ready(function() { performOperations(); }); - // ----- - // Cancel operations - // ----- - - var cancelButton = $('#cancel_operations'); - var cancelForm = $('#cancel_form'); - - function cancelOperations(opes_array, password = '') { - if (lock == 1) - return false - lock = 1; - var data = { 'operations' : opes_array } - $.ajax({ - dataType: "json", - url : "{% url 'kfet.kpsul.cancel_operations' %}", - method : "POST", - data : data, - beforeSend: function ($xhr) { - $xhr.setRequestHeader("X-CSRFToken", csrftoken); - if (password != '') - $xhr.setRequestHeader("KFetPassword", password); - }, - - }) - .done(function(data) { - coolReset(); - lock = 0; - }) - .fail(function($xhr) { - var data = $xhr.responseJSON; - switch ($xhr.status) { - case 403: - requestAuth(data, function(password) { - cancelOperations(opes_array, password); - }, triInput); - break; - case 400: - displayErrors(getErrorsHtml(data)); - break; - } - lock = 0; - }); - } - - // Event listeners - cancelButton.on('click', function() { - cancelOperations(); - }); - // ----- // Articles data // ----- @@ -1189,24 +1140,12 @@ $(document).ready(function() { // History // ----- - khistory = new KHistory(); - - function getHistory() { - var data = { + khistory = new KHistory({ + fetch_options: { from: moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss'), - }; - $.ajax({ - dataType: "json", - url : "{% url 'kfet.history.json' %}", - method : "POST", - data : data, - }) - .done(function(data) { - for (var i=0; i 0) - cancelOperations(opes_to_cancel); + khistory.cancel_selected() } }); @@ -1396,7 +1316,7 @@ $(document).ready(function() { khistory.reset(); resetSettings().done(function (){ getArticles(); - getHistory(); + khistory.fetch(); displayAddcost(); }); } From 41ad2a15ac7dd42e8f25ab76acefb83d9d4544e2 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 12:59:46 +0100 Subject: [PATCH 06/22] Update websocket data --- kfet/views.py | 1 + 1 file changed, 1 insertion(+) diff --git a/kfet/views.py b/kfet/views.py index cb35cca8..d7a7be55 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1159,6 +1159,7 @@ def kpsul_perform_operations(request): websocket_data["opegroups"] = [ { "add": True, + "type": "opegroup", "id": operationgroup.pk, "amount": operationgroup.amount, "checkout__name": operationgroup.checkout.name, From c95e1818b21449fd366538d8f6ed1c15053137db Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 13:20:47 +0100 Subject: [PATCH 07/22] Fix ws tests --- kfet/tests/test_views.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/kfet/tests/test_views.py b/kfet/tests/test_views.py index 0a5c4e49..71c9c72c 100644 --- a/kfet/tests/test_views.py +++ b/kfet/tests/test_views.py @@ -2000,6 +2000,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, + "type": "opegroup", "at": mock.ANY, "amount": Decimal("-5.00"), "checkout__name": "Checkout", @@ -2272,6 +2273,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, + "type": "opegroup", "at": mock.ANY, "amount": Decimal("10.75"), "checkout__name": "Checkout", @@ -2446,6 +2448,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, + "type": "opegroup", "at": mock.ANY, "amount": Decimal("-10.75"), "checkout__name": "Checkout", @@ -2604,6 +2607,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, + "type": "opegroup", "at": mock.ANY, "amount": Decimal("10.75"), "checkout__name": "Checkout", @@ -3173,6 +3177,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, + "type": "opegroup", "at": mock.ANY, "amount": Decimal("-9.00"), "checkout__name": "Checkout", From af0de33d4c6bb0c069b01604e84260f320435ef4 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 14:16:23 +0100 Subject: [PATCH 08/22] =?UTF-8?q?Suppression=20des=20op=C3=A9rations=20et?= =?UTF-8?q?=20des=20transferts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/static/kfet/js/history.js | 40 +++++++++++++++++++++++++--------- kfet/urls.py | 4 ++-- kfet/views.py | 2 +- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index 2869ea86..b398a65c 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -218,17 +218,15 @@ function KHistory(options = {}) { }); } - this.cancel_opes = function (opes, password = "") { + this.cancel = function (type, opes, password = "") { if (window.lock == 1) return false window.lock = 1; $.ajax({ dataType: "json", - url: django_urls["kfet.kpsul.cancel_operations"](), + url: django_urls[`kfet.${type}.cancel`](), method: "POST", - data: { - 'operations': opes - }, + data: opes, beforeSend: function ($xhr) { $xhr.setRequestHeader("X-CSRFToken", csrftoken); if (password != '') @@ -254,11 +252,33 @@ function KHistory(options = {}) { } this.cancel_selected = function () { - var opes_to_cancel = this.$container.find('.ope.ui-selected').map(function () { - return $(this).data('id'); - }).toArray(); - if (opes_to_cancel.length > 0) - this.cancel(opes_to_cancel); + var opes_to_cancel = { + "transfers": [], + "operations": [], + } + this.$container.find('.ope.ui-selected').each(function () { + if ($(this).data("transfergroup")) + opes_to_cancel["transfers"].push($(this).data("id")); + else + opes_to_cancel["operations"].push($(this).data("id")); + }); + if (opes_to_cancel["transfers"].length > 0 && opes_to_cancel["operations"].length > 0) { + // Lancer 2 requêtes AJAX et gérer tous les cas d'erreurs possibles est trop complexe + $.alert({ + title: 'Erreur', + content: "Impossible de supprimer des transferts et des opérations en même temps !", + backgroundDismiss: true, + animation: 'top', + closeAnimation: 'bottom', + keyboardEnabled: true, + }); + } else if (opes_to_cancel["transfers"].length > 0) { + delete opes_to_cancel["operations"]; + this.cancel("transfers", opes_to_cancel); + } else if (opes_to_cancel["operations"].length > 0) { + delete opes_to_cancel["transfers"]; + this.cancel("operations", opes_to_cancel); + } } } diff --git a/kfet/urls.py b/kfet/urls.py index 03c174f3..88220845 100644 --- a/kfet/urls.py +++ b/kfet/urls.py @@ -219,8 +219,8 @@ urlpatterns = [ ), path( "k-psul/cancel_operations", - views.kpsul_cancel_operations, - name="kfet.kpsul.cancel_operations", + views.cancel_operations, + name="kfet.operations.cancel", ), path( "k-psul/articles_data", diff --git a/kfet/views.py b/kfet/views.py index d7a7be55..c06bd074 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1208,7 +1208,7 @@ def kpsul_perform_operations(request): @teamkfet_required @kfet_password_auth -def kpsul_cancel_operations(request): +def cancel_operations(request): # Pour la réponse data = {"canceled": [], "warnings": {}, "errors": {}} From 550a073d5176c60d53f5e0d95be2c3fde7b075eb Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 14:17:35 +0100 Subject: [PATCH 09/22] Fix tests again --- kfet/tests/test_views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kfet/tests/test_views.py b/kfet/tests/test_views.py index 71c9c72c..852d5bf1 100644 --- a/kfet/tests/test_views.py +++ b/kfet/tests/test_views.py @@ -3239,7 +3239,7 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): """ - url_name = "kfet.kpsul.cancel_operations" + url_name = "kfet.operations.cancel" url_expected = "/k-fet/k-psul/cancel_operations" http_methods = ["POST"] From 49ef8b3c15a813c9c271622d078b1b839a0e71d0 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 15:09:41 +0100 Subject: [PATCH 10/22] Pas besoin de ws pour les suppressions --- kfet/static/kfet/js/history.js | 41 +++++++++++++++++++++------------- kfet/templates/kfet/kpsul.html | 7 ------ kfet/views.py | 40 +++++++++++++-------------------- 3 files changed, 41 insertions(+), 47 deletions(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index b398a65c..22aff4d6 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -35,14 +35,14 @@ function KHistory(options = {}) { var is_cof = opegroup['is_cof']; var type = opegroup['type'] switch (type) { - case 'opegroup': + case 'operation': for (let ope of opegroup['opes']) { var $ope = this._opeHtml(ope, is_cof, trigramme); $ope.data('opegroup', opegroup['id']); $opegroup.after($ope); } break; - case 'transfergroup': + case 'transfer': for (let transfer of opegroup['opes']) { var $transfer = this._transferHtml(transfer); $transfer.data('transfergroup', opegroup['id']); @@ -80,7 +80,7 @@ function KHistory(options = {}) { } $ope_html - .data('type', 'ope') + .data('type', 'operation') .data('id', ope['id']) .find('.amount').text(amount).end() .find('.infos1').text(infos1).end() @@ -119,7 +119,7 @@ function KHistory(options = {}) { this.cancelOpe = function (ope, $ope = null) { if (!$ope) - $ope = this.findOpe(ope['id'], ope["type"]); + $ope = this.findOpe(ope["id"], ope["type"]); var cancel = 'Annulé'; var canceled_at = dateUTCToParis(ope['canceled_at']); @@ -135,13 +135,13 @@ function KHistory(options = {}) { switch (type) { - case 'opegroup': + case 'operation': var $opegroup_html = $(this.template_opegroup); var trigramme = opegroup['on_acc__trigramme']; var amount = amountDisplay( parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); break; - case 'transfergroup': + case 'transfer': var $opegroup_html = $(this.template_transfergroup); $opegroup_html.find('.infos').text('Transferts').end() var trigramme = ''; @@ -183,20 +183,20 @@ function KHistory(options = {}) { return $day.data('date', at_ser).text(at.format('D MMMM YYYY')); } - this.findOpeGroup = function (id) { + this.findOpeGroup = function (id, type = "operation") { return this.$container.find('.opegroup').filter(function () { - return $(this).data('opegroup') == id + return ($(this).data('id') == id && $(this).data("type") == type) }); } - this.findOpe = function (id, type = 'ope') { + this.findOpe = function (id, type = 'operation') { return this.$container.find('.ope').filter(function () { return ($(this).data('id') == id && $(this).data('type') == type) }); } - this.cancelOpeGroup = function (opegroup) { - var $opegroup = this.findOpeGroup(opegroup['id']); + this.update_opegroup = function (opegroup, type = "operation") { + var $opegroup = this.findOpeGroup(opegroup['id'], type); var trigramme = $opegroup.find('.trigramme').text(); var amount = amountDisplay( parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); @@ -218,13 +218,14 @@ function KHistory(options = {}) { }); } - this.cancel = function (type, opes, password = "") { + this._cancel = function (type, opes, password = "") { if (window.lock == 1) return false window.lock = 1; + var that = this; $.ajax({ dataType: "json", - url: django_urls[`kfet.${type}.cancel`](), + url: django_urls[`kfet.${type}s.cancel`](), method: "POST", data: opes, beforeSend: function ($xhr) { @@ -235,6 +236,16 @@ function KHistory(options = {}) { }).done(function (data) { window.lock = 0; + that.$container.find('.ui-selected').removeClass('ui-selected'); + for (let ope of data["canceled"]) { + ope["type"] = type; + that.cancelOpe(ope); + } + if (type == "operation") { + for (let opegroup of data["opegroups_to_update"]) { + that.update_opegroup(opegroup) + } + } }).fail(function ($xhr) { var data = $xhr.responseJSON; switch ($xhr.status) { @@ -274,10 +285,10 @@ function KHistory(options = {}) { }); } else if (opes_to_cancel["transfers"].length > 0) { delete opes_to_cancel["operations"]; - this.cancel("transfers", opes_to_cancel); + this._cancel("transfer", opes_to_cancel); } else if (opes_to_cancel["operations"].length > 0) { delete opes_to_cancel["transfers"]; - this.cancel("operations", opes_to_cancel); + this._cancel("operation", opes_to_cancel); } } } diff --git a/kfet/templates/kfet/kpsul.html b/kfet/templates/kfet/kpsul.html index c745d598..0b7f946e 100644 --- a/kfet/templates/kfet/kpsul.html +++ b/kfet/templates/kfet/kpsul.html @@ -1256,13 +1256,6 @@ $(document).ready(function() { for (var i=0; i Date: Mon, 23 Dec 2019 15:16:04 +0100 Subject: [PATCH 11/22] On renvoie les promesses --- kfet/static/kfet/js/history.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index 22aff4d6..5608c02f 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -206,7 +206,7 @@ function KHistory(options = {}) { this.fetch = function (fetch_options) { options = $.extend({}, this.fetch_options, fetch_options); var that = this; - $.ajax({ + return $.ajax({ dataType: "json", url: django_urls["kfet.history.json"](), method: "POST", @@ -223,7 +223,7 @@ function KHistory(options = {}) { return false window.lock = 1; var that = this; - $.ajax({ + return $.ajax({ dataType: "json", url: django_urls[`kfet.${type}s.cancel`](), method: "POST", From f7ce2edd87f1d6cdaf97c07d13fa1a6b3f5b5e81 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 18:54:58 +0100 Subject: [PATCH 12/22] Plug new history in templates --- kfet/templates/kfet/account_read.html | 32 +++---- kfet/templates/kfet/history.html | 129 +------------------------- kfet/templates/kfet/transfers.html | 105 ++++----------------- 3 files changed, 35 insertions(+), 231 deletions(-) diff --git a/kfet/templates/kfet/account_read.html b/kfet/templates/kfet/account_read.html index bbd1cff7..d1af035a 100644 --- a/kfet/templates/kfet/account_read.html +++ b/kfet/templates/kfet/account_read.html @@ -5,6 +5,7 @@ {% block extra_head %} + @@ -81,7 +82,7 @@ $(document).ready(function() { {% endif %} -
+
@@ -93,29 +94,22 @@ $(document).ready(function() { khistory = new KHistory({ display_trigramme: false, - }); - - function getHistory() { - var data = { + fetch_options: { 'accounts': [{{ account.pk }}], } + }); - $.ajax({ - dataType: "json", - url : "{% url 'kfet.history.json' %}", - method : "POST", - data : data, - }) - .done(function(data) { - for (var i=0; i diff --git a/kfet/templates/kfet/history.html b/kfet/templates/kfet/history.html index ae63358e..204e0d57 100644 --- a/kfet/templates/kfet/history.html +++ b/kfet/templates/kfet/history.html @@ -5,6 +5,7 @@ {{ filter_form.media }} + {% endblock %} @@ -40,6 +41,8 @@ $(document).ready(function() { settings = { 'subvention_cof': parseFloat({{ kfet_config.subvention_cof|unlocalize }})} + window.lock = 0; + khistory = new KHistory(); var $from_date = $('#id_from_date'); @@ -67,16 +70,7 @@ $(document).ready(function() { var accounts = getSelectedMultiple($accounts); data['accounts'] = accounts; - $.ajax({ - dataType: "json", - url : "{% url 'kfet.history.json' %}", - method : "POST", - data : data, - }) - .done(function(data) { - for (var i=0; i 0) - confirmCancel(opes_to_cancel); + khistory.cancel_selected() } }); - - function confirmCancel(opes_to_cancel) { - var nb = opes_to_cancel.length; - var content = nb+" opérations vont être annulées"; - $.confirm({ - title: 'Confirmation', - content: content, - backgroundDismiss: true, - animation: 'top', - closeAnimation: 'bottom', - keyboardEnabled: true, - confirm: function() { - cancelOperations(opes_to_cancel); - } - }); - } - - function requestAuth(data, callback) { - var content = getErrorsHtml(data); - content += '', - $.confirm({ - title: 'Authentification requise', - content: content, - backgroundDismiss: true, - animation:'top', - closeAnimation:'bottom', - keyboardEnabled: true, - confirm: function() { - var password = this.$content.find('input').val(); - callback(password); - }, - onOpen: function() { - var that = this; - this.$content.find('input').on('keypress', function(e) { - if (e.keyCode == 13) - that.$confirmButton.click(); - }); - }, - }); - } - - function getErrorsHtml(data) { - var content = ''; - if ('missing_perms' in data['errors']) { - content += 'Permissions manquantes'; - content += '
    '; - for (var i=0; i'; - content += '
'; - } - if ('negative' in data['errors']) { - var url_base = "{% url 'kfet.account.update' LIQ}"; - url_base = base_url(0, url_base.length-8); - for (var i=0; iAutorisation de négatif requise pour '+data['errors']['negative'][i]+''; - } - } - return content; - } - - function cancelOperations(opes_array, password = '') { - var data = { 'operations' : opes_array } - $.ajax({ - dataType: "json", - url : "{% url 'kfet.kpsul.cancel_operations' %}", - method : "POST", - data : data, - beforeSend: function ($xhr) { - $xhr.setRequestHeader("X-CSRFToken", csrftoken); - if (password != '') - $xhr.setRequestHeader("KFetPassword", password); - }, - - }) - .done(function(data) { - khistory.$container.find('.ui-selected').removeClass('ui-selected'); - }) - .fail(function($xhr) { - var data = $xhr.responseJSON; - switch ($xhr.status) { - case 403: - requestAuth(data, function(password) { - cancelOperations(opes_array, password); - }); - break; - case 400: - displayErrors(getErrorsHtml(data)); - break; - } - - }); - } - - getHistory(); }); diff --git a/kfet/templates/kfet/transfers.html b/kfet/templates/kfet/transfers.html index f6778b3f..83f20c70 100644 --- a/kfet/templates/kfet/transfers.html +++ b/kfet/templates/kfet/transfers.html @@ -1,9 +1,16 @@ {% extends 'kfet/base_col_2.html' %} {% load staticfiles %} +{% load l10n staticfiles widget_tweaks %} {% block title %}Transferts{% endblock %} {% block header-title %}Transferts{% endblock %} +{% block extra_head %} + + + +{% endblock %} + {% block fixed %}
@@ -16,109 +23,31 @@ {% block main %} -
- {% for transfergroup in transfergroups %} -
- {{ transfergroup.at }} - {{ transfergroup.valid_by.trigramme }} - {{ transfergroup.comment }} -
- {% for transfer in transfergroup.transfers.all %} -
- {{ transfer.amount }} € - {{ transfer.from_acc.trigramme }} - - {{ transfer.to_acc.trigramme }} -
- {% endfor %} - {% endfor %} -
+ +
From 74384451109b95dc73558d7235b6013e90276c40 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 18:55:15 +0100 Subject: [PATCH 13/22] Last tweaks --- kfet/static/kfet/js/history.js | 14 +++++++------- kfet/views.py | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index 5608c02f..98bc7a2a 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -14,7 +14,7 @@ function KHistory(options = {}) { if ($(this).hasClass('opegroup')) { var opegroup = $(this).data('id'); $(this).siblings('.ope').filter(function () { - return $(this).data('opegroup') == opegroup + return $(this).data('group') == opegroup }).addClass('ui-selected'); } }); @@ -38,14 +38,16 @@ function KHistory(options = {}) { case 'operation': for (let ope of opegroup['opes']) { var $ope = this._opeHtml(ope, is_cof, trigramme); - $ope.data('opegroup', opegroup['id']); + $ope.data('group', opegroup['id']); + $ope.data('group_type', type); $opegroup.after($ope); } break; case 'transfer': for (let transfer of opegroup['opes']) { var $transfer = this._transferHtml(transfer); - $transfer.data('transfergroup', opegroup['id']); + $transfer.data('group', opegroup['id']); + $transfer.data('group_type', type); $opegroup.after($transfer); } break; @@ -268,10 +270,8 @@ function KHistory(options = {}) { "operations": [], } this.$container.find('.ope.ui-selected').each(function () { - if ($(this).data("transfergroup")) - opes_to_cancel["transfers"].push($(this).data("id")); - else - opes_to_cancel["operations"].push($(this).data("id")); + type = $(this).data("group_type"); + opes_to_cancel[`${type}s`].push($(this).data("id")); }); if (opes_to_cancel["transfers"].length > 0 && opes_to_cancel["operations"].length > 0) { // Lancer 2 requêtes AJAX et gérer tous les cas d'erreurs possibles est trop complexe diff --git a/kfet/views.py b/kfet/views.py index 4944546e..e4fd2564 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1799,7 +1799,7 @@ def cancel_transfers(request): .filter(pk__in=transfers) .order_by("pk") ) - data["canceled"] = transfers + data["canceled"] = list(transfers) if transfers_already_canceled: data["warnings"]["already_canceled"] = transfers_already_canceled return JsonResponse(data) From fb4455af39cbfbb32346863dab3421270892f228 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Mon, 23 Dec 2019 18:55:45 +0100 Subject: [PATCH 14/22] Fix tests 3 --- kfet/tests/test_views.py | 185 ++++++++++++++++++++++----------------- 1 file changed, 105 insertions(+), 80 deletions(-) diff --git a/kfet/tests/test_views.py b/kfet/tests/test_views.py index 852d5bf1..853ec449 100644 --- a/kfet/tests/test_views.py +++ b/kfet/tests/test_views.py @@ -3358,7 +3358,26 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): ) self.assertDictEqual( - json_data, {"canceled": [operation.pk], "errors": {}, "warnings": {}} + json_data, + { + "canceled": [ + { + "id": operation.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + } + ], + "errors": {}, + "warnings": {}, + "opegroups_to_update": [ + { + "id": group.pk, + "amount": str(group.amount), + "is_cof": group.is_cof, + } + ], + }, ) self.account.refresh_from_db() @@ -3370,26 +3389,7 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): self.kpsul_consumer_mock.group_send.assert_called_with( "kfet.kpsul", - { - "opegroups": [ - { - "cancellation": True, - "id": group.pk, - "amount": Decimal("0.00"), - "is_cof": False, - } - ], - "opes": [ - { - "cancellation": True, - "id": operation.pk, - "canceled_by__trigramme": None, - "canceled_at": self.now + timedelta(seconds=15), - } - ], - "checkouts": [], - "articles": [{"id": self.article.pk, "stock": 22}], - }, + {"checkouts": [], "articles": [{"id": self.article.pk, "stock": 22}]}, ) def test_purchase_with_addcost(self): @@ -3546,7 +3546,26 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): ) self.assertDictEqual( - json_data, {"canceled": [operation.pk], "errors": {}, "warnings": {}} + json_data, + { + "canceled": [ + { + "id": operation.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + } + ], + "errors": {}, + "warnings": {}, + "opegroups_to_update": [ + { + "id": group.pk, + "amount": str(group.amount), + "is_cof": group.is_cof, + } + ], + }, ) self.account.refresh_from_db() @@ -3559,22 +3578,6 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): self.kpsul_consumer_mock.group_send.assert_called_with( "kfet.kpsul", { - "opegroups": [ - { - "cancellation": True, - "id": group.pk, - "amount": Decimal("0.00"), - "is_cof": False, - } - ], - "opes": [ - { - "cancellation": True, - "id": operation.pk, - "canceled_by__trigramme": None, - "canceled_at": self.now + timedelta(seconds=15), - } - ], "checkouts": [{"id": self.checkout.pk, "balance": Decimal("89.25")}], "articles": [], }, @@ -3630,7 +3633,26 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): ) self.assertDictEqual( - json_data, {"canceled": [operation.pk], "errors": {}, "warnings": {}} + json_data, + { + "canceled": [ + { + "id": operation.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + } + ], + "errors": {}, + "warnings": {}, + "opegroups_to_update": [ + { + "id": group.pk, + "amount": str(group.amount), + "is_cof": group.is_cof, + } + ], + }, ) self.account.refresh_from_db() @@ -3643,22 +3665,6 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): self.kpsul_consumer_mock.group_send.assert_called_with( "kfet.kpsul", { - "opegroups": [ - { - "cancellation": True, - "id": group.pk, - "amount": Decimal("0.00"), - "is_cof": False, - } - ], - "opes": [ - { - "cancellation": True, - "id": operation.pk, - "canceled_by__trigramme": None, - "canceled_at": self.now + timedelta(seconds=15), - } - ], "checkouts": [{"id": self.checkout.pk, "balance": Decimal("110.75")}], "articles": [], }, @@ -3714,7 +3720,26 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): ) self.assertDictEqual( - json_data, {"canceled": [operation.pk], "errors": {}, "warnings": {}} + json_data, + { + "canceled": [ + { + "id": operation.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + } + ], + "errors": {}, + "warnings": {}, + "opegroups_to_update": [ + { + "id": group.pk, + "amount": str(group.amount), + "is_cof": group.is_cof, + } + ], + }, ) self.account.refresh_from_db() @@ -3725,27 +3750,7 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): self.assertEqual(self.checkout.balance, Decimal("100.00")) self.kpsul_consumer_mock.group_send.assert_called_with( - "kfet.kpsul", - { - "opegroups": [ - { - "cancellation": True, - "id": group.pk, - "amount": Decimal("0.00"), - "is_cof": False, - } - ], - "opes": [ - { - "cancellation": True, - "id": operation.pk, - "canceled_by__trigramme": None, - "canceled_at": self.now + timedelta(seconds=15), - } - ], - "checkouts": [], - "articles": [], - }, + "kfet.kpsul", {"checkouts": [], "articles": []}, ) @mock.patch("django.utils.timezone.now") @@ -3966,13 +3971,33 @@ class KPsulCancelOperationsViewTests(ViewTestCaseMixin, TestCase): group.refresh_from_db() self.assertEqual(group.amount, Decimal("10.75")) self.assertEqual(group.opes.exclude(canceled_at=None).count(), 3) - + self.maxDiff = None self.assertDictEqual( json_data, { - "canceled": [operation1.pk, operation2.pk], - "warnings": {"already_canceled": [operation3.pk]}, + "canceled": [ + { + "id": operation1.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + }, + { + "id": operation2.id, + # l'encodage des dates en JSON est relou... + "canceled_at": mock.ANY, + "canceled_by__trigramme": None, + }, + ], "errors": {}, + "warnings": {"already_canceled": [operation3.pk]}, + "opegroups_to_update": [ + { + "id": group.pk, + "amount": str(group.amount), + "is_cof": group.is_cof, + } + ], }, ) From 677ba5b92e7b5883ed1f648294f7707dabcbeb0d Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Wed, 25 Dec 2019 11:34:34 +0100 Subject: [PATCH 15/22] Fix : le ws K-Psul remarche --- kfet/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kfet/views.py b/kfet/views.py index e4fd2564..3122636b 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1159,7 +1159,7 @@ def kpsul_perform_operations(request): websocket_data["opegroups"] = [ { "add": True, - "type": "opegroup", + "type": "operation", "id": operationgroup.pk, "amount": operationgroup.amount, "checkout__name": operationgroup.checkout.name, From 786c8f132f03fa5f5c03a5ebfef823240c3eb4ed Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Wed, 25 Dec 2019 11:53:08 +0100 Subject: [PATCH 16/22] =?UTF-8?q?Fix:=20tests=20cass=C3=A9s=20par=20commit?= =?UTF-8?q?=20pr=C3=A9c=C3=A9dent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/tests/test_views.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/kfet/tests/test_views.py b/kfet/tests/test_views.py index 853ec449..e69c81d9 100644 --- a/kfet/tests/test_views.py +++ b/kfet/tests/test_views.py @@ -2000,7 +2000,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, - "type": "opegroup", + "type": "operation", "at": mock.ANY, "amount": Decimal("-5.00"), "checkout__name": "Checkout", @@ -2273,7 +2273,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, - "type": "opegroup", + "type": "operation", "at": mock.ANY, "amount": Decimal("10.75"), "checkout__name": "Checkout", @@ -2448,7 +2448,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, - "type": "opegroup", + "type": "operation", "at": mock.ANY, "amount": Decimal("-10.75"), "checkout__name": "Checkout", @@ -2607,7 +2607,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, - "type": "opegroup", + "type": "operation", "at": mock.ANY, "amount": Decimal("10.75"), "checkout__name": "Checkout", @@ -3177,7 +3177,7 @@ class KPsulPerformOperationsViewTests(ViewTestCaseMixin, TestCase): "opegroups": [ { "add": True, - "type": "opegroup", + "type": "operation", "at": mock.ANY, "amount": Decimal("-9.00"), "checkout__name": "Checkout", From 8d11044610dd25c5656e97947e5afd9f2552d5f0 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Wed, 25 Dec 2019 12:35:46 +0100 Subject: [PATCH 17/22] =?UTF-8?q?Fix:=20pas=20d'erreur=20quand=20pas=20de?= =?UTF-8?q?=20compte=20K-F=C3=AAt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/tests/test_views.py | 10 ++++++++-- kfet/views.py | 11 +++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/kfet/tests/test_views.py b/kfet/tests/test_views.py index e69c81d9..3baed2c3 100644 --- a/kfet/tests/test_views.py +++ b/kfet/tests/test_views.py @@ -3,7 +3,7 @@ from datetime import datetime, timedelta from decimal import Decimal from unittest import mock -from django.contrib.auth.models import Group +from django.contrib.auth.models import Group, User from django.test import Client, TestCase from django.urls import reverse from django.utils import timezone @@ -4151,12 +4151,18 @@ class HistoryJSONViewTests(ViewTestCaseMixin, TestCase): url_expected = "/k-fet/history.json" auth_user = "user" - auth_forbidden = [None] + auth_forbidden = [None, "noaccount"] def test_ok(self): r = self.client.post(self.url) self.assertEqual(r.status_code, 200) + def get_users_extra(self): + noaccount = User.objects.create(username="noaccount") + noaccount.set_password("noaccount") + noaccount.save() + return {"noaccount": noaccount} + class AccountReadJSONViewTests(ViewTestCaseMixin, TestCase): url_name = "kfet.account.read.json" diff --git a/kfet/views.py b/kfet/views.py index 3122636b..9d2d2c09 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1423,10 +1423,13 @@ def history_json(request): ) if not request.user.has_perm("kfet.is_team"): - acc = request.user.profile.account_kfet - transfer_queryset_prefetch = transfer_queryset_prefetch.filter( - Q(from_acc=acc) | Q(to_acc=acc) - ) + try: + acc = request.user.profile.account_kfet + transfer_queryset_prefetch = transfer_queryset_prefetch.filter( + Q(from_acc=acc) | Q(to_acc=acc) + ) + except Account.DoesNotExist: + return JsonResponse({}, status=403) transfer_prefetch = Prefetch( "transfers", queryset=transfer_queryset_prefetch, to_attr="filtered_transfers" From b450cb09e681a163d1b7fa0e1b1164c856c43640 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Wed, 25 Dec 2019 12:39:41 +0100 Subject: [PATCH 18/22] Petit refactor --- kfet/views.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/kfet/views.py b/kfet/views.py index 9d2d2c09..3d9ff79a 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1407,16 +1407,13 @@ def history_json(request): transfers_only = request.POST.get("transfersonly", None) opes_only = request.POST.get("opesonly", None) - # Construction de la requête (sur les opérations) pour le prefetch - ope_queryset_prefetch = Operation.objects.select_related( - "article", "canceled_by", "addcost_for" - ) - ope_prefetch = Prefetch("opes", queryset=ope_queryset_prefetch) + # Construction de la requête (sur les transferts) pour le prefetch transfer_queryset_prefetch = Transfer.objects.select_related( "from_acc", "to_acc", "canceled_by" ) + # Le check sur les comptes est dans le prefetch pour les transferts if accounts: transfer_queryset_prefetch = transfer_queryset_prefetch.filter( Q(from_acc__trigramme__in=accounts) | Q(to_acc__trigramme__in=accounts) @@ -1435,6 +1432,12 @@ def history_json(request): "transfers", queryset=transfer_queryset_prefetch, to_attr="filtered_transfers" ) + # Construction de la requête (sur les opérations) pour le prefetch + ope_queryset_prefetch = Operation.objects.select_related( + "article", "canceled_by", "addcost_for" + ) + ope_prefetch = Prefetch("opes", queryset=ope_queryset_prefetch) + # Construction de la requête principale opegroups = ( OperationGroup.objects.prefetch_related(ope_prefetch) From 931b2c4e1f23ed940f96ed0dc508cfcbda28fe24 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Wed, 25 Dec 2019 17:28:36 +0100 Subject: [PATCH 19/22] Refactor js code Harmonize history denominations * opegroups/transfergroups -> groups * opes/transfers -> entries * snake/camel case -> snake case --- kfet/static/kfet/css/history.css | 42 ++++------ kfet/static/kfet/js/history.js | 140 +++++++++++++++---------------- kfet/templates/kfet/kpsul.html | 6 +- kfet/tests/test_views.py | 50 +++++------ kfet/views.py | 24 +++--- 5 files changed, 127 insertions(+), 135 deletions(-) diff --git a/kfet/static/kfet/css/history.css b/kfet/static/kfet/css/history.css index e1e1ab42..42e73527 100644 --- a/kfet/static/kfet/css/history.css +++ b/kfet/static/kfet/css/history.css @@ -20,7 +20,7 @@ z-index:10; } -#history .opegroup { +#history .group { height:30px; line-height:30px; background-color: #c63b52; @@ -30,29 +30,29 @@ overflow:auto; } -#history .opegroup .time { +#history .group .time { width:70px; } -#history .opegroup .trigramme { +#history .group .trigramme { width:55px; text-align:right; } -#history .opegroup .amount { +#history .group .amount { text-align:right; width:90px; } -#history .opegroup .valid_by { +#history .group .valid_by { padding-left:20px } -#history .opegroup .comment { +#history .group .comment { padding-left:20px; } -#history .ope { +#history .entry { position:relative; height:25px; line-height:24px; @@ -61,38 +61,38 @@ overflow:auto; } -#history .ope .amount { +#history .entry .amount { width:50px; text-align:right; } -#history .ope .infos1 { +#history .entry .infos1 { width:80px; text-align:right; } -#history .ope .infos2 { +#history .entry .infos2 { padding-left:15px; } -#history .ope .addcost { +#history .entry .addcost { padding-left:20px; } -#history .ope .canceled { +#history .entry .canceled { padding-left:20px; } -#history div.ope.ui-selected, #history div.ope.ui-selecting { +#history div.entry.ui-selected, #history div.entry.ui-selecting { background-color:rgba(200,16,46,0.6); color:#FFF; } -#history .ope.canceled, #history .transfer.canceled { +#history .entry.canceled { color:#444; } -#history .ope.canceled::before, #history.transfer.canceled::before { +#history .entry.canceled::before { position: absolute; content: ' '; width:100%; @@ -101,19 +101,11 @@ border-top: 1px solid rgba(200,16,46,0.5); } -#history .transfer .amount { - width:80px; -} - -#history .transfer .from_acc { - padding-left:10px; -} - -#history .opegroup .infos { +#history .group .infos { text-align:center; width:145px; } -#history .ope .glyphicon { +#history .entry .glyphicon { padding-left:15px; } diff --git a/kfet/static/kfet/js/history.js b/kfet/static/kfet/js/history.js index 98bc7a2a..540c8239 100644 --- a/kfet/static/kfet/js/history.js +++ b/kfet/static/kfet/js/history.js @@ -2,19 +2,20 @@ function dateUTCToParis(date) { return moment.tz(date, 'UTC').tz('Europe/Paris'); } +// TODO : classifier (later) function KHistory(options = {}) { $.extend(this, KHistory.default_options, options); this.$container = $(this.container); this.$container.selectable({ - filter: 'div.opegroup, div.ope', + filter: 'div.group, div.entry', selected: function (e, ui) { $(ui.selected).each(function () { - if ($(this).hasClass('opegroup')) { - var opegroup = $(this).data('id'); - $(this).siblings('.ope').filter(function () { - return $(this).data('group') == opegroup + if ($(this).hasClass('group')) { + var id = $(this).data('id'); + $(this).siblings('.entry').filter(function () { + return $(this).data('group_id') == id }).addClass('ui-selected'); } }); @@ -25,36 +26,35 @@ function KHistory(options = {}) { this.$container.html(''); }; - this.addOpeGroup = function (opegroup) { - var $day = this._getOrCreateDay(opegroup['at']); - var $opegroup = this._opeGroupHtml(opegroup); + this.add_history_group = function (group) { + var $day = this._get_or_create_day(group['at']); + var $group = this._group_html(group); - $day.after($opegroup); + $day.after($group); - var trigramme = opegroup['on_acc_trigramme']; - var is_cof = opegroup['is_cof']; - var type = opegroup['type'] + var trigramme = group['on_acc_trigramme']; + var is_cof = group['is_cof']; + var type = group['type'] + // TODO : simplifier ça ? switch (type) { case 'operation': - for (let ope of opegroup['opes']) { - var $ope = this._opeHtml(ope, is_cof, trigramme); - $ope.data('group', opegroup['id']); - $ope.data('group_type', type); - $opegroup.after($ope); + for (let ope of group['entries']) { + var $ope = this._ope_html(ope, is_cof, trigramme); + $ope.data('group_id', group['id']); + $group.after($ope); } break; case 'transfer': - for (let transfer of opegroup['opes']) { - var $transfer = this._transferHtml(transfer); - $transfer.data('group', opegroup['id']); - $transfer.data('group_type', type); - $opegroup.after($transfer); + for (let transfer of group['entries']) { + var $transfer = this._transfer_html(transfer); + $transfer.data('group_id', group['id']); + $group.after($transfer); } break; } } - this._opeHtml = function (ope, is_cof, trigramme) { + this._ope_html = function (ope, is_cof, trigramme) { var $ope_html = $(this.template_ope); var parsed_amount = parseFloat(ope['amount']); var amount = amountDisplay(parsed_amount, is_cof, trigramme); @@ -95,12 +95,12 @@ function KHistory(options = {}) { } if (ope['canceled_at']) - this.cancelOpe(ope, $ope_html); + this.cancel_entry(ope, $ope_html); return $ope_html; } - this._transferHtml = function (transfer) { + this._transfer_html = function (transfer) { var $transfer_html = $(this.template_transfer); var parsed_amount = parseFloat(transfer['amount']); var amount = parsed_amount.toFixed(2) + '€'; @@ -113,67 +113,67 @@ function KHistory(options = {}) { .find('.infos2').text(transfer['to_acc']).end(); if (transfer['canceled_at']) - this.cancelOpe(transfer, $transfer_html); + this.cancel_entry(transfer, $transfer_html); return $transfer_html; } - this.cancelOpe = function (ope, $ope = null) { - if (!$ope) - $ope = this.findOpe(ope["id"], ope["type"]); + this.cancel_entry = function (entry, $entry = null) { + if (!$entry) + $entry = this.find_entry(entry["id"], entry["type"]); var cancel = 'Annulé'; - var canceled_at = dateUTCToParis(ope['canceled_at']); - if (ope['canceled_by__trigramme']) - cancel += ' par ' + ope['canceled_by__trigramme']; + var canceled_at = dateUTCToParis(entry['canceled_at']); + if (entry['canceled_by__trigramme']) + cancel += ' par ' + entry['canceled_by__trigramme']; cancel += ' le ' + canceled_at.format('DD/MM/YY à HH:mm:ss'); - $ope.addClass('canceled').find('.canceled').text(cancel); + $entry.addClass('canceled').find('.canceled').text(cancel); } - this._opeGroupHtml = function (opegroup) { - var type = opegroup['type']; + this._group_html = function (group) { + var type = group['type']; switch (type) { case 'operation': - var $opegroup_html = $(this.template_opegroup); - var trigramme = opegroup['on_acc__trigramme']; + var $group_html = $(this.template_opegroup); + var trigramme = group['on_acc__trigramme']; var amount = amountDisplay( - parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); + parseFloat(group['amount']), group['is_cof'], trigramme); break; case 'transfer': - var $opegroup_html = $(this.template_transfergroup); - $opegroup_html.find('.infos').text('Transferts').end() + var $group_html = $(this.template_transfergroup); + $group_html.find('.infos').text('Transferts').end() var trigramme = ''; var amount = ''; break; } - var at = dateUTCToParis(opegroup['at']).format('HH:mm:ss'); - var comment = opegroup['comment'] || ''; + var at = dateUTCToParis(group['at']).format('HH:mm:ss'); + var comment = group['comment'] || ''; - $opegroup_html + $group_html .data('type', type) - .data('id', opegroup['id']) + .data('id', group['id']) .find('.time').text(at).end() .find('.amount').text(amount).end() .find('.comment').text(comment).end() .find('.trigramme').text(trigramme).end(); if (!this.display_trigramme) - $opegroup_html.find('.trigramme').remove(); - $opegroup_html.find('.info').remove(); + $group_html.find('.trigramme').remove(); + $group_html.find('.info').remove(); - if (opegroup['valid_by__trigramme']) - $opegroup_html.find('.valid_by').text('Par ' + opegroup['valid_by__trigramme']); + if (group['valid_by__trigramme']) + $group_html.find('.valid_by').text('Par ' + group['valid_by__trigramme']); - return $opegroup_html; + return $group_html; } - this._getOrCreateDay = function (date) { + this._get_or_create_day = function (date) { var at = dateUTCToParis(date); var at_ser = at.format('YYYY-MM-DD'); var $day = this.$container.find('.day').filter(function () { @@ -185,24 +185,24 @@ function KHistory(options = {}) { return $day.data('date', at_ser).text(at.format('D MMMM YYYY')); } - this.findOpeGroup = function (id, type = "operation") { - return this.$container.find('.opegroup').filter(function () { + this.find_group = function (id, type = "operation") { + return this.$container.find('.group').filter(function () { return ($(this).data('id') == id && $(this).data("type") == type) }); } - this.findOpe = function (id, type = 'operation') { - return this.$container.find('.ope').filter(function () { + this.find_entry = function (id, type = 'operation') { + return this.$container.find('.entry').filter(function () { return ($(this).data('id') == id && $(this).data('type') == type) }); } - this.update_opegroup = function (opegroup, type = "operation") { - var $opegroup = this.findOpeGroup(opegroup['id'], type); - var trigramme = $opegroup.find('.trigramme').text(); + this.update_opegroup = function (group, type = "operation") { + var $group = this.find_group(group['id'], type); + var trigramme = $group.find('.trigramme').text(); var amount = amountDisplay( - parseFloat(opegroup['amount']), opegroup['is_cof'], trigramme); - $opegroup.find('.amount').text(amount); + parseFloat(group['amount']), group['is_cof'], trigramme); + $group.find('.amount').text(amount); } this.fetch = function (fetch_options) { @@ -214,8 +214,8 @@ function KHistory(options = {}) { method: "POST", data: options, }).done(function (data) { - for (let opegroup of data['opegroups']) { - that.addOpeGroup(opegroup); + for (let group of data['groups']) { + that.add_history_group(group); } }); } @@ -239,9 +239,9 @@ function KHistory(options = {}) { }).done(function (data) { window.lock = 0; that.$container.find('.ui-selected').removeClass('ui-selected'); - for (let ope of data["canceled"]) { - ope["type"] = type; - that.cancelOpe(ope); + for (let entry of data["canceled"]) { + entry["type"] = type; + that.cancel_entry(entry); } if (type == "operation") { for (let opegroup of data["opegroups_to_update"]) { @@ -269,8 +269,8 @@ function KHistory(options = {}) { "transfers": [], "operations": [], } - this.$container.find('.ope.ui-selected').each(function () { - type = $(this).data("group_type"); + this.$container.find('.entry.ui-selected').each(function () { + type = $(this).data("type"); opes_to_cancel[`${type}s`].push($(this).data("id")); }); if (opes_to_cancel["transfers"].length > 0 && opes_to_cancel["operations"].length > 0) { @@ -296,9 +296,9 @@ function KHistory(options = {}) { KHistory.default_options = { container: '#history', template_day: '
', - template_opegroup: '
', - template_transfergroup: '
', - template_ope: '
', - template_transfer: '
', + template_opegroup: '
', + template_transfergroup: '
', + template_ope: '
', + template_transfer: '
', display_trigramme: true, } diff --git a/kfet/templates/kfet/kpsul.html b/kfet/templates/kfet/kpsul.html index 0b7f946e..7b292087 100644 --- a/kfet/templates/kfet/kpsul.html +++ b/kfet/templates/kfet/kpsul.html @@ -1253,9 +1253,9 @@ $(document).ready(function() { // ----- OperationWebSocket.add_handler(function(data) { - for (var i=0; i Date: Thu, 26 Dec 2019 18:58:55 +0100 Subject: [PATCH 20/22] Simplify transfer view --- kfet/urls.py | 2 +- kfet/views.py | 15 +++------------ 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/kfet/urls.py b/kfet/urls.py index 88220845..12c06d26 100644 --- a/kfet/urls.py +++ b/kfet/urls.py @@ -252,7 +252,7 @@ urlpatterns = [ # ----- # Transfers urls # ----- - path("transfers/", views.transfers, name="kfet.transfers"), + path("transfers/", views.TransferView.as_view(), name="kfet.transfers"), path("transfers/new", views.transfers_create, name="kfet.transfers.create"), path("transfers/perform", views.perform_transfers, name="kfet.transfers.perform"), path("transfers/cancel", views.cancel_transfers, name="kfet.transfers.cancel"), diff --git a/kfet/views.py b/kfet/views.py index d5ab30a7..70e5d453 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1598,18 +1598,9 @@ config_update = permission_required("kfet.change_config")(SettingsUpdate.as_view # ----- -@teamkfet_required -def transfers(request): - transfers_pre = Prefetch( - "transfers", queryset=(Transfer.objects.select_related("from_acc", "to_acc")) - ) - - transfergroups = ( - TransferGroup.objects.select_related("valid_by") - .prefetch_related(transfers_pre) - .order_by("-at") - ) - return render(request, "kfet/transfers.html", {"transfergroups": transfergroups}) +@method_decorator(teamkfet_required, name="dispatch") +class TransferView(TemplateView): + template_name = "kfet/transfers.html" @teamkfet_required From 9eebc7fb2285bc8dd940ab9041ce4ceef99445ca Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Thu, 23 Apr 2020 13:13:31 +0200 Subject: [PATCH 21/22] Fix: les transferts apparaissent dans l'historique perso --- kfet/views.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/kfet/views.py b/kfet/views.py index 70e5d453..2d13b3d3 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -1404,8 +1404,8 @@ def history_json(request): to_date = request.POST.get("to", None) checkouts = request.POST.getlist("checkouts[]", None) accounts = request.POST.getlist("accounts[]", None) - transfers_only = request.POST.get("transfersonly", None) - opes_only = request.POST.get("opesonly", None) + transfers_only = request.POST.get("transfersonly", False) + opes_only = request.POST.get("opesonly", False) # Construction de la requête (sur les transferts) pour le prefetch @@ -1416,7 +1416,7 @@ def history_json(request): # Le check sur les comptes est dans le prefetch pour les transferts if accounts: transfer_queryset_prefetch = transfer_queryset_prefetch.filter( - Q(from_acc__trigramme__in=accounts) | Q(to_acc__trigramme__in=accounts) + Q(from_acc__in=accounts) | Q(to_acc__in=accounts) ) if not request.user.has_perm("kfet.is_team"): @@ -1458,14 +1458,14 @@ def history_json(request): opegroups = opegroups.filter(at__lt=to_date) transfergroups = transfergroups.filter(at__lt=to_date) if checkouts: - opegroups = opegroups.filter(checkout_id__in=checkouts) + opegroups = opegroups.filter(checkout__in=checkouts) transfergroups = TransferGroup.objects.none() if transfers_only: opegroups = OperationGroup.objects.none() if opes_only: transfergroups = TransferGroup.objects.none() if accounts: - opegroups = opegroups.filter(on_acc_id__in=accounts) + opegroups = opegroups.filter(on_acc__in=accounts) # Un non-membre de l'équipe n'a que accès à son historique if not request.user.has_perm("kfet.is_team"): opegroups = opegroups.filter(on_acc=request.user.profile.account_kfet) From 6362740a77618743c52e664dc18a6aaf17709821 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Thu, 23 Apr 2020 13:54:10 +0200 Subject: [PATCH 22/22] =?UTF-8?q?Fix:=20`history.html`=20=20marche=20(?= =?UTF-8?q?=C3=A0=20peu=20pr=C3=A8s)=20correctement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kfet/templates/kfet/history.html | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/kfet/templates/kfet/history.html b/kfet/templates/kfet/history.html index 204e0d57..94bba48c 100644 --- a/kfet/templates/kfet/history.html +++ b/kfet/templates/kfet/history.html @@ -28,6 +28,9 @@
  • Comptes {{ filter_form.accounts }}
  • +
    + +
    {% endblock %} @@ -71,7 +74,7 @@ $(document).ready(function() { data['accounts'] = accounts; khistory.fetch(data).done(function () { - var nb_opes = khistory.$container.find('.ope:not(.canceled)').length; + var nb_opes = khistory.$container.find('.entry:not(.canceled)').length; $('#nb_opes').text(nb_opes); }); } @@ -106,7 +109,7 @@ $(document).ready(function() { countSelected: "# sur %" }); - $("input").on('dp.change change', function() { + $("#btn-fetch").on('click', function() { khistory.reset(); getHistory(); });