890be9b343
- nouvelle classe - Account: stocke, sert et récupère les données associées à un compte - nouvelle classe - AccountManager: interface pour le management de la partie Account de K-Psul - nouvelle classe - AccountSearch: module de recherche d'un compte - nouvelles classes - AccountFormatter, StandardAccountFormatter, LIQAccountFormatter: styles de formattage des données d'un compte - désactive l'autocomplétion dans la recherche d'un compte - fix #89: "Entrée" dans le champ de trigramme met le compte LIQ
1563 lines
50 KiB
HTML
1563 lines
50 KiB
HTML
{% extends 'kfet/base.html' %}
|
|
{% load staticfiles %}
|
|
|
|
{% block extra_head %}
|
|
<link rel="stylesheet" style="text/css" href="{% static 'kfet/css/jquery-ui.min.css' %}">
|
|
<link rel="stylesheet" style="text/css" href="{% static 'kfet/css/kpsul_grid.css' %}">
|
|
<script src="{% static "autocomplete_light/autocomplete.js" %}" type="text/javascript"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/js.cookie.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/reconnecting-websocket.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/jquery-ui.min.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/jquery-confirm.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/moment.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/moment-fr.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/moment-timezone-with-data-2010-2020.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/kfet.js' %}"></script>
|
|
<script type="text/javascript" src="{% static 'kfet/js/history.js' %}"></script>
|
|
{% endblock %}
|
|
|
|
{% block title %}K-Psul{% endblock %}
|
|
|
|
{% block content-header %}{% endblock %}
|
|
|
|
{% block help %}
|
|
|
|
<div class="row">
|
|
<div class="col-md-6">
|
|
<div class="block">
|
|
<h4>Opérations</h4>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F3</b></div>
|
|
<div class="col-xs-9">Charge</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>Shift + F3</b></div>
|
|
<div class="col-xs-9">Retrait</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F8</b></div>
|
|
<div class="col-xs-9">Edition</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<div class="block">
|
|
<h4>Général</h4>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F1</b></div>
|
|
<div class="col-xs-9">Reset</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F2</b></div>
|
|
<div class="col-xs-9">Reset panier</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>Shift + F2</b></div>
|
|
<div class="col-xs-9">Reset compte</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F9</b></div>
|
|
<div class="col-xs-9">Majoration</div>
|
|
</div>
|
|
<div class="row">
|
|
<div class="col-xs-3"><b>F10</b></div>
|
|
<div class="col-xs-9">Hard reset</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{% endblock %}
|
|
|
|
{% block content %}
|
|
|
|
{% include 'kfet/base_messages.html' %}
|
|
|
|
<div class="row kpsul_top">
|
|
<div class="col-sm-8">
|
|
<div class="row" id="account">
|
|
<div class="col-lg-3 col-xs-4" id="account_form">
|
|
{{ trigramme_form.trigramme }}
|
|
</div>
|
|
<div class="col-lg-9 col-xs-8" id="account_data">
|
|
<div id="account-balance" class="data_line"></div>
|
|
<div id="account-name" class="data_line"></div>
|
|
<div id="account-nickname" class="data_line"></div>
|
|
<div class="data_line">
|
|
<span id="account-is_cof"></span>
|
|
<span id="account-departement"></span>
|
|
<span id="account-promo"></span>
|
|
</div>
|
|
<div id="account-email" class="data_line"></div>
|
|
<div class="buttons">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="col-sm-4" id="checkout">
|
|
<div id="checkout_form">
|
|
{{ checkout_form.checkout }}
|
|
</div>
|
|
<div id="checkout_data">
|
|
<div>
|
|
<b>En caisse:</b> <span id="checkout-balance"></span> €
|
|
</div>
|
|
<div id="last_statement">
|
|
</div>
|
|
<div class="buttons">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="row kpsul_middle">
|
|
<div class="col-sm-8 kpsul_middle_left_col">
|
|
<div class="kpsul_middle_left">
|
|
<div class="kpsul_middle_left_top">
|
|
<div id="special_operations">
|
|
<button role="button" class="btn" id="operation_deposit">Charge (F3)</button>
|
|
<button role="button" class="btn" id="operation_withdraw">Retrait (Shift+F3)</button>
|
|
<button role="button" class="btn" id="cool_reset">RAZ (F1)</button>
|
|
<button role="button" class="btn" id="ask_addcost">Major. (F9)</button>
|
|
</div>
|
|
<div id="article_selection">
|
|
<input type="text" id="article_autocomplete" autocomplete="off">
|
|
<input type="number" id="article_number" step="1" min="1">
|
|
<input type="hidden" id="article_id" value="">
|
|
</div>
|
|
<div id="articles_data">
|
|
<table>
|
|
<tbody>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
<div class="row kpsul_middle_left_bottom">
|
|
<div class="col-sm-6">
|
|
<div id="basket">
|
|
<table id="basket_table">
|
|
</table>
|
|
</div>
|
|
</div>
|
|
<div class="col-sm-3">
|
|
<div id="basket_rel">
|
|
</div>
|
|
</div>
|
|
<div class="col-sm-3">
|
|
<div id="previous_op">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="col-sm-4 kpsul_middle_right_col">
|
|
<div id="history">
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="history2">
|
|
</div>
|
|
|
|
<form id="operationgroup_form" style="display:none;">{{ operationgroup_form }}</form>
|
|
<form id="operation_formset" style="display:none;">{{ operation_formset }}</form>
|
|
|
|
<div style="display:none;" id="operation_empty_html" data-opeindex="__prefix__">
|
|
{{ operation_formset.empty_form }}
|
|
</div>
|
|
|
|
{% csrf_token %}
|
|
|
|
<script type="text/javascript">
|
|
|
|
function intCheck(v) {
|
|
return Number.parseInt(v);
|
|
}
|
|
|
|
function floatCheck(v) {
|
|
if (typeof v === 'number')
|
|
return v;
|
|
return Number.parseFloat(v);
|
|
}
|
|
|
|
function booleanCheck(v) {
|
|
return v == true;
|
|
}
|
|
|
|
function functionCheck(v) {
|
|
if (typeof v === 'function')
|
|
return v;
|
|
return function(){};
|
|
}
|
|
|
|
class Config {
|
|
|
|
static getAll() {
|
|
if (typeof window.config === 'undefined')
|
|
window.config = {};
|
|
return window.config;
|
|
}
|
|
|
|
static reset(callback) {
|
|
$.ajax({
|
|
dataType: "json",
|
|
url : "{% url 'kfet.kpsul.get_settings' %}",
|
|
method : "POST",
|
|
})
|
|
.done(function(data) {
|
|
Config.addcost_for = data['addcost_for'];
|
|
Config.addcost_amount = data['addcost_amount'];
|
|
Config.subvention_cof = data['subvention_cof'];
|
|
})
|
|
.always(callback);
|
|
}
|
|
|
|
static set addcost_for(v) {
|
|
Config.getAll().addcost_for = v;
|
|
}
|
|
|
|
static set addcost_amount(v) {
|
|
Config.getAll().addcost_amount = floatCheck(v);
|
|
}
|
|
|
|
static set subvention_cof(v) {
|
|
Config.getAll().subvention_cof = floatCheck(v);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
String.prototype.formatTri = function() {
|
|
return this.toUpperCase();
|
|
}
|
|
|
|
String.prototype.isValidTri = function() {
|
|
var pattern = /^[^a-z]{3}$/;
|
|
return pattern.test(this);
|
|
}
|
|
|
|
String.prototype.urlify = function() {
|
|
return encodeURIComponent(this);
|
|
}
|
|
|
|
|
|
class Account {
|
|
|
|
constructor() {
|
|
$.extend(this, this.constructor.default_data);
|
|
}
|
|
|
|
static get default_data() {
|
|
return {
|
|
'id': 0, 'trigramme': '', 'name': '', 'nickname': '', 'email': '',
|
|
'is_cof' : false, 'promo': '', 'balance': 0, 'is_frozen': false,
|
|
'departement': '',
|
|
};
|
|
};
|
|
|
|
get id() { return this._id; }
|
|
get balance() { return this._balance; }
|
|
get is_cof() { return this._is_cof; }
|
|
get is_frozen() { return this._is_frozen; }
|
|
|
|
set id(v) { this._id = intCheck(v); }
|
|
set balance(v) { this._balance = floatCheck(v); }
|
|
set is_cof(v) { this._is_cof = booleanCheck(v); }
|
|
set is_frozen(v) { this._is_frozen = booleanCheck(v); }
|
|
|
|
from(data, callback) {
|
|
callback = functionCheck(callback);
|
|
$.extend(this, Account.default_data, data);
|
|
callback();
|
|
}
|
|
|
|
fromAPI(trigramme, on_success, on_error) {
|
|
on_error = functionCheck(on_error);
|
|
var that = this;
|
|
$.ajax({
|
|
dataType: "json",
|
|
url : "{% url 'kfet.account.read.json' %}",
|
|
method : "POST",
|
|
data : { trigramme: trigramme },
|
|
})
|
|
.done((data) => this.from(data, on_success))
|
|
.fail(on_error);
|
|
}
|
|
|
|
reset() {
|
|
this.from({});
|
|
}
|
|
|
|
}
|
|
|
|
|
|
class AccountFormatter {
|
|
|
|
constructor(account) {
|
|
this._account = account;
|
|
}
|
|
|
|
static get _data_balance_default() { return ''; }
|
|
static get _data_balance_frozen() { return 'frozen'; }
|
|
static get _data_balance_ok() { return 'ok'; }
|
|
static get _data_balance_low() { return 'low'; }
|
|
static get _data_balance_neg() { return 'neg'; }
|
|
|
|
get str_balance_ukf() { return ''; }
|
|
get str_is_cof() { return ''; }
|
|
get data_balance() { return this.constructor._data_balance_default; }
|
|
|
|
display($container) {
|
|
var a = this._account;
|
|
$container
|
|
.find('#account-balance')
|
|
.text(this.str_balance_ukf)
|
|
.end()
|
|
.find('#account-is_cof')
|
|
.text(this.str_is_cof)
|
|
.end()
|
|
.find('#account-name')
|
|
.text(a.name)
|
|
.end()
|
|
.find('#account-nickname')
|
|
.text(a.nickname)
|
|
.end()
|
|
.find('#account-departement')
|
|
.text(a.departement)
|
|
.end()
|
|
.find('#account-promo')
|
|
.text(a.promo)
|
|
.end()
|
|
.find('#account-email')
|
|
.text(a.email)
|
|
.end();
|
|
$container.attr('data-balance', this.data_balance);
|
|
}
|
|
}
|
|
|
|
|
|
class StandardAccountFormatter extends AccountFormatter {
|
|
|
|
get str_balance_ukf() {
|
|
return amountToUKF(this._account.balance, this._account.is_cof);
|
|
}
|
|
|
|
get str_is_cof() {
|
|
return this._account.is_cof ? 'COF' : 'Non-COF';
|
|
}
|
|
|
|
get data_balance() {
|
|
var is_frozen = this._account.is_frozen;
|
|
var balance = this._account.balance;
|
|
if (is_frozen) { return this.constructor._data_balance_frozen; }
|
|
else if (balance >= 5) { return this.constructor._data_balance_ok; }
|
|
else if (balance >= 0) { return this.constructor._data_balance_low; }
|
|
else /* balance < 0 */ { return this.constructor._data_balance_neg; }
|
|
}
|
|
|
|
}
|
|
|
|
|
|
class LIQAccountFormatter extends AccountFormatter {
|
|
|
|
get str_balance_ukf() { return ''; }
|
|
get str_is_cof() { return ''; }
|
|
get data_balance() { return this.constructor.data_balance_ok; }
|
|
|
|
}
|
|
|
|
|
|
class AccountManager {
|
|
|
|
constructor(env) {
|
|
this._env = env; // temporary, should be a link to "kpsul_manager" or something like this
|
|
this.account = new Account();
|
|
this.search = new AccountSearch(this);
|
|
this._$container = $('#account');
|
|
this._$input_trigramme = $('#id_trigramme');
|
|
|
|
this._init_events();
|
|
}
|
|
|
|
get is_empty() {
|
|
return this.account.id == 0;
|
|
}
|
|
|
|
get formatter() {
|
|
if (this.account.trigramme == 'LIQ') { return LIQAccountFormatter; }
|
|
else if (!this.is_empty) { return StandardAccountFormatter; }
|
|
else /* account is empty */ { return AccountFormatter; }
|
|
}
|
|
|
|
display() {
|
|
this._display_data();
|
|
this._display_buttons();
|
|
}
|
|
|
|
_display_data() {
|
|
(new (this.formatter)(this.account)).display(this._$container);
|
|
}
|
|
|
|
_display_buttons() {
|
|
// dirty
|
|
|
|
var buttons = '';
|
|
|
|
if (this.is_empty) {
|
|
var trigramme = this._$input_trigramme.val().formatTri();
|
|
if (trigramme.isValidTri()) {
|
|
var url_base = "{% url 'kfet.account.create' %}";
|
|
var url = url_base + '?trigramme=' + trigramme.urlify();
|
|
buttons += '<a href="'+url+'" class="btn btn-primary" target="_blank" title="Créer ce compte"><span class="glyphicon glyphicon-plus"></span></a>';
|
|
} else { /* trigramme input is empty or invalid */
|
|
buttons += '<button class="btn btn-primary search" title="Rechercher"><span class="glyphicon glyphicon-search"></span></button>';
|
|
}
|
|
} else { /* an account is loaded */
|
|
var url_pattern = "{% url 'kfet.account.read' 'LIQ' %}";
|
|
var url_base = url_pattern.substr(0, url_pattern.length - 3); /* dirty */
|
|
var url = url_base + this.account.trigramme.urlify();
|
|
buttons += '<a href="'+url+'" class="btn btn-primary" target="_blank" title="Modifier ce compte"><span class="glyphicon glyphicon-cog"></span></a>';
|
|
}
|
|
|
|
this._$container.find('.buttons').html(buttons);
|
|
}
|
|
|
|
update() {
|
|
var trigramme = this._$input_trigramme.val().formatTri();
|
|
if (trigramme.isValidTri()) {
|
|
this.account.fromAPI(trigramme,
|
|
() => this.on_api_success(),
|
|
() => this.reset_data()
|
|
);
|
|
} else {
|
|
this.reset_data();
|
|
}
|
|
}
|
|
|
|
on_api_success() {
|
|
$('#id_on_acc').val(this.account.id);
|
|
this.display();
|
|
|
|
this._env.articleSelect.focus();
|
|
this._env.updateBasketAmount();
|
|
this._env.updateBasketRel();
|
|
}
|
|
|
|
_init_events() {
|
|
var that = this;
|
|
|
|
this._$input_trigramme
|
|
.on('input', () => this.update()); // doesn't want "that.update" instead of "() => this.update()"
|
|
|
|
this._$input_trigramme
|
|
.on('keydown', function(e) {
|
|
// keys: 13:Enter|40:Arrow-Down
|
|
if (e.keyCode == 13 || e.keyCode == 40) {
|
|
that._$input_trigramme.val('LIQ');
|
|
that.update();
|
|
}
|
|
});
|
|
|
|
/* open search on button click */
|
|
this._$container
|
|
.on('click', '.search', () => this.search.open());
|
|
|
|
/* open search on Ctrl-F */
|
|
this._$container
|
|
.on('keydown', function(e) {
|
|
if (e.which == 70 && e.ctrlKey) {
|
|
that.search.open();
|
|
e.preventDefault() ;
|
|
}
|
|
});
|
|
}
|
|
|
|
reset() {
|
|
$('#id_on_acc').val(0);
|
|
this._$input_trigramme.val('');
|
|
this.reset_data();
|
|
}
|
|
|
|
reset_data() {
|
|
this.account.reset();
|
|
this.display();
|
|
}
|
|
|
|
}
|
|
|
|
class AccountSearch {
|
|
|
|
constructor(account_manager) {
|
|
this.account_manager = account_manager;
|
|
|
|
this._content = '<input type="text" name="q" id="search_autocomplete" autocomplete="off" spellcheck="false" autofocus><div id="account_results"></div>' ;
|
|
this._input = '#search_autocomplete';
|
|
this._results_container = '#account_results';
|
|
}
|
|
|
|
open() {
|
|
console.log('plop');
|
|
var that = this;
|
|
this._$dialog = $.dialog({
|
|
title: 'Recherche de compte',
|
|
content: this._content,
|
|
backgroundDismiss: true,
|
|
animation: 'top',
|
|
closeAnimation: 'bottom',
|
|
keyboardEnabled: true,
|
|
onOpen: function() {
|
|
that._$input = $(that._input);
|
|
that._$results_container = $(that._results_container);
|
|
that._init_input();
|
|
that._init_events();
|
|
}
|
|
});
|
|
}
|
|
|
|
_init_input() {
|
|
var that = this;
|
|
this._$input.yourlabsAutocomplete({
|
|
url: '{% url "kfet.account.search.autocomplete" %}',
|
|
minimumCharacters: 2,
|
|
id: 'search_autocomplete',
|
|
choiceSelector: '.choice',
|
|
placeholder: "Chercher un utilisateur K-Fêt",
|
|
container: that._$results_container,
|
|
box: that._$results_container,
|
|
});
|
|
}
|
|
|
|
_init_events() {
|
|
this._$input.bind('selectChoice', (e, choice, autocomplete) => this._on_select(e, choice, autocomplete));
|
|
}
|
|
|
|
_on_select(e, choice, autocomplete) {
|
|
this.account_manager._$input_trigramme.val(choice.find('.trigramme').text());
|
|
this.account_manager._$input_trigramme.trigger('input');
|
|
this.close();
|
|
}
|
|
|
|
close() {
|
|
this._$dialog.close();
|
|
}
|
|
}
|
|
|
|
|
|
$(document).ready(function() {
|
|
'use strict';
|
|
// -----
|
|
// General
|
|
// -----
|
|
|
|
// Lock to avoid multiple requests
|
|
var lock = 0;
|
|
|
|
// -----
|
|
// Checkout data management
|
|
// -----
|
|
|
|
// 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>';
|
|
|
|
|
|
// 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_data['trigramme']) {
|
|
articleSelect.focus().select();
|
|
} else {
|
|
account_manager._$input_trigramme.focus().select();
|
|
}
|
|
});
|
|
|
|
// -----
|
|
// Auth
|
|
// -----
|
|
|
|
function askComment(callback) {
|
|
var comment = $('#id_comment').val();
|
|
$.confirm({
|
|
title: 'Commentaire requis',
|
|
content: '<input type="text" name="comment_opegroup" value="'+comment+'" autofocus>',
|
|
backgroundDismiss: true,
|
|
animation: 'top',
|
|
closeAnimation: 'bottom',
|
|
keyboardEnabled: true,
|
|
confirm: function() {
|
|
$('#id_comment').val(this.$content.find('input').val());
|
|
callback();
|
|
},
|
|
onOpen: function() {
|
|
var that = this;
|
|
this.$content.find('input').on('keydown', function(e) {
|
|
if (e.keyCode == 13)
|
|
that.$confirmButton.click();
|
|
});
|
|
},
|
|
onClose: function() { this._lastFocused = articleSelect; }
|
|
});
|
|
}
|
|
|
|
function resetComment() {
|
|
$('#id_comment').val('');
|
|
}
|
|
|
|
// -----
|
|
// Errors ajax
|
|
// -----
|
|
|
|
function displayErrors(html) {
|
|
$.alert({
|
|
title: 'Erreurs',
|
|
content: html,
|
|
backgroundDismiss: true,
|
|
animation: 'top',
|
|
closeAnimation: 'bottom',
|
|
keyboardEnabled: true,
|
|
});
|
|
}
|
|
|
|
// -----
|
|
// Perform operations
|
|
// -----
|
|
|
|
var performButton = $('#perform_operations');
|
|
var operationGroup = $('#operationgroup_form');
|
|
var operations = $('#operation_formset');
|
|
|
|
function performOperations(password = '') {
|
|
if (lock == 1)
|
|
return false;
|
|
lock = 1;
|
|
var data = operationGroup.serialize() + '&' + operations.serialize();
|
|
$.ajax({
|
|
dataType: "json",
|
|
url : "{% url 'kfet.kpsul.perform_operations' %}",
|
|
method : "POST",
|
|
data : data,
|
|
beforeSend: function ($xhr) {
|
|
$xhr.setRequestHeader("X-CSRFToken", csrftoken);
|
|
if (password != '')
|
|
$xhr.setRequestHeader("KFetPassword", password);
|
|
},
|
|
})
|
|
.done(function(data) {
|
|
updatePreviousOp();
|
|
coolReset();
|
|
lock = 0;
|
|
})
|
|
.fail(function($xhr) {
|
|
var data = $xhr.responseJSON;
|
|
switch ($xhr.status) {
|
|
case 403:
|
|
requestAuth(data, performOperations, articleSelect);
|
|
break;
|
|
case 400:
|
|
if ('need_comment' in data['errors']) {
|
|
askComment(performOperations);
|
|
} else {
|
|
displayErrors(getErrorsHtml(data));
|
|
}
|
|
break;
|
|
}
|
|
lock = 0;
|
|
});
|
|
}
|
|
|
|
// Event listeners
|
|
performButton.on('click', 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);
|
|
}, account_manager._$input_trigramme);
|
|
break;
|
|
case 400:
|
|
displayErrors(getErrorsHtml(data));
|
|
break;
|
|
}
|
|
lock = 0;
|
|
});
|
|
}
|
|
|
|
// Event listeners
|
|
cancelButton.on('click', function() {
|
|
cancelOperations();
|
|
});
|
|
|
|
// -----
|
|
// Articles data
|
|
// -----
|
|
|
|
var articles_container = $('#articles_data tbody');
|
|
var article_category_default_html = '<tr class="category"><td colspan="3"></td></tr>';
|
|
var article_default_html = '<tr class="article"><td class="name"></td><td class="price"></td><td class="stock"></td></tr>';
|
|
|
|
function addArticle(article) {
|
|
var article_html = $(article_default_html);
|
|
article_html.attr('id', 'data-article-'+article['id']);
|
|
article_html.addClass('data-category-'+article['category_id']);
|
|
for (var elem in article) {
|
|
article_html.find('.'+elem).text(article[elem])
|
|
}
|
|
article_html.find('.price').text(amountToUKF(article['price'], false));
|
|
var category_html = articles_container
|
|
.find('#data-category-'+article['category_id']);
|
|
if (category_html.length == 0) {
|
|
category_html = $(article_category_default_html);
|
|
category_html.attr('id', 'data-category-'+article['category_id']);
|
|
category_html.find('td').text(article['category__name']);
|
|
var added = false;
|
|
articles_container.find('.category').each(function() {
|
|
if (article['category__name'].toLowerCase() < $(this).text().toLowerCase()) {
|
|
$(this).before(category_html);
|
|
added = true;
|
|
return false;
|
|
}
|
|
});
|
|
if (!added) articles_container.append(category_html);
|
|
}
|
|
var $after = articles_container.find('#data-category-'+article['category_id']);
|
|
articles_container
|
|
.find('.article.data-category-'+article['category_id']).each(function() {
|
|
if (article['name'].toLowerCase < $('.name', this).text().toLowerCase())
|
|
return false;
|
|
$after = $(this);
|
|
});
|
|
$after.after(article_html);
|
|
// Pour l'autocomplétion
|
|
articlesList.push([article['name'],article['id'],article['category_id'],article['price']]);
|
|
}
|
|
|
|
function getArticles() {
|
|
$.ajax({
|
|
dataType: "json",
|
|
url : "{% url 'kfet.kpsul.articles_data' %}",
|
|
method : "GET",
|
|
})
|
|
.done(function(data) {
|
|
for (var i=0; i<data['articles'].length; i++) {
|
|
addArticle(data['articles'][i]);
|
|
}
|
|
});
|
|
}
|
|
|
|
function resetArticles() {
|
|
articles_container.find('tr').remove();
|
|
articlesList = [];
|
|
}
|
|
|
|
// -----
|
|
// Article selection
|
|
// -----
|
|
|
|
var articleSelect = $('#article_autocomplete');
|
|
var articleId = $('#article_id');
|
|
var articleNb = $('#article_number');
|
|
// 8:Backspace|9:Tab|13:Enter|46:DEL|112-117:F1-6|119-123:F8-F12
|
|
var normalKeys = /^(8|9|13|46|112|113|114|115|116|117|119|120|121|122|123)$/;
|
|
var articlesList = [];
|
|
|
|
function deleteNonMatching(array, str) {
|
|
var dup = [];
|
|
var lower_str = str.toLowerCase();
|
|
for (var i=0; i<array.length; i++) {
|
|
if (((array[i][0]).toLowerCase()).indexOf(lower_str) === 0)
|
|
dup.push(array[i])
|
|
}
|
|
return dup;
|
|
}
|
|
|
|
function callbackForPrefix(elt) {
|
|
return elt[0].toLowerCase();
|
|
}
|
|
|
|
function sharedPrefix(array) {
|
|
var dup = array.map(callbackForPrefix);
|
|
dup.sort(); // On trie l'array
|
|
// On récupère le préfixe du premier et du dernier élément
|
|
var first = dup[0], last = dup[array.length-1],
|
|
length = first.length, i = 0;
|
|
while (i < length && first.charAt(i) === last.charAt(i)) i++;
|
|
return first.substring(0, i);
|
|
}
|
|
|
|
function displayMatchedArticles(array) {
|
|
var categories_to_display = [];
|
|
for (var i=0; i<articlesList.length; i++) {
|
|
if (array.indexOf(articlesList[i]) > -1) {
|
|
articles_container.find('#data-article-'+articlesList[i][1]).show();
|
|
if (categories_to_display.indexOf(articlesList[i][2]) == -1)
|
|
categories_to_display.push(articlesList[i][2]);
|
|
} else {
|
|
articles_container.find('#data-article-'+articlesList[i][1]).hide();
|
|
}
|
|
}
|
|
articles_container.find('.category').hide();
|
|
for (var i=0; i<categories_to_display.length; i++) {
|
|
articles_container
|
|
.find('#data-category-'+categories_to_display[i])
|
|
.show();
|
|
}
|
|
}
|
|
|
|
function updateMatchedArticles(str, commit = true) {
|
|
var lower_str = str.toLowerCase();
|
|
var articlesMatch = deleteNonMatching(articlesList, lower_str);
|
|
|
|
if (articlesMatch.length == 1) {
|
|
articleId.val(0);
|
|
// 1 seul résultat, victoire
|
|
if (commit) {
|
|
articleId.val(articlesMatch[0][1]);
|
|
articleSelect.val(articlesMatch[0][0]);
|
|
displayMatchedArticles(articlesList);
|
|
return true;
|
|
}
|
|
displayMatchedArticles(articlesMatch);
|
|
} else if (articlesMatch.length > 1) {
|
|
articleId.val(0);
|
|
if (commit)
|
|
articleSelect.val(sharedPrefix(articlesMatch));
|
|
displayMatchedArticles(articlesMatch);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// A utiliser après la sélection d'un article
|
|
function goToArticleNb() {
|
|
articleNb.val('1');
|
|
articleNb.focus().select();
|
|
}
|
|
|
|
articleSelect.on('keydown', function(e) {
|
|
var text = articleSelect.val();
|
|
// Comportement normal pour ces touches
|
|
if (normalKeys.test(e.keyCode) || e.ctrlKey) {
|
|
if (text == '' && e.keyCode == 13)
|
|
performOperations();
|
|
if (e.keyCode == 8)
|
|
updateMatchedArticles(text.substring(0,text.length-1), false);
|
|
if (e.charCode == 65 && e.ctrlKey) {
|
|
articleId.val(0);
|
|
articleSelect.val('');
|
|
}
|
|
return true;
|
|
}
|
|
if (updateMatchedArticles(text+e.key))
|
|
goToArticleNb();
|
|
return false;
|
|
});
|
|
|
|
function getArticleId($article) {
|
|
return $article.attr('id').split('-')[2];
|
|
}
|
|
|
|
function getArticleName($article) {
|
|
return $article.find('.name').text();
|
|
}
|
|
|
|
// Sélection des articles à la souris/tactile
|
|
articles_container.on('click', '.article', function() {
|
|
articleId.val(getArticleId($(this)));
|
|
articleSelect.val(getArticleName($(this)));
|
|
displayMatchedArticles(articlesList);
|
|
goToArticleNb();
|
|
});
|
|
|
|
function is_nb_ok(nb) {
|
|
return /^[0-9]+$/.test(nb) && nb > 0 && nb <= 24;
|
|
}
|
|
|
|
articleNb.on('keydown', function(e) {
|
|
if (e.keyCode == 13 && is_nb_ok(articleNb.val()) && articleId.val() > 0) {
|
|
addPurchase(articleId.val(), articleNb.val());
|
|
articleSelect.val('');
|
|
articleNb.val('');
|
|
articleSelect.focus();
|
|
displayMatchedArticles(articlesList);
|
|
return false;
|
|
}
|
|
if (normalKeys.test(e.keyCode) || arrowKeys.test(e.keyCode) || e.keyCode == 8 || e.ctrlKey) {
|
|
if (e.ctrlKey && e.charCode == 65)
|
|
articleNb.val('');
|
|
return true;
|
|
}
|
|
var nb = articleNb.val()+e.key;
|
|
if (is_nb_ok(nb))
|
|
return true;
|
|
return false;
|
|
});
|
|
|
|
// -----
|
|
// Basket
|
|
// -----
|
|
|
|
var item_basket_default_html = '<tr><td class="amount"></td><td class="number"></td><td class="name"></td></tr>';
|
|
var basket_container = $('#basket table');
|
|
var arrowKeys = /^(37|38|39|40)$/;
|
|
|
|
function amountEuroPurchase(article_data, nb) {
|
|
var cfg = Config.getAll();
|
|
var amount_euro = - article_data[3] * nb ;
|
|
if (cfg.addcost_for && cfg.addcost_amount && account_data['trigramme'] != cfg.addcost_for)
|
|
amount_euro -= cfg.addcost_amount * nb;
|
|
var reduc_divisor = 1;
|
|
if (account_data['is_cof'])
|
|
reduc_divisor = 1 + cfg.subvention_cof / 100;
|
|
return amount_euro / reduc_divisor;
|
|
}
|
|
|
|
function addPurchase(id, nb) {
|
|
|
|
var i = 0;
|
|
while (i<articlesList.length && id != articlesList[i][1]) i++;
|
|
var article_data = articlesList[i];
|
|
|
|
var amount_euro = amountEuroPurchase(article_data, nb).toFixed(2);
|
|
var index = addPurchaseToFormset(article_data[1], nb, amount_euro);
|
|
var article_basket_html = $(item_basket_default_html);
|
|
article_basket_html
|
|
.attr('data-opeindex', index)
|
|
.find('.number').text(nb).end()
|
|
.find('.name').text(article_data[0]).end()
|
|
.find('.amount').text(amountToUKF(amount_euro, account_data['is_cof']));
|
|
basket_container.prepend(article_basket_html);
|
|
updateBasketRel();
|
|
}
|
|
|
|
function addDeposit(amount, is_checkout=1) {
|
|
var deposit_basket_html = $(item_basket_default_html);
|
|
var amount = parseFloat(amount).toFixed(2);
|
|
var index = addDepositToFormset(amount, is_checkout);
|
|
var text = is_checkout ? 'Charge' : 'Édition';
|
|
deposit_basket_html
|
|
.attr('data-opeindex', index)
|
|
.find('.number').text(amount+"€").end()
|
|
.find('.name').text(text).end()
|
|
.find('.amount').text(amountToUKF(amount, account_data['is_cof']));
|
|
basket_container.prepend(deposit_basket_html);
|
|
updateBasketRel();
|
|
}
|
|
|
|
function addWithdraw(amount) {
|
|
var withdraw_basket_html = $(item_basket_default_html);
|
|
var amount = (- parseFloat(amount)).toFixed(2);
|
|
var index = addWithdrawToFormset(amount);
|
|
withdraw_basket_html
|
|
.attr('data-opeindex', index)
|
|
.find('.number').text(amount+"€").end()
|
|
.find('.name').text('Retrait').end()
|
|
.find('.amount').text(amountToUKF(amount, account_data['is_cof']));
|
|
basket_container.prepend(withdraw_basket_html);
|
|
updateBasketRel();
|
|
}
|
|
|
|
basket_container.selectable({
|
|
filter: 'tr',
|
|
});
|
|
|
|
$(document).on('keydown', function (e) {
|
|
if (e.keyCode == 46) {
|
|
// DEL (Suppr)
|
|
basket_container.find('.ui-selected').each(function () {
|
|
deleteFromBasket($(this).data('opeindex'));
|
|
});
|
|
}
|
|
});
|
|
|
|
function isBasketEmpty() {
|
|
return !basket_container.find('[data-opeindex]').length;
|
|
}
|
|
|
|
function getAmountBasket() {
|
|
var total = 0;
|
|
formset_container.find('[data-opeindex]').each(function () {
|
|
var opeindex = $(this).attr('data-opeindex');
|
|
if (!$(this).find('#id_form-'+opeindex+'-DELETE').prop('checked'))
|
|
total += parseFloat($(this).find('#id_form-'+opeindex+'-amount').val());
|
|
});
|
|
return total;
|
|
}
|
|
|
|
function updateBasketAmount() {
|
|
formset_container.find('[data-opeindex]').each(function () {
|
|
var opeindex = $(this).attr('data-opeindex');
|
|
var deleted = $(this).find('#id_form-'+opeindex+'-DELETE').prop('checked');
|
|
var type = $(this).find('#id_form-'+opeindex+'-type').val();
|
|
var article_id = $(this).find('#id_form-'+opeindex+'-article').val();
|
|
var article_nb = $(this).find('#id_form-'+opeindex+'-article_nb').val();
|
|
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_data['is_cof']));
|
|
});
|
|
}
|
|
|
|
var basketrel_container = $('#basket_rel');
|
|
|
|
function updateBasketRel() {
|
|
var basketrel_html = '';
|
|
if (account_data['trigramme'] == 'LIQ' && !isBasketEmpty()) {
|
|
var amount = - getAmountBasket();
|
|
basketrel_html += '<div>Total: '+amount.toFixed(2)+' €</div>';
|
|
if (amount < 5)
|
|
basketrel_html += '<div>Sur 5€: '+ (5-amount).toFixed(2) +' €</div>';
|
|
if (amount < 10)
|
|
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_data['trigramme'] != '' && !isBasketEmpty()) {
|
|
var amount = getAmountBasket();
|
|
var amountUKF = amountToUKF(amount, account_manager.account.is_cof);
|
|
var newBalance = account_manager.account.balance + amount;
|
|
var newBalanceUKF = amountToUKF(newBalance, account_manager.account.is_cof);
|
|
basketrel_html += '<div>Total: '+amountUKF+'</div>';
|
|
basketrel_html += '<div>Nouveau solde: '+newBalanceUKF+'</div>';
|
|
if (newBalance < 0)
|
|
basketrel_html += '<div>Manque: '+ (-newBalance).toFixed(2) +' €</div>';
|
|
}
|
|
basketrel_container.html(basketrel_html);
|
|
}
|
|
|
|
function deleteFromBasket(opeindex) {
|
|
basket_container.find('[data-opeindex='+opeindex+']').remove();
|
|
deleteFromFormset(opeindex);
|
|
updateBasketRel();
|
|
}
|
|
|
|
function resetBasket() {
|
|
basket_container.find('tr').remove();
|
|
mngmt_total_forms = 1;
|
|
mngmt_total_forms_input.val(1);
|
|
formset_container.find('div').remove();
|
|
updateBasketRel();
|
|
articleId.val(0);
|
|
articleSelect.val('');
|
|
articleNb.val('');
|
|
displayMatchedArticles(articlesList);
|
|
}
|
|
|
|
// -----
|
|
// Ask deposit or withdraw
|
|
// -----
|
|
|
|
function askDeposit(is_checkout=1) {
|
|
var title = is_checkout ? 'Montant de la charge' : "Montant de l'édition";
|
|
$.confirm({
|
|
title: title,
|
|
content: '<input type="number" lang="en" step="0.01" min="0.01" on autofocus placeholder="€">',
|
|
backgroundDismiss: true,
|
|
animation:'top',
|
|
closeAnimation:'bottom',
|
|
keyboardEnabled: true,
|
|
confirm: function() {
|
|
var amount = this.$content.find('input').val();
|
|
if (!$.isNumeric(amount) || amount <= 0)
|
|
return false;
|
|
addDeposit(amount, is_checkout);
|
|
},
|
|
onOpen: function() {
|
|
var that = this
|
|
this.$content.find('input').on('keydown', function(e) {
|
|
if (e.keyCode == 13) {
|
|
e.preventDefault();
|
|
that.$confirmButton.click();
|
|
}
|
|
});
|
|
},
|
|
onClose: function() { this._lastFocused = (articleSelect.val() ? articleNb : articleSelect) ; }
|
|
});
|
|
}
|
|
|
|
function askWithdraw() {
|
|
$.confirm({
|
|
title: 'Montant du retrait',
|
|
content: '<input type="number" lang="en" step="0.01" min="0.01" on autofocus placeholder="€">',
|
|
backgroundDismiss: true,
|
|
animation:'top',
|
|
closeAnimation:'bottom',
|
|
keyboardEnabled: true,
|
|
confirm: function() {
|
|
var amount = this.$content.find('input').val();
|
|
if (!$.isNumeric(amount) || amount <= 0)
|
|
return false;
|
|
addWithdraw(amount);
|
|
},
|
|
onOpen: function() {
|
|
var that = this
|
|
this.$content.find('input').on('keydown', function(e) {
|
|
if (e.keyCode == 13) {
|
|
e.preventDefault();
|
|
that.$confirmButton.click();
|
|
}
|
|
});
|
|
},
|
|
onClose: function() { this._lastFocused = articleSelect; }
|
|
});
|
|
}
|
|
|
|
// Event
|
|
|
|
var depositButton = $('#operation_deposit');
|
|
var withdrawButton = $('#operation_withdraw');
|
|
|
|
depositButton.on('click', function() { askDeposit(); });
|
|
withdrawButton.on('click', function() { askWithdraw(); });
|
|
|
|
// -----
|
|
// Operation formset management
|
|
// -----
|
|
|
|
var operation_empty_html = $('#operation_empty_html')
|
|
.removeAttr('id')
|
|
.find('label').remove().end()
|
|
.find('#id_form-__prefix__-DELETE').css('display','none').end();
|
|
$('#id_form-0-DELETE').prop('checked',true);
|
|
|
|
var formset_container = $('#operation_formset');
|
|
var mngmt_total_forms_input = $('#id_form-TOTAL_FORMS');
|
|
var mngmt_total_forms = 1;
|
|
var prefix_regex = /__prefix__/;
|
|
|
|
function addOperationToFormset(type, amount, article='', article_nb='', is_checkout=1) {
|
|
var operation_html = operation_empty_html.clone();
|
|
var index = mngmt_total_forms;
|
|
|
|
operation_html.attr('data-opeindex', index);
|
|
|
|
operation_html
|
|
.find('#id_form-__prefix__-type').val(type).end()
|
|
.find('#id_form-__prefix__-amount').val((parseFloat(amount)).toFixed(2)).end()
|
|
.find('#id_form-__prefix__-article').val(article).end()
|
|
.find('#id_form-__prefix__-article_nb').val(article_nb).end()
|
|
.find('#id_form-__prefix__-is_checkout').val(is_checkout);
|
|
|
|
mngmt_total_forms_input.val(index+1);
|
|
mngmt_total_forms++;
|
|
|
|
operation_html.find(':input').each(function() {
|
|
var name = $(this).attr('name').replace(prefix_regex, index);
|
|
var id = 'id_' + name;
|
|
$(this).attr({'name': name, 'id': id});
|
|
});
|
|
formset_container.append(operation_html);
|
|
|
|
return index;
|
|
}
|
|
|
|
function addDepositToFormset(amount, is_checkout=1) {
|
|
return addOperationToFormset('deposit', amount, '', '', is_checkout);
|
|
}
|
|
|
|
function addWithdrawToFormset(amount, is_checkout=1) {
|
|
return addOperationToFormset('withdraw', amount, '', '', is_checkout);
|
|
}
|
|
|
|
function addPurchaseToFormset(article_id, article_nb, amount=0) {
|
|
return addOperationToFormset('purchase', amount, article_id, article_nb);
|
|
}
|
|
|
|
function deleteFromFormset(opeindex) {
|
|
formset_container.find('#id_form-'+opeindex+'-DELETE').prop('checked', true);
|
|
}
|
|
|
|
// -----
|
|
// History
|
|
// -----
|
|
|
|
var khistory = new KHistory();
|
|
|
|
function getHistory() {
|
|
var data = {
|
|
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<data['opegroups'].length; i++) {
|
|
khistory.addOpeGroup(data['opegroups'][i]);
|
|
}
|
|
});
|
|
}
|
|
|
|
var previousop_container = $('#previous_op');
|
|
|
|
function updatePreviousOp() {
|
|
var previousop_html = '';
|
|
var trigramme = account_manager.account.trigramme;
|
|
previousop_html += '<div class="trigramme">Trigramme : '+trigramme+'</div>';
|
|
previousop_html += basketrel_container.html();
|
|
previousop_container.html(previousop_html);
|
|
}
|
|
|
|
function resetPreviousOp() {
|
|
previousop_container.html('');
|
|
}
|
|
|
|
// -----
|
|
// Addcost
|
|
// -----
|
|
|
|
var addcost_default_html = '<div id="addcost">Majoration vers <span class="addcost_for"></span> de <span class="addcost_amount"></span>€</div>';
|
|
|
|
function displayAddcost() {
|
|
var cfg = Config.getAll();
|
|
checkout_container.find('#addcost').remove();
|
|
$('body').css('animation', 'none');
|
|
if (cfg.addcost_for && cfg.addcost_amount) {
|
|
var addcost_html = $(addcost_default_html);
|
|
addcost_html
|
|
.find('.addcost_for').text(cfg.addcost_for).end()
|
|
.find('.addcost_amount').text(cfg.addcost_amount.toFixed(2)).end();
|
|
checkout_container.prepend(addcost_html);
|
|
$('body').css('animation', 'colorchange 3s infinite');
|
|
}
|
|
}
|
|
function sendAddcost(trigramme, amount, password='') {
|
|
var data = {
|
|
trigramme: trigramme,
|
|
amount: amount,
|
|
}
|
|
$.ajax({
|
|
dataType: "json",
|
|
url : "{% url 'kfet.kpsul.update_addcost' %}",
|
|
method : "POST",
|
|
data : data,
|
|
beforeSend: function ($xhr) {
|
|
$xhr.setRequestHeader("X-CSRFToken", csrftoken);
|
|
if (password != '')
|
|
$xhr.setRequestHeader("KFetPassword", password);
|
|
},
|
|
})
|
|
.fail(function($xhr) {
|
|
var data = $xhr.responseJSON;
|
|
switch ($xhr.status) {
|
|
case 403:
|
|
requestAuth(data, function(password) {
|
|
sendAddcost(trigramme, amount, password);
|
|
}, account_manager._$input_trigramme);
|
|
break;
|
|
case 400:
|
|
askAddcost(getErrorsHtml(data));
|
|
break;
|
|
}
|
|
});
|
|
}
|
|
|
|
function askAddcost(errors = '') {
|
|
$.confirm({
|
|
title: 'Majoration',
|
|
content: errors + '<input type="text" placeholder="Trigramme" autocomplete="off" name="trigramme" spellcheck="false" style="text-transform:uppercase" autofocus><input type="number" lang="en" step="0.01" min="0.01" placeholder="€" name="amount">',
|
|
backgroundDismiss: true,
|
|
animation:'top',
|
|
closeAnimation:'bottom',
|
|
keyboardEnabled: true,
|
|
confirm: function() {
|
|
var trigramme = this.$content.find('input[name=trigramme]').val().toUpperCase();
|
|
var amount = this.$content.find('input[name=amount]').val();
|
|
sendAddcost(trigramme, amount);
|
|
},
|
|
onOpen: function() {
|
|
var that = this
|
|
this.$content.find('input[name=amount]').on('keydown', function(e) {
|
|
if (e.keyCode == 13) {
|
|
e.preventDefault();
|
|
that.$confirmButton.click();
|
|
}
|
|
});
|
|
},
|
|
onClose: function() { this._lastFocused = account_manager._$input_trigramme; }
|
|
});
|
|
}
|
|
|
|
|
|
// -----
|
|
// Cancel from history
|
|
// -----
|
|
|
|
khistory.$container.selectable({
|
|
filter: 'div.opegroup, div.ope',
|
|
selected: function(e, ui) {
|
|
$(ui.selected).each(function() {
|
|
if ($(this).hasClass('opegroup')) {
|
|
var opegroup = $(this).data('opegroup');
|
|
$(this).siblings('.ope').filter(function() {
|
|
return $(this).data('opegroup') == opegroup
|
|
}).addClass('ui-selected');
|
|
}
|
|
});
|
|
},
|
|
});
|
|
|
|
$(document).on('keydown', function (e) {
|
|
if (e.keyCode == 46) {
|
|
// DEL (Suppr)
|
|
var opes_to_cancel = [];
|
|
khistory.$container.find('.ope.ui-selected').each(function () {
|
|
opes_to_cancel.push($(this).data('ope'));
|
|
});
|
|
if (opes_to_cancel.length > 0)
|
|
cancelOperations(opes_to_cancel);
|
|
}
|
|
});
|
|
|
|
// -----
|
|
// Synchronization
|
|
// -----
|
|
|
|
var websocket_msg_default = {'opegroups':[],'opes':[],'checkouts':[],'articles':[]}
|
|
|
|
var websocket_protocol = window.location.protocol == 'https:' ? 'wss' : 'ws';
|
|
var location_host = window.location.host;
|
|
var location_url = window.location.pathname.startsWith('/gestion/') ? location_host + '/gestion' : location_host;
|
|
var socket = new ReconnectingWebSocket(websocket_protocol+"://" + location_url + "/ws/k-fet/k-psul/");
|
|
socket.onmessage = function(e) {
|
|
var data = $.extend({}, websocket_msg_default, JSON.parse(e.data));
|
|
|
|
for (var i=0; i<data['opegroups'].length; i++) {
|
|
if (data['opegroups'][i]['add']) {
|
|
khistory.addOpeGroup(data['opegroups'][i]);
|
|
} else if (data['opegroups'][i]['cancellation']) {
|
|
khistory.cancelOpeGroup(data['opegroups'][i]);
|
|
}
|
|
}
|
|
for (var i=0; i<data['opes'].length; i++) {
|
|
if (data['opes'][i]['cancellation']) {
|
|
khistory.cancelOpe(data['opes'][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();
|
|
}
|
|
}
|
|
for (var i=0; i<data['articles'].length; i++) {
|
|
var article = data['articles'][i];
|
|
articles_container.find('#data-article-'+article['id']+' .stock')
|
|
.text(article['stock']);
|
|
}
|
|
if (data['addcost']) {
|
|
Config.addcost_for = data['addcost']['for'];
|
|
Config.addcost_amount = data['addcost']['amount'];
|
|
displayAddcost();
|
|
}
|
|
}
|
|
|
|
// -----
|
|
// General
|
|
// -----
|
|
|
|
// Reset functions
|
|
|
|
function coolReset(give_tri_focus=true) {
|
|
account_manager.reset();
|
|
resetBasket();
|
|
resetComment();
|
|
resetSelectable();
|
|
if (give_tri_focus)
|
|
account_manager._$input_trigramme.focus();
|
|
}
|
|
|
|
function hardReset(give_tri_focus=true) {
|
|
coolReset(give_tri_focus);
|
|
checkoutInput.trigger('change');
|
|
resetArticles();
|
|
resetPreviousOp();
|
|
khistory.reset();
|
|
Config.reset(function() {
|
|
displayAddcost();
|
|
getArticles();
|
|
getHistory();
|
|
});
|
|
}
|
|
|
|
function resetSelectable() {
|
|
$('.ui-selected').removeClass('ui-selected');
|
|
}
|
|
|
|
// Shorcuts
|
|
|
|
$('#cool_reset').click(function() {
|
|
coolReset();
|
|
});
|
|
|
|
$('#ask_addcost').click(function() {
|
|
askAddcost();
|
|
});
|
|
|
|
$(document).on('keydown', function(e) {
|
|
switch (e.keyCode) {
|
|
case 27:
|
|
// Escape - Hide help
|
|
$('.help').hide('fast');
|
|
return false;
|
|
case 72:
|
|
if (e.ctrlKey) {
|
|
// Ctrl+H - Display help
|
|
e.preventDefault();
|
|
$('.help').show('fast');
|
|
}
|
|
return true;
|
|
case 112:
|
|
// F1 - Cool reset
|
|
coolReset();
|
|
return false;
|
|
case 113:
|
|
if (e.shiftKey) {
|
|
// Shift+F2 - Account reset
|
|
account_manager.reset();
|
|
account_manager._$input_trigramme.focus();
|
|
} else {
|
|
// F2 - Basket reset
|
|
resetBasket();
|
|
articleSelect.focus();
|
|
}
|
|
return false;
|
|
case 114:
|
|
if (e.shiftKey) {
|
|
// Shift+F3 - Withdraw
|
|
askWithdraw();
|
|
} else {
|
|
// F3 - Withdraw
|
|
askDeposit();
|
|
}
|
|
return false;
|
|
case 119:
|
|
// F8 - Edition
|
|
askDeposit(0);
|
|
return false;
|
|
case 120:
|
|
// F9 - Addcost
|
|
askAddcost();
|
|
return false;
|
|
case 121:
|
|
// F10 - Hard reset
|
|
hardReset();
|
|
return false;
|
|
}
|
|
});
|
|
|
|
// -----
|
|
// Initiliazing all
|
|
// -----
|
|
|
|
var env = {
|
|
articleSelect: articleSelect,
|
|
updateBasketAmount: updateBasketAmount,
|
|
updateBasketRel: updateBasketRel,
|
|
};
|
|
|
|
var account_manager = new AccountManager(env);
|
|
|
|
hardReset();
|
|
|
|
});
|
|
</script>
|
|
|
|
{% endblock %}
|