K-Psul - Historique + synchronisation

- Ajoute l'affichage de l'historique dans K-Psul
- Ajoute la synchronisation du montant des caisses et de l'historique
  entre les interfaces K-Psul ouvertes par le package 'channels' et
  l'utilisation de websockets
- Corrige l'obligation de l'article sur K-Psul (pas d'article pour les
  charges et retraits)
- Corrige type renvoyé par perms_to_perform_operations
- Rangement de js.cookie.js dans static/kfet/js/
- Ajout de dépendances
This commit is contained in:
Aurélien Delobelle 2016-08-14 19:59:36 +02:00
parent 820687c8af
commit 8256c96ffb
12 changed files with 834 additions and 9 deletions

3
cof/routing.py Normal file
View file

@ -0,0 +1,3 @@
from kfet.routing import channel_routing as kfet_channel_routings
channel_routing = kfet_channel_routings

20
kfet/consumers.py Normal file
View file

@ -0,0 +1,20 @@
from channels import Group
from channels.generic.websockets import JsonWebsocketConsumer
class KPsul(JsonWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
def connection_groups(self, **kwargs):
return ['kfet.kpsul']
def connect(self, message, **kwargs):
pass
def receive(self, content, **kwargs):
pass
def disconnect(self, message, **kwargs):
pass

View file

@ -146,7 +146,8 @@ class KPsulCheckoutForm(forms.Form):
class KPsulOperationForm(forms.ModelForm): class KPsulOperationForm(forms.ModelForm):
article = forms.ModelChoiceField( article = forms.ModelChoiceField(
queryset=Article.objects.select_related('category').all()) queryset=Article.objects.select_related('category').all(),
required=False)
class Meta: class Meta:
model = Operation model = Operation
fields = ['type', 'amount', 'is_checkout', 'article', 'article_nb'] fields = ['type', 'amount', 'is_checkout', 'article', 'article_nb']

View file

@ -111,7 +111,7 @@ class Account(models.Model):
# Checking is cash account # Checking is cash account
if self.is_cash: if self.is_cash:
# Yes, so no perms and no stop # Yes, so no perms and no stop
return [], False return set(), False
# Checking is frozen account # Checking is frozen account
if self.is_frozen: if self.is_frozen:
perms.add('kfet.override_frozen_protection') perms.add('kfet.override_frozen_protection')

8
kfet/routing.py Normal file
View file

@ -0,0 +1,8 @@
from channels.routing import route, route_class
from kfet import consumers
channel_routing = [
route_class(consumers.KPsul, path=r"^/k-fet/k-psul/$"),
#route("websocket.connect", ws_kpsul_history_connect),
#route('websocket.receive', ws_message)
]

View file

@ -0,0 +1,365 @@
// MIT License:
//
// Copyright (c) 2010-2012, Joe Walnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/**
* This behaves like a WebSocket in every way, except if it fails to connect,
* or it gets disconnected, it will repeatedly poll until it successfully connects
* again.
*
* It is API compatible, so when you have:
* ws = new WebSocket('ws://....');
* you can replace with:
* ws = new ReconnectingWebSocket('ws://....');
*
* The event stream will typically look like:
* onconnecting
* onopen
* onmessage
* onmessage
* onclose // lost connection
* onconnecting
* onopen // sometime later...
* onmessage
* onmessage
* etc...
*
* It is API compatible with the standard WebSocket API, apart from the following members:
*
* - `bufferedAmount`
* - `extensions`
* - `binaryType`
*
* Latest version: https://github.com/joewalnes/reconnecting-websocket/
* - Joe Walnes
*
* Syntax
* ======
* var socket = new ReconnectingWebSocket(url, protocols, options);
*
* Parameters
* ==========
* url - The url you are connecting to.
* protocols - Optional string or array of protocols.
* options - See below
*
* Options
* =======
* Options can either be passed upon instantiation or set after instantiation:
*
* var socket = new ReconnectingWebSocket(url, null, { debug: true, reconnectInterval: 4000 });
*
* or
*
* var socket = new ReconnectingWebSocket(url);
* socket.debug = true;
* socket.reconnectInterval = 4000;
*
* debug
* - Whether this instance should log debug messages. Accepts true or false. Default: false.
*
* automaticOpen
* - Whether or not the websocket should attempt to connect immediately upon instantiation. The socket can be manually opened or closed at any time using ws.open() and ws.close().
*
* reconnectInterval
* - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000.
*
* maxReconnectInterval
* - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000.
*
* reconnectDecay
* - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5.
*
* timeoutInterval
* - The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. Accepts integer. Default: 2000.
*
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports){
module.exports = factory();
} else {
global.ReconnectingWebSocket = factory();
}
})(this, function () {
if (!('WebSocket' in window)) {
return;
}
function ReconnectingWebSocket(url, protocols, options) {
// Default settings
var settings = {
/** Whether this instance should log debug messages. */
debug: false,
/** Whether or not the websocket should attempt to connect immediately upon instantiation. */
automaticOpen: true,
/** The number of milliseconds to delay before attempting to reconnect. */
reconnectInterval: 1000,
/** The maximum number of milliseconds to delay a reconnection attempt. */
maxReconnectInterval: 30000,
/** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */
reconnectDecay: 1.5,
/** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */
timeoutInterval: 2000,
/** The maximum number of reconnection attempts to make. Unlimited if null. */
maxReconnectAttempts: null,
/** The binary type, possible values 'blob' or 'arraybuffer', default 'blob'. */
binaryType: 'blob'
}
if (!options) { options = {}; }
// Overwrite and define settings with options if they exist.
for (var key in settings) {
if (typeof options[key] !== 'undefined') {
this[key] = options[key];
} else {
this[key] = settings[key];
}
}
// These should be treated as read-only properties
/** The URL as resolved by the constructor. This is always an absolute URL. Read only. */
this.url = url;
/** The number of attempted reconnects since starting, or the last successful connection. Read only. */
this.reconnectAttempts = 0;
/**
* The current state of the connection.
* Can be one of: WebSocket.CONNECTING, WebSocket.OPEN, WebSocket.CLOSING, WebSocket.CLOSED
* Read only.
*/
this.readyState = WebSocket.CONNECTING;
/**
* A string indicating the name of the sub-protocol the server selected; this will be one of
* the strings specified in the protocols parameter when creating the WebSocket object.
* Read only.
*/
this.protocol = null;
// Private state variables
var self = this;
var ws;
var forcedClose = false;
var timedOut = false;
var eventTarget = document.createElement('div');
// Wire up "on*" properties as event handlers
eventTarget.addEventListener('open', function(event) { self.onopen(event); });
eventTarget.addEventListener('close', function(event) { self.onclose(event); });
eventTarget.addEventListener('connecting', function(event) { self.onconnecting(event); });
eventTarget.addEventListener('message', function(event) { self.onmessage(event); });
eventTarget.addEventListener('error', function(event) { self.onerror(event); });
// Expose the API required by EventTarget
this.addEventListener = eventTarget.addEventListener.bind(eventTarget);
this.removeEventListener = eventTarget.removeEventListener.bind(eventTarget);
this.dispatchEvent = eventTarget.dispatchEvent.bind(eventTarget);
/**
* This function generates an event that is compatible with standard
* compliant browsers and IE9 - IE11
*
* This will prevent the error:
* Object doesn't support this action
*
* http://stackoverflow.com/questions/19345392/why-arent-my-parameters-getting-passed-through-to-a-dispatched-event/19345563#19345563
* @param s String The name that the event should use
* @param args Object an optional object that the event will use
*/
function generateEvent(s, args) {
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(s, false, false, args);
return evt;
};
this.open = function (reconnectAttempt) {
ws = new WebSocket(self.url, protocols || []);
ws.binaryType = this.binaryType;
if (reconnectAttempt) {
if (this.maxReconnectAttempts && this.reconnectAttempts > this.maxReconnectAttempts) {
return;
}
} else {
eventTarget.dispatchEvent(generateEvent('connecting'));
this.reconnectAttempts = 0;
}
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'attempt-connect', self.url);
}
var localWs = ws;
var timeout = setTimeout(function() {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'connection-timeout', self.url);
}
timedOut = true;
localWs.close();
timedOut = false;
}, self.timeoutInterval);
ws.onopen = function(event) {
clearTimeout(timeout);
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onopen', self.url);
}
self.protocol = ws.protocol;
self.readyState = WebSocket.OPEN;
self.reconnectAttempts = 0;
var e = generateEvent('open');
e.isReconnect = reconnectAttempt;
reconnectAttempt = false;
eventTarget.dispatchEvent(e);
};
ws.onclose = function(event) {
clearTimeout(timeout);
ws = null;
if (forcedClose) {
self.readyState = WebSocket.CLOSED;
eventTarget.dispatchEvent(generateEvent('close'));
} else {
self.readyState = WebSocket.CONNECTING;
var e = generateEvent('connecting');
e.code = event.code;
e.reason = event.reason;
e.wasClean = event.wasClean;
eventTarget.dispatchEvent(e);
if (!reconnectAttempt && !timedOut) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onclose', self.url);
}
eventTarget.dispatchEvent(generateEvent('close'));
}
var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts);
setTimeout(function() {
self.reconnectAttempts++;
self.open(true);
}, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout);
}
};
ws.onmessage = function(event) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onmessage', self.url, event.data);
}
var e = generateEvent('message');
e.data = event.data;
eventTarget.dispatchEvent(e);
};
ws.onerror = function(event) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'onerror', self.url, event);
}
eventTarget.dispatchEvent(generateEvent('error'));
};
}
// Whether or not to create a websocket upon instantiation
if (this.automaticOpen == true) {
this.open(false);
}
/**
* Transmits data to the server over the WebSocket connection.
*
* @param data a text string, ArrayBuffer or Blob to send to the server.
*/
this.send = function(data) {
if (ws) {
if (self.debug || ReconnectingWebSocket.debugAll) {
console.debug('ReconnectingWebSocket', 'send', self.url, data);
}
return ws.send(data);
} else {
throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
}
};
/**
* Closes the WebSocket connection or connection attempt, if any.
* If the connection is already CLOSED, this method does nothing.
*/
this.close = function(code, reason) {
// Default CLOSE_NORMAL code
if (typeof code == 'undefined') {
code = 1000;
}
forcedClose = true;
if (ws) {
ws.close(code, reason);
}
};
/**
* Additional public API method to refresh the connection if still open (close, re-open).
* For example, if the app suspects bad data / missed heart beats, it can try to refresh.
*/
this.refresh = function() {
if (ws) {
ws.close();
}
};
}
/**
* An event listener to be called when the WebSocket connection's readyState changes to OPEN;
* this indicates that the connection is ready to send and receive data.
*/
ReconnectingWebSocket.prototype.onopen = function(event) {};
/** An event listener to be called when the WebSocket connection's readyState changes to CLOSED. */
ReconnectingWebSocket.prototype.onclose = function(event) {};
/** An event listener to be called when a connection begins being attempted. */
ReconnectingWebSocket.prototype.onconnecting = function(event) {};
/** An event listener to be called when a message is received from the server. */
ReconnectingWebSocket.prototype.onmessage = function(event) {};
/** An event listener to be called when an error occurs. */
ReconnectingWebSocket.prototype.onerror = function(event) {};
/**
* Whether all instances of ReconnectingWebSocket should log debug messages.
* Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
*/
ReconnectingWebSocket.debugAll = false;
ReconnectingWebSocket.CONNECTING = WebSocket.CONNECTING;
ReconnectingWebSocket.OPEN = WebSocket.OPEN;
ReconnectingWebSocket.CLOSING = WebSocket.CLOSING;
ReconnectingWebSocket.CLOSED = WebSocket.CLOSED;
return ReconnectingWebSocket;
});

View file

@ -0,0 +1,167 @@
/**
* options.uri - > The Websocket URI
* options.connected -> Callback called after the websocket is connected.
* options.connecting -> Callback called when the websocket is connecting.
* options.disconnected -> Callback called after the websocket is disconnected.
* options.receive_message -> Callback called when a message is received from the websocket.
* options.heartbeat_msg -> String to identify the heartbeat message.
* $ -> JQuery instance.
*/
function WS4Redis(options, $) {
'use strict';
var opts, ws, deferred, timer, attempts = 1, must_reconnect = true;
var heartbeat_interval = null, missed_heartbeats = 0;
if (this === undefined)
return new WS4Redis(options, $);
if (options.uri === undefined)
throw new Error('No Websocket URI in options');
if ($ === undefined)
$ = jQuery;
opts = $.extend({ heartbeat_msg: null }, options);
connect(opts.uri);
function connect(uri) {
try {
if (ws && (is_connecting() || is_connected())) {
console.log("Websocket is connecting or already connected.");
return;
}
if ($.type(opts.connecting) === 'function') {
opts.connecting();
}
console.log("Connecting to " + uri + " ...");
deferred = $.Deferred();
ws = new WebSocket(uri);
ws.onopen = on_open;
ws.onmessage = on_message;
ws.onerror = on_error;
ws.onclose = on_close;
timer = null;
} catch (err) {
try_to_reconnect();
deferred.reject(new Error(err));
}
}
function try_to_reconnect() {
if (must_reconnect && !timer) {
// try to reconnect
console.log('Reconnecting...');
var interval = generate_inteval(attempts);
timer = setTimeout(function() {
attempts++;
connect(ws.url);
}, interval);
}
}
function send_heartbeat() {
try {
missed_heartbeats++;
if (missed_heartbeats > 3)
throw new Error("Too many missed heartbeats.");
ws.send(opts.heartbeat_msg);
} catch(e) {
clearInterval(heartbeat_interval);
heartbeat_interval = null;
console.warn("Closing connection. Reason: " + e.message);
if ( !is_closing() && !is_closed() ) {
ws.close();
}
}
}
function on_open() {
console.log('Connected!');
// new connection, reset attemps counter
attempts = 1;
deferred.resolve();
if (opts.heartbeat_msg && heartbeat_interval === null) {
missed_heartbeats = 0;
heartbeat_interval = setInterval(send_heartbeat, 5000);
}
if ($.type(opts.connected) === 'function') {
opts.connected();
}
}
function on_close(evt) {
console.log("Connection closed!");
if ($.type(opts.disconnected) === 'function') {
opts.disconnected(evt);
}
try_to_reconnect();
}
function on_error(evt) {
console.error("Websocket connection is broken!");
deferred.reject(new Error(evt));
}
function on_message(evt) {
if (opts.heartbeat_msg && evt.data === opts.heartbeat_msg) {
// reset the counter for missed heartbeats
missed_heartbeats = 0;
} else if ($.type(opts.receive_message) === 'function') {
return opts.receive_message(evt.data);
}
}
// this code is borrowed from http://blog.johnryding.com/post/78544969349/
//
// Generate an interval that is randomly between 0 and 2^k - 1, where k is
// the number of connection attmpts, with a maximum interval of 30 seconds,
// so it starts at 0 - 1 seconds and maxes out at 0 - 30 seconds
function generate_inteval(k) {
var maxInterval = (Math.pow(2, k) - 1) * 1000;
// If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
if (maxInterval > 30*1000) {
maxInterval = 30*1000;
}
// generate the interval to a random number between 0 and the maxInterval determined from above
return Math.random() * maxInterval;
}
this.send_message = function(message) {
ws.send(message);
};
this.get_state = function() {
return ws.readyState;
};
function is_connecting() {
return ws && ws.readyState === 0;
}
function is_connected() {
return ws && ws.readyState === 1;
}
function is_closing() {
return ws && ws.readyState === 2;
}
function is_closed() {
return ws && ws.readyState === 3;
}
this.close = function () {
clearInterval(heartbeat_interval);
must_reconnect = false;
if (!is_closing() || !is_closed()) {
ws.close();
}
}
this.is_connecting = is_connecting;
this.is_connected = is_connected;
this.is_closing = is_closing;
this.is_closed = is_closed;
}

View file

@ -2,7 +2,8 @@
{% load staticfiles %} {% load staticfiles %}
{% block extra_head %} {% block extra_head %}
<script type="text/javascript" src="{% static 'kfet/js.cookie.js' %}"></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>
{% endblock %} {% endblock %}
{% block title %}K-Psul{% endblock %} {% block title %}K-Psul{% endblock %}
@ -44,6 +45,19 @@
{{ operation_formset.as_p }} {{ operation_formset.as_p }}
</form> </form>
<table id="articles_data">
<thead>
<tr>
<td>Nom</td>
<td>Catégorie</td>
<td>Prix</td>
<td>Stock</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" id="perform_operations">Valider</button> <button type="button" id="perform_operations">Valider</button>
<form id="cancel_form"> <form id="cancel_form">
@ -53,6 +67,9 @@
<button type="button" id="cancel_operations">Annuler</button> <button type="button" id="cancel_operations">Annuler</button>
<div id="history_data">
</div>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function() { $(document).ready(function() {
// ----- // -----
@ -219,7 +236,7 @@ $(document).ready(function() {
.done(function(data) { .done(function(data) {
console.log(data); console.log(data);
}) })
.always(function($xhr) { .fail(function($xhr) {
var data = $xhr.responseJSON; var data = $xhr.responseJSON;
console.log(data); console.log(data);
}); });
@ -230,7 +247,9 @@ $(document).ready(function() {
performOperations(); performOperations();
}); });
// -----
// Cancel operations // Cancel operations
// -----
var cancelButton = $('#cancel_operations'); var cancelButton = $('#cancel_operations');
var cancelForm = $('#cancel_form'); var cancelForm = $('#cancel_form');
@ -256,6 +275,151 @@ $(document).ready(function() {
cancelButton.on('click', function() { cancelButton.on('click', function() {
cancelOperations(); cancelOperations();
}); });
// -----
// Articles data management
// -----
var articles_data = {}
var articles_container = $('#articles_data tbody');
var articles_new_html = '<tr><td class="article_name"></td><td class="article_category_name"></td><td class="article_price"></td><td class="article_stock"></td></tr>';
function addArticle(article) {
var article_new = $(articles_new_html);
article_new.filter('tr').attr('id', 'article-' + article['id'])
for (var elem in article) {
article_new.filter('.article_'+elem).text(article[elem])
}
articles_container.append(article_new);
}
function storeArticlesData(data) {
if (data['articles']['new']) {
for (var article in data['articles']['new']) {
addArticle(article);
}
}
}
function retrieveArticlesData() {
$.ajax({
dataType: "json",
url : "",
method : "GET",
data : { 'articles' : articles_data },
})
.done(function(data) {
storeArticlesData(data);
});
}
// -----
// History
// -----
var history_container = $('#history_data');
var history_operationgroup_html = '<div class="opegroup"><div class="general"></div></div>';
var history_operation_html = '<div class="ope"></div>';
function getTextOpe(ope) {
if (ope['type'] == 'deposit') {
return ope['amount']+' € - Charge';
} else if (ope['type'] == 'withdraw') {
return ope['amount']+' € - Retrait';
} else {
return ope['amount']+' € - '+ope['article_nb']+' '+ope['article__name'];
}
}
function addOpeGroup(opegroup) {
// Préparation ajout groupe d'opés à l'historique
var opegroup_html = $(history_operationgroup_html);
opegroup_html
.attr('id', 'opegroup-'+opegroup['id']);
opegroup_html.find('.general').html(
opegroup['at']
+' '+opegroup['on_acc__trigramme']
+' <span class="amount">'+opegroup['amount']+'</span> €');
// Ajout des opérations de ce groupe
for (var i=0; i < opegroup['opes'].length; i++) {
var ope_html = $(history_operation_html);
var ope = opegroup['opes'][i];
if (ope['canceled_at']) {
ope_html.addClass('canceled')
}
ope_html
.attr('id', 'ope-'+ope['id'])
.text(getTextOpe(ope));
opegroup_html.append(ope_html);
}
// Ajout du groupe
history_container.prepend(opegroup_html);
}
function getHistory() {
$.ajax({
dataType: "json",
url : "{% url 'kfet.kpsul.history' %}",
method : "GET",
})
.done(function(data) {
for (var opegroup_id in data['opegroups']) {
addOpeGroup(data['opegroups'][opegroup_id]);
}
});
}
function cancelOpeGroup(opegroup) {
var opegroup_html = history_container.find('#opegroup-'+opegroup['id']);
opegroup_html.find('.amount').text(opegroup['amount']);
}
function cancelOpe(ope) {
var ope_html = history_container.find('#ope-'+ope['id']);
ope_html.addClass('canceled');
}
// -----
// Synchronization
// -----
socket = new ReconnectingWebSocket("ws://" + window.location.host + "/k-fet/k-psul/");
socket.onmessage = function(e) {
data = JSON.parse(e.data);
data['opegroups'] = data['opegroups'] || [];
data['opes'] = data['opes'] || [];
data['checkouts'] = data['checkouts'] || [];
for (var i=0; i<data['opegroups'].length; i++) {
if (data['opegroups'][i]['add']) {
addOpeGroup(data['opegroups'][i]);
} else if (data['opegroups'][i]['cancellation']) {
cancelOpeGroup(data['opegroups'][i]);
}
}
for (var i=0; i<data['opes'].length; i++) {
if (data['opes'][i]['cancellation']) {
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();
}
}
}
// -----
// Initiliazing all
// -----
resetAccountData();
resetCheckoutData();
getHistory();
}); });
</script> </script>

View file

@ -103,4 +103,6 @@ urlpatterns = [
name = 'kfet.kpsul.perform_operations'), name = 'kfet.kpsul.perform_operations'),
url('^k-psul/cancel_operations$', views.kpsul_cancel_operations, url('^k-psul/cancel_operations$', views.kpsul_cancel_operations,
name = 'kfet.kpsul.cancel_operations'), name = 'kfet.kpsul.cancel_operations'),
url('^k-psul/history$', views.kpsul_history,
name = 'kfet.kpsul.history'),
] ]

View file

@ -17,6 +17,9 @@ from kfet.models import (Account, Checkout, Article, Settings, AccountNegative,
CheckoutStatement) CheckoutStatement)
from kfet.forms import * from kfet.forms import *
from collections import defaultdict from collections import defaultdict
from channels import Group
from kfet import consumers
from datetime import timedelta
@login_required @login_required
def home(request): def home(request):
@ -450,6 +453,22 @@ def kpsul_checkout_data(request):
raise http404 raise http404
return JsonResponse(data) return JsonResponse(data)
@permission_required('kfet.is_team')
def kpsul_articles_data(request):
articles_old = request.GET.get('articles', [])
data = { 'articles' : {'new': [], 'deleted': [], 'updated': []} }
articles = (Article.objects
.annotate(category_name=F('category__name'))
.values('id', 'name', 'price', 'stock', 'category_name')
.select_related('category')
.filter(is_sold=True)
)
for article in articles:
if article['id'] not in articles_old['id']:
pass
return JsonResponse(data)
def get_missing_perms(required_perms, user): def get_missing_perms(required_perms, user):
missing_perms_codenames = [ (perm.split('.'))[1] missing_perms_codenames = [ (perm.split('.'))[1]
for perm in required_perms if not user.has_perm(perm)] for perm in required_perms if not user.has_perm(perm)]
@ -462,7 +481,7 @@ def get_missing_perms(required_perms, user):
@permission_required('kfet.is_team') @permission_required('kfet.is_team')
def kpsul_perform_operations(request): def kpsul_perform_operations(request):
# Initializing response data # Initializing response data
data = { 'operation_group': 0, 'operations': [], data = { 'operationgroup': 0, 'operations': [],
'warnings': {}, 'errors': {} } 'warnings': {}, 'errors': {} }
# Checking operationgroup # Checking operationgroup
@ -505,7 +524,7 @@ def kpsul_perform_operations(request):
if is_addcost: if is_addcost:
operation.addcost_for = addcost_for operation.addcost_for = addcost_for
operation.addcost_amount = addcost_amount * operation.article_nb operation.addcost_amount = addcost_amount * operation.article_nb
operation.amount -= operation.addcost_amounty operation.amount -= operation.addcost_amount
to_addcost_for_balance += operation.addcost_amount to_addcost_for_balance += operation.addcost_amount
if operationgroup.on_acc.is_cash: if operationgroup.on_acc.is_cash:
to_checkout_balance += -operation.amount to_checkout_balance += -operation.amount
@ -584,6 +603,38 @@ def kpsul_perform_operations(request):
Article.objects.filter(pk=article.pk).update( Article.objects.filter(pk=article.pk).update(
stock = F('stock') + to_articles_stocks[article]) stock = F('stock') + to_articles_stocks[article])
# Websocket data
websocket_data = {}
websocket_data['opegroups'] = [{
'add': True,
'id': operationgroup.pk,
'amount': operationgroup.amount,
'checkout__name': operationgroup.checkout.name,
'at': operationgroup.at,
'valid_by__trigramme': ( operationgroup.valid_by and
operationgroup.valid_by.trigramme or None),
'on_acc__trigramme': operationgroup.on_acc.trigramme,
'opes': [],
}]
for operation in operations:
ope_data = {
'id': operation.pk, 'type': operation.type, 'amount': operation.amount,
'addcost_amount': operation.addcost_amount,
'addcost_for': addcost_for.trigramme,
'is_checkout': operation.is_checkout,
'article__name': operation.article and operation.article.name or None,
'article_nb': operation.article_nb,
'group_id': operationgroup.pk,
'canceled_by__trigramme': None, 'canceled_at': None,
}
websocket_data['opegroups'][0]['opes'].append(ope_data)
operationgroup.checkout.refresh_from_db()
websocket_data['checkouts'] = [{
'id': operationgroup.checkout.pk,
'balance': operationgroup.checkout.balance,
}]
print(operationgroup.checkout.balance)
consumers.KPsul.group_send('kfet.kpsul', websocket_data)
return JsonResponse(data) return JsonResponse(data)
@permission_required('kfet.is_team') @permission_required('kfet.is_team')
@ -668,10 +719,12 @@ def kpsul_cancel_operations(request):
data['errors']['negative'] = True data['errors']['negative'] = True
return JsonResponse(data, status=403) return JsonResponse(data, status=403)
with transaction.atomic():
canceled_by = required_perms and request.user.profile.account_kfet or None canceled_by = required_perms and request.user.profile.account_kfet or None
canceled_at = timezone.now()
with transaction.atomic():
(Operation.objects.filter(pk__in=opes) (Operation.objects.filter(pk__in=opes)
.update(canceled_by=canceled_by, canceled_at=timezone.now())) .update(canceled_by=canceled_by, canceled_at=canceled_at))
for account in to_accounts_balances: for account in to_accounts_balances:
Account.objects.filter(pk=account.pk).update( Account.objects.filter(pk=account.pk).update(
balance = F('balance') + to_accounts_balances[account]) balance = F('balance') + to_accounts_balances[account])
@ -685,7 +738,45 @@ def kpsul_cancel_operations(request):
Article.objects.filter(pk=article.pk).update( Article.objects.filter(pk=article.pk).update(
stock = F('stock') + to_articles_stocks[article]) stock = F('stock') + to_articles_stocks[article])
# Websocket data
websocket_data = { 'opegroups': [], 'opes': [] }
for opegroup in to_groups_amounts:
websocket_data['opegroups'].append({
'cancellation': True,
'id': opegroup.pk,
'amount': OperationGroup.objects.get(pk=opegroup.pk).amount,
})
for ope in opes:
websocket_data['opes'].append({
'cancellation': True,
'id': ope,
'canceled_by__trigramme': canceled_by.trigramme,
'canceled_at': canceled_at,
})
consumers.KPsul.group_send('kfet.kpsul', websocket_data)
data['canceled'] = opes data['canceled'] = opes
if opes_already_canceled: if opes_already_canceled:
data['warnings']['already_canceled'] = opes_already_canceled data['warnings']['already_canceled'] = opes_already_canceled
return JsonResponse(data) return JsonResponse(data)
@permission_required('kfet.is_team')
def kpsul_history(request):
opegroups_list = (OperationGroup.objects
.values(
'id', 'amount', 'at', 'checkout_id',
'valid_by__trigramme', 'on_acc__trigramme')
.select_related('valid_by', 'on_acc')
.filter(at__gt=timezone.now()-timedelta(hours=4)))
opegroups = { opegroup['id']:opegroup for opegroup in opegroups_list }
for opegroup in opegroups:
opegroups[opegroup]['opes'] = []
opes = (Operation.objects
.values(
'id', 'type', 'amount', 'addcost_amount', 'is_checkout',
'article__name', 'canceled_by__trigramme', 'canceled_at',
'addcost_for__trigramme', 'article_nb', 'group_id')
.filter(group__in=opegroups.keys()))
for ope in opes:
opegroups[ope['group_id']]['opes'].append(ope)
return JsonResponse({ 'opegroups': opegroups })

View file

@ -12,4 +12,8 @@ six==1.10.0
unicodecsv==0.14.1 unicodecsv==0.14.1
icalendar==3.10 icalendar==3.10
django-bootstrap-form==3.2.1 django-bootstrap-form==3.2.1
django-rest-framework==3.4.0 asgiref==0.14.0
daphne==0.14.3
channels==0.17.2
asgi-redis==0.14.0
channels=0.17.2