Compare commits

...

10 commits

Author SHA1 Message Date
Ludovic Stephan
6938d5283a Woops 2021-05-05 18:03:56 +02:00
Ludovic Stephan
f4def6d51b Fix tests and simplify checkout data 2021-05-05 18:03:15 +02:00
Ludovic Stephan
b7ebd77afb Adapt checkout json view 2021-05-05 18:03:15 +02:00
Ludovic Stephan
d537fce257 Glue code between kpsul and the new js 2021-05-05 18:03:15 +02:00
Ludovic Stephan
c98bc38c83 New checkout model and manager 2021-05-05 18:03:15 +02:00
Ludovic Stephan
6a704a31a0 Revert "Doc"
This reverts commit 1ab3d11f639520a2a32c7afb004dcbb004e632d6.
2021-05-05 17:59:27 +02:00
Ludovic Stephan
819b875971 Doc 2021-05-05 17:59:27 +02:00
Ludovic Stephan
e4973367c6 Add clean target 2021-05-05 17:59:27 +02:00
Ludovic Stephan
30ac7817cf Switch to minifier 2021-05-05 17:59:27 +02:00
Ludovic Stephan
e42349bc74 Use ES6 modules 2021-05-05 17:59:27 +02:00
15 changed files with 320 additions and 183 deletions

View file

@ -360,7 +360,9 @@ class KPsulAccountForm(forms.ModelForm):
class KPsulCheckoutForm(forms.Form):
checkout = forms.ModelChoiceField(
queryset=None, widget=forms.Select(attrs={"id": "id_checkout_select"})
queryset=None,
widget=forms.Select(attrs={"id": "id_checkout_select"}),
empty_label=None,
)
def __init__(self, *args, **kwargs):

1
kfet/static/kfet/js/kpsul.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,28 @@
# Compilation des fichiers .js de K-Psul en une version minifiée
LIBS = libs/underscore.js libs/backbone.js
MODELS = $(wildcard models/**.js)
MANAGERS = $(wildcard managers/**.js)
ENTRYPOINT = kpsul.js
CONCAT_FILE = kpsul.src.js
TARGET = ../../js/kpsul.min.js
FLAGS =
build: concat minify clean
# For dev use : we don't minify
dev: concat cp clean
concat:
@cat $(LIBS) $(MODELS) $(MANAGERS) $(ENTRYPOINT) > $(CONCAT_FILE)
cp:
@cp $(CONCAT_FILE) $(TARGET)
minify:
terser $(CONCAT_FILE) -o $(TARGET) $(FLAGS)
clean:
@rm $(CONCAT_FILE)

View file

@ -0,0 +1,32 @@
class KPsul {
constructor() {
this.account_manager = new AccountManager(this);
this.checkout_manager = new CheckoutManager(this);
this._$article_select = $("#article_autocomplete")
}
focus(to_focus) {
switch (to_focus) {
case "account":
this.account_manager.focus()
break;
case "articles":
this._$article_select.focus()
break;
}
}
// En attendant de tout convertir : on duplique les fonctions de kpsul.html
// en méthodes de l'objet KPsul
updateBasketAmount() {
window.updateBasketAmount();
}
updateBasketRel() {
window.updateBasketRel();
}
}
$(function () {
kpsul = new KPsul()
})

View file

@ -1,11 +1,13 @@
class AccountManager {
// Classe pour gérer la partie "compte" de K-Psul
// Devrait être la seule interface entre le JS de K-Psul et la logique des comptes.
constructor() {
constructor(kpsul) {
// jQuery elements
this._$input = $("#id_trigramme");
this._$container = $("#account");
this._$article_select = $("#article_autocomplete")
// Parent class
this.kpsul = kpsul
// Subordinated classes
this.account = new Account({ "trigramme": "" });
@ -15,6 +17,10 @@ class AccountManager {
this._init_events();
}
get is_empty() {
return !this.account.is_valid()
}
get data() {
return this.account.toJSON();
}
@ -51,6 +57,10 @@ class AccountManager {
this.update();
}
focus() {
this._$input.focus()
}
update() {
var trigramme = this._$input.val().format_trigramme();
this.account.set({ "trigramme": trigramme })
@ -67,9 +77,9 @@ class AccountManager {
_on_success() {
// On utilise l'objet global window pour accéder aux fonctions nécessaires
this.account.render();
this._$article_select.focus();
window.updateBasketAmount();
window.updateBasketRel();
this.kpsul._$article_select.focus();
this.kpsul.updateBasketAmount();
this.kpsul.updateBasketRel();
}
reset(hard_reset = false) {
@ -141,7 +151,7 @@ class AccountSearch {
var choice_text = choice.text().trim();
var trigramme_regex = /\((.{3})\)$/;
// le match est de la forme [<global match>, <group match>]
trigramme = choice_text.match(trigramme_regex)[1]
var trigramme = choice_text.match(trigramme_regex)[1]
this.manager.set(trigramme);
this.close();
}
@ -151,4 +161,4 @@ class AccountSearch {
this._$dialog.close();
}
}
}
}

View file

@ -0,0 +1,47 @@
class CheckoutManager {
constructor(kpsul) {
// jQuery elements
this._$input = $("#id_checkout_select");
this._$container = $("#checkout");
// Parent class
this.kpsul = kpsul
// Subordinated classes
this.checkout = new Checkout();
// Initialization
this._init_events();
}
_init_events() {
// L'input change ; on met à jour la caisse
this._$input.on("input", () => this.update())
}
update() {
var id = this._$input.val();
this.checkout.set("id", id);
this.checkout.fetch_all({
"success": this._on_success.bind(this),
})
}
ws_update(ws_data) {
for (const entry of ws_data) {
if (entry.id == this.checkout.id)
this.checkout.set("balance", entry.balance);
}
this.checkout.render()
}
_on_success() {
this.checkout.render()
if (this.kpsul.account_manager.is_empty)
this.kpsul.focus("account");
else
this.kpsul.focus("articles");
}
}

View file

@ -1,15 +1,15 @@
var Account = Backbone.Model.extend({
defaults: {
'id': 0,
'name': '',
'email': '',
'is_cof': '',
'promo': '',
'balance': '',
'is_frozen': false,
'departement': '',
'nickname': '',
"id": 0,
"name": "",
"email": "",
"is_cof": "",
"promo": "",
"balance": "",
"is_frozen": false,
"departement": "",
"nickname": "",
},
url: function () {
@ -18,22 +18,22 @@ var Account = Backbone.Model.extend({
reset: function () {
// Réinitialise les attributs du modèle à leurs défaults, sauf le trigramme qui est bind à l'input.
// On n'utilise pas .clear() car on ne veut pas clear le trigramme.
this.set(this.defaults)
},
parse: function (resp, options) {
if (_.has(resp, 'balance')) {
return _.extend(resp, { 'balance': parseFloat(resp.balance) });
if (_.has(resp, "balance")) {
return _.extend(resp, { "balance": parseFloat(resp.balance) });
} else {
return resp;
}
},
view: function () {
var view_class;
if (this.is_empty_account()) {
view_class = EmptyAccountView
} else if (this.get("trigramme") == 'LIQ') {
} else if (this.get("trigramme") == "LIQ") {
view_class = LIQView
} else {
view_class = AccountView
@ -52,8 +52,8 @@ var Account = Backbone.Model.extend({
var AccountView = Backbone.View.extend({
el: '#account',
buttons: '.buttons',
el: "#account",
buttons: ".buttons",
id_field: "#id_on_acc",
props: _.keys(Account.prototype.defaults),
@ -61,7 +61,7 @@ var AccountView = Backbone.View.extend({
get: function (property) {
/* If the function this.get_<property> is defined,
we call it ; else we call this.model.<property>. */
getter_name = `get_${property}`;
var getter_name = `get_${property}`;
if (_.functions(this).includes(getter_name))
return this[getter_name]()
else
@ -69,7 +69,7 @@ var AccountView = Backbone.View.extend({
},
get_is_cof: function () {
return this.model.get("is_cof") ? 'COF' : 'Non-COF';
return this.model.get("is_cof") ? "COF" : "Non-COF";
},
get_balance: function () {
@ -84,9 +84,9 @@ var AccountView = Backbone.View.extend({
} else if (this.model.get("balance") < 0) {
return 'neg';
} else if (this.model.get("balance") <= 5) {
return 'low';
return "low";
} else {
return 'ok';
return "ok";
}
},
@ -114,25 +114,25 @@ var LIQView = AccountView.extend({
},
attr_data_balance: function () {
return 'ok';
return "ok";
}
})
var EmptyAccountView = AccountView.extend({
get: function () {
return '';
return "";
},
attr_data_balance: function () {
return '';
return "";
},
get_buttons: function () {
/* Léger changement de fonctionnement :
on affiche *toujours* le bouton de recherche si
le compte est invalide */
buttons = '<button class="btn btn-primary search" title="Rechercher"><span class="glyphicon glyphicon-search"></span></button>';
trigramme = this.model.get("trigramme")
var buttons = `<button class="btn btn-primary search" title="Rechercher"><span class="glyphicon glyphicon-search"></span></button>`;
var trigramme = this.model.get("trigramme")
if (trigramme.is_valid_trigramme()) {
trigramme = encodeURIComponent(trigramme);
var url_base = django_urls["kfet.account.create"]();
@ -142,4 +142,4 @@ var EmptyAccountView = AccountView.extend({
return buttons
}
})
})

View file

@ -0,0 +1,118 @@
var Statement = Backbone.Model.extend({
defaults: {
"id": 0,
"at": "",
"balance": 0,
"by": "",
"checkout_id": 0,
},
parse: function (resp) {
return _.extend(resp, { "balance": parseFloat(resp.balance) });
},
is_valid: function () {
return this.id != 0;
},
});
var Checkout = Backbone.Model.extend({
defaults: {
"id": 0,
"balance": 0,
"last_statement": new Statement()
},
url: function () {
return django_urls["kfet.kpsul.checkout_data"](this.id);
},
fetch_all: function (options) {
var that = this;
var success = options.success
options.success = function (model, resp, options) {
ls = that.get("last_statement");
ls.set(ls.parse(resp.last_statement));
success.call(options.context, model, resp, options);
}
return this.fetch(options)
},
is_valid: function () {
return this.id != 0;
},
parse: function (resp, options) {
return _(resp).pick(_.keys(_.omit(this.defaults, "last_statement")))
},
render: function () {
if (this.is_valid()) {
checkout_view = new CheckoutView({ "model": this });
statement_view = new StatementView({ "model": this.get("last_statement") });
checkout_view.render();
statement_view.render();
} else {
checkout_view = new EmptyCheckoutView({ "model": this });
checkout_view.render();
}
},
reset: function () {
this.set(this.defaults)
},
});
var CheckoutView = Backbone.View.extend({
el: "#checkout",
buttons: ".buttons",
id_field: "#id_checkout",
props: _.keys(Checkout.prototype.defaults),
render: function () {
for (let prop of this.props) {
selector = "#checkout-" + prop;
this.$(selector).text(this.model.get(prop));
}
this.$(this.buttons).html(this.get_buttons());
$(this.id_field).val(this.model.id);
},
get_buttons: function () {
var url_ls_create = django_urls["kfet.checkoutstatement.create"](this.model.id)
var url_update = django_urls["kfet.checkout.update"](this.model.id)
buttons = `<a class="btn btn-primary" href="${url_ls_create}" title="Effectuer un relevé" target="_blank"><span class="glyphicon glyphicon-euro"></span></a>`;
buttons += `<a class="btn btn-primary" href="${url_update}" title="Modifier" target="_blank"><span class="glyphicon glyphicon-cog"></span></a>`;
return buttons
}
})
var EmptyCheckoutView = CheckoutView.extend({
get_buttons: function () {
return "";
},
})
var StatementView = Backbone.View.extend({
el: "#last_statement",
render: function () {
var at = moment.tz(this.model.get("at"), "UTC");
var by = this.model.get("by")
var balance = this.model.get("balance")
at = at.tz('Europe/Paris').format('DD/MM/YY à HH:mm');
title = "<b>Dernier relevé : </b>"
content = `<span id="last_statement_text">${balance}€ le ${at} par ${by}</span>`
this.$el.html(title + "<br>" + content)
}
})

View file

@ -7,10 +7,7 @@
<script type="text/javascript" src="{% static 'kfet/vendor/moment/moment-timezone-with-data-2012-2022.min.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/history.js' %}"></script>
<script type="text/javascript" src="{% url 'js_reverse' %}" ></script>
<script type="text/javascript" src="{% static 'kfet/vendor/underscore-min.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/vendor/backbone-min.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/account.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/kpsul.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/kpsul.min.js' %}"></script>
{% endblock %}
{% block title %}K-Psul{% endblock %}
@ -209,12 +206,7 @@ $(document).ready(function() {
});
}
// -----
// Account data management
// -----
var account_manager = new AccountManager();
var triInput = $('#id_trigramme');
@ -224,90 +216,7 @@ $(document).ready(function() {
// Initializing
var checkout_container = $('#checkout');
var checkoutInput = $('#id_checkout_select');
var checkout_data = {}
var checkout_data_default = {
'id' : 0,
'name': '',
'balance' : '',
'valid_from': '',
'valid_to' : '',
'last_statement_balance': '',
'last_statement_at' : '',
'last_statement_by_trigramme' : '',
'last_statement_by_first_name': '',
'last_statement_by_last_name' : '' ,
}
var last_statement_container = $('#last_statement');
var last_statement_html_default = '<b>Dernier relevé: </b><br><span id="checkout-last_statement_balance"></span>€ le <span id="checkout-last_statement_at"></span> par <span id="checkout-last_statement_by_trigramme"></span>';
// If only one checkout is available, select it
var checkout_choices = checkoutInput.find("option[value!='']");
if (checkout_choices.length == 1) {
$(checkout_choices[0]).prop("selected", true);
}
// Display data
function displayCheckoutData() {
var at_formated = '';
if (checkout_data['last_statement_at']) {
last_statement_container.html(last_statement_html_default);
var at = moment.tz(checkout_data['last_statement_at'], 'UTC');
at_formated = at.tz('Europe/Paris').format('DD/MM/YY à HH:mm');
} else {
last_statement_container.html('');
}
for (var elem in checkout_data) {
$('#checkout-'+elem).text(checkout_data[elem]);
}
$('#checkout-last_statement_at').text(at_formated);
var buttons = '';
if (checkout_data['id'] !== 0) {
var url_base = "{% url 'kfet.checkoutstatement.create' 1 %}";
url_base = url_base.substr(0,url_base.length - 16);
buttons += '<a class="btn btn-primary" href="'+url_base+checkout_data['id']+'/statements/add" title="Effectuer un relevé" target="_blank"><span class="glyphicon glyphicon-euro"></span></a>';
buttons += '<a class="btn btn-primary" href="'+url_base+checkout_data['id']+'" title="Modifier" target="_blank"><span class="glyphicon glyphicon-cog"></span></a>';
}
checkout_container.find('.buttons').html(buttons);
}
// Clear data
function resetCheckout() {
checkout_data = checkout_data_default;
$('#id_checkout').val(0);
checkoutInput.find('option:first').prop('selected', true);
displayCheckoutData();
}
// Store data
function storeCheckoutData(data) {
checkout_data = $.extend({}, checkout_data_default, data);
$('#id_checkout').val(checkout_data['id']);
displayCheckoutData();
}
// Retrieve data
function retrieveCheckoutData(id) {
$.ajax({
dataType: "json",
url : "{% url 'kfet.kpsul.checkout_data' %}",
method : "POST",
data : { 'pk': id },
})
.done(function(data) { storeCheckoutData(data) })
.fail(function() { resetCheckout() });
}
// Event listener
checkoutInput.on('change', function() {
retrieveCheckoutData(checkoutInput.val());
if (account_manager.data['trigramme']) {
articleSelect.focus().select();
} else {
triInput.focus().select();
}
});
// -----
// Auth
// -----
@ -637,11 +546,11 @@ $(document).ready(function() {
var amount_euro = - article_data[3] * nb ;
if (settings['addcost_for']
&& settings['addcost_amount']
&& account_manager.data['trigramme'] != settings['addcost_for']
&& kpsul.account_manager.data['trigramme'] != settings['addcost_for']
&& article_data[5])
amount_euro -= settings['addcost_amount'] * nb;
var reduc_divisor = 1;
if (account_manager.data['is_cof'] && article_data[6])
if (kpsul.account_manager.data['is_cof'] && article_data[6])
reduc_divisor = 1 + settings['subvention_cof'] / 100;
return (amount_euro / reduc_divisor).toFixed(2);
}
@ -664,7 +573,7 @@ $(document).ready(function() {
.attr('data-opeindex', index)
.find('.number').text('('+nb+'/'+article_data[4]+')').end()
.find('.name').text(article_data[0]).end()
.find('.amount').text(amountToUKF(amount_euro, account_manager.data['is_cof'], false));
.find('.amount').text(amountToUKF(amount_euro, kpsul.account_manager.data['is_cof'], false));
basket_container.prepend(article_basket_html);
if (is_low_stock(id, nb))
article_basket_html.find('.lowstock')
@ -690,7 +599,7 @@ $(document).ready(function() {
.attr('data-opeindex', index)
.find('.number').text(amount+"€").end()
.find('.name').text('Charge').end()
.find('.amount').text(amountToUKF(amount, account_manager.data['is_cof'], false));
.find('.amount').text(amountToUKF(amount, kpsul.account_manager.data['is_cof'], false));
basket_container.prepend(deposit_basket_html);
updateBasketRel();
}
@ -703,7 +612,7 @@ $(document).ready(function() {
.attr('data-opeindex', index)
.find('.number').text(amount+"€").end()
.find('.name').text('Édition').end()
.find('.amount').text(amountToUKF(amount, account_manager.data['is_cof'], false));
.find('.amount').text(amountToUKF(amount, kpsul.account_manager.data['is_cof'], false));
basket_container.prepend(deposit_basket_html);
updateBasketRel();
}
@ -716,7 +625,7 @@ $(document).ready(function() {
.attr('data-opeindex', index)
.find('.number').text(amount+"€").end()
.find('.name').text('Retrait').end()
.find('.amount').text(amountToUKF(amount, account_manager.data['is_cof'], false));
.find('.amount').text(amountToUKF(amount, kpsul.account_manager.data['is_cof'], false));
basket_container.prepend(withdraw_basket_html);
updateBasketRel();
}
@ -772,7 +681,7 @@ $(document).ready(function() {
var amount = $(this).find('#id_form-'+opeindex+'-amount');
if (!deleted && type == "purchase")
amount.val(amountEuroPurchase(article_id, article_nb));
basket_container.find('[data-opeindex='+opeindex+'] .amount').text(amountToUKF(amount.val(), account_manager.data['is_cof'], false));
basket_container.find('[data-opeindex='+opeindex+'] .amount').text(amountToUKF(amount.val(), kpsul.account_manager.data['is_cof'], false));
});
}
@ -780,7 +689,7 @@ $(document).ready(function() {
function updateBasketRel() {
var basketrel_html = '';
if (account_manager.data['trigramme'] == 'LIQ' && !isBasketEmpty()) {
if (kpsul.account_manager.data['trigramme'] == 'LIQ' && !isBasketEmpty()) {
var amount = - getAmountBasket();
basketrel_html += '<div>Total: '+amount.toFixed(2)+' €</div>';
if (amount < 5)
@ -789,11 +698,11 @@ $(document).ready(function() {
basketrel_html += '<div>Sur 10€: '+ (10-amount).toFixed(2) +' €</div>';
if (amount < 20)
basketrel_html += '<div>Sur 20€: '+ (20-amount).toFixed(2) +' €</div>';
} else if (account_manager.data['trigramme'] != '' && !isBasketEmpty()) {
} else if (kpsul.account_manager.data['trigramme'] != '' && !isBasketEmpty()) {
var amount = getAmountBasket();
var amountUKF = amountToUKF(amount, account_manager.data['is_cof'], false);
var newBalance = account_manager.data['balance'] + amount;
var newBalanceUKF = amountToUKF(newBalance, account_manager.data['is_cof'], true);
var amountUKF = amountToUKF(amount, kpsul.account_manager.data['is_cof'], false);
var newBalance = kpsul.account_manager.data['balance'] + amount;
var newBalanceUKF = amountToUKF(newBalance, kpsul.account_manager.data['is_cof'], true);
basketrel_html += '<div>Total: '+amountUKF+'</div>';
basketrel_html += '<div>Nouveau solde: '+newBalanceUKF+'</div>';
if (newBalance < 0)
@ -814,7 +723,7 @@ $(document).ready(function() {
var nb_before = formset_container.find("#id_form-"+opeindex+"-article_nb").val();
var nb_after = parseInt(nb_before) + parseInt(nb);
var amountEuro_after = amountEuroPurchase(id, nb_after);
var amountUKF_after = amountToUKF(amountEuro_after, account_manager.data['is_cof']);
var amountUKF_after = amountToUKF(amountEuro_after, kpsul.account_manager.data['is_cof']);
if (type == 'purchase') {
if (nb_after == 0) {
@ -1036,7 +945,7 @@ $(document).ready(function() {
function updatePreviousOp() {
var previousop_html = '';
var trigramme = account_manager.data['trigramme'];
var trigramme = kpsul.account_manager.data['trigramme'];
previousop_html += '<div class="trigramme">Trigramme : '+trigramme+'</div>';
previousop_html += basketrel_container.html();
previousop_container.html(previousop_html);
@ -1143,12 +1052,9 @@ $(document).ready(function() {
khistory.add_history_group(data['groups'][i]);
}
}
for (var i=0; i<data['checkouts'].length; i++) {
if (checkout_data['id'] == data['checkouts'][i]['id']) {
checkout_data['balance'] = data['checkouts'][i]['balance'];
displayCheckoutData();
}
}
kpsul.checkout_manager.ws_update(data["checkouts"]);
for (var i=0; i<data['articles'].length; i++) {
var article = data['articles'][i];
var article_line = articles_container.find('#data-article-'+article.id);
@ -1178,7 +1084,7 @@ $(document).ready(function() {
// Reset functions
function coolReset(give_tri_focus=true) {
account_manager.reset(true);
kpsul.account_manager.reset(true);
resetBasket();
resetComment();
resetSelectable();
@ -1188,7 +1094,7 @@ $(document).ready(function() {
function hardReset(give_tri_focus=true) {
coolReset(give_tri_focus);
checkoutInput.trigger('change');
kpsul.checkout_manager.update();
resetArticles();
resetPreviousOp();
khistory.reset();
@ -1233,7 +1139,7 @@ $(document).ready(function() {
case 113:
if (e.shiftKey) {
// Shift+F2 - Account reset
account_manager.reset(true);
kpsul.account_manager.reset(true);
triInput.focus();
} else {
// F2 - Basket reset

View file

@ -28,9 +28,7 @@ class KPsulCheckoutFormTests(TestCase):
def test_checkout(self):
checkout_f = self.form.fields["checkout"]
self.assertListEqual(
list(checkout_f.choices), [("", "---------"), (self.c1.pk, "C1")]
)
self.assertListEqual(list(checkout_f.choices), [(self.c1.pk, "C1")])
@mock.patch("django.utils.timezone.now")
def test_checkout_valid(self, mock_now):
@ -44,4 +42,4 @@ class KPsulCheckoutFormTests(TestCase):
form = KPsulCheckoutForm()
checkout_f = form.fields["checkout"]
self.assertListEqual(list(checkout_f.choices), [("", "---------")])
self.assertListEqual(list(checkout_f.choices), [])

View file

@ -1683,11 +1683,19 @@ class KPsulCheckoutDataViewTests(ViewTestCaseMixin, TestCase):
url_name = "kfet.kpsul.checkout_data"
url_expected = "/k-fet/k-psul/checkout_data"
http_methods = ["POST"]
http_methods = ["GET"]
auth_user = "team"
auth_forbidden = [None, "user"]
@property
def url_kwargs(self):
return {"pk": self.checkout.pk}
@property
def url_expected(self):
return "/k-fet/k-psul/checkout_data/{}".format(self.checkout.pk)
def setUp(self):
super().setUp()
self.checkout = Checkout.objects.create(
@ -1704,7 +1712,7 @@ class KPsulCheckoutDataViewTests(ViewTestCaseMixin, TestCase):
content = json.loads(r.content.decode("utf-8"))
expected = {"name": "Checkout", "balance": "10.00"}
expected = {"balance": "10.00"}
self.assertDictContainsSubset(expected, content)
@ -1714,14 +1722,7 @@ class KPsulCheckoutDataViewTests(ViewTestCaseMixin, TestCase):
[
"balance",
"id",
"name",
"valid_from",
"valid_to",
"last_statement_at",
"last_statement_balance",
"last_statement_by_first_name",
"last_statement_by_last_name",
"last_statement_by_trigramme",
"last_statement",
]
),
)

View file

@ -208,7 +208,7 @@ urlpatterns = [
# -----
path("k-psul/", views.kpsul, name="kfet.kpsul"),
path(
"k-psul/checkout_data",
"k-psul/checkout_data/<int:pk>",
views.kpsul_checkout_data,
name="kfet.kpsul.checkout_data",
),

View file

@ -927,20 +927,10 @@ def account_read_json(request, trigramme):
@teamkfet_required
def kpsul_checkout_data(request):
pk = request.POST.get("pk", 0)
if not pk:
pk = 0
def kpsul_checkout_data(request, pk):
data = (
Checkout.objects.annotate(
last_statement_by_first_name=F(
"statements__by__cofprofile__user__first_name"
),
last_statement_by_last_name=F(
"statements__by__cofprofile__user__last_name"
),
last_statement_by_trigramme=F("statements__by__trigramme"),
last_statement_by=F("statements__by__trigramme"),
last_statement_balance=F("statements__balance_new"),
last_statement_at=F("statements__at"),
)
@ -951,20 +941,24 @@ def kpsul_checkout_data(request):
.order_by("statements__at")
.values(
"id",
"name",
"balance",
"valid_from",
"valid_to",
"last_statement_balance",
"last_statement_at",
"last_statement_by_trigramme",
"last_statement_by_last_name",
"last_statement_by_first_name",
"last_statement_by",
)
.last()
)
if data is None:
raise Http404
prefix = "last_statement_"
ls_dict = {}
for (key, value) in list(data.items()):
if key.startswith(prefix):
ls_dict[key[len(prefix) :]] = value
del data[key]
data["last_statement"] = ls_dict
return JsonResponse(data)