from connectEficas import accasConnecteur
code='Essai'
-from flask import Flask, request, render_template, url_for, jsonify, make_response
+from flask import Flask, request, render_template, url_for, jsonify, make_response, session, g, Response
# from flask import Flask, request, render_template, url_for, json, jsonify
import json
import pprint
-from forms import BasicForm
-from collections import OrderedDict
+from forms import BasicForm
+from collections import OrderedDict
+from markupsafe import escape
+
+from flask_sse import sse
+
+# For example, you may want to override how request parameters are handled to preserve their order:
+# from flask import Flask, Request
+# from werkzeug.datastructures import ImmutableOrderedMultiDict
+# class MyRequest(Request):
+# """Request subclass to override request parameter storage"""
+# parameter_storage_class = ImmutableOrderedMultiDict
+# class MyFlask(Flask):
+# """Flask subclass using the custom request class"""
+# request_class = MyReq
def createConnecteur():
monConnecteur=accasConnecteur(code, langue='ang')
print (monConnecteur.getListeCommandes())
app = Flask(__name__)
+#Server Side Event config
+app.config["REDIS_URL"] = "redis://localhost"
+#app.config["REDIS_URL"] = "redis://:password@localhost"
+#TODO: personaliser l'url en fonction de la session utilisateur
+app.register_blueprint(sse, url_prefix='/stream')
+
+@app.route('/update')
+def publish_update():
+ sse.publish({"message": "Hello!"}, type='update')
+ return "Message sent!"
@app.route('/')
def index():
# Print the dictionary
print(req)
print(req['id'])
- id,data = req.values()
- data = str(data) #Oups PN
- #comments,changeIsAccepted = monConnecteur.changeValeur(id,data);
- changeDone = monConnecteur.changeValeur(id,data);
- changeDone = False
+ id=req['id'];value=req['value']
+ # id, value = req.values() # Dangereux correspondance implicite
+ value = str(value) #Oups PN
+ changeDone = monConnecteur.changeValeur(id,value);
+ changeDone = True
print ("changeDone : ",changeDone)
- # Ne pas récupérer le noeud dans le cas du SIMP (le changeDone et l''ancienne valeur ds la WebApp suffit
+ # Ne pas récupérer et ne pas renvoyer le noeud dans le cas du SIMP
+ # (le changeDone et l''ancienne valeur ds la WebApp suffit
node = monConnecteur.getDicoForFancy(monConnecteur.monEditeur.getNodeById(id))
print("node :",node)
- # myTreeDico=monConnecteur.getDicoObjetsCompletsPourTree(req['id'])
- # print("myTreeDico :",myTreeDico)
# return jsonify([myTreeDico])
- # return make_response(json.dumps([myTreeDico]))
- #return make_response(json.dumps([monConnecteur.getDicoObjetsCompletsPourTree(monConnecteur.monEditeur.tree.racine)]))
+
return make_response(json.dumps( {'source':node, 'changeIsAccepted' : changeDone} ))
- # # Return a string along with an HTTP status code
- # return "JSON received!", 200
+ # Return a string along with an HTTP status code
+ # return "JSON received!", 200
else:
# The request body wasn't JSON so return a 400 HTTP status code
return "Request was not JSON", 400
+ #return make_response(jsonify({"message": "Request body must be JSON"}), 400)
## SSE from Eficas signals :
# - Validite
<!-- </style> -->
<script>
-
-function getTree1() {
- // Some logic to retrieve, or generate tree structure
- return {{ tree|tojson }};
-}
+
+ var source = new EventSource("{{ url_for('sse.stream') }}");
+ source.addEventListener('update', function(event) {
+ var data = JSON.parse(event.data);
+ alert("The server says " + data.message);
+ }, false);
+ source.addEventListener('error', function(event) {
+ alert("Failed to connect to event stream. Is Redis running?");
+ }, false);
+
+ function getTree1() {
+ // Some logic to retrieve, or generate tree structure
+ return {{ tree|tojson }};
+ }
-function getTree2() {
- // Some logic to retrieve, or generate tree structure
-return {{ mcTraiteJson|tojson }};
-}
+ function getTree2() {
+ // Some logic to retrieve, or generate tree structure
+ return {{ mcTraiteJson|tojson }};
+ }
<!-- $('#tree1').treeview({ data: getTree1() }) -->
$(function(){
$("#tree1").fancytree({
+ //focusOnSelect:true,
+ debug:4,
//extensions: ["dnd5", "edit", "glyph", "wide", "table", "gridnav"],
extensions: [ "glyph", "table", "ariagrid"],
//extensions: [ "glyph", "table", "gridnav"],
checkbox: true, // Activate the use of checkboxes next to the nodes
- <!-- selectMode: 3, -->
+
+ // selectMode: 1: single selection
+ // Only one node is selected at any time.
+ // selectMode: 2: multiple selection (default)
+ // Every node may be selected independently.
+ // selectMode: 3: hierarchical selection
+ // (De)selecting a node will propagate to all descendants. Mixed states will be displayed as partially selected using a tri-state checkbox.
+
selectMode: 1,
- dnd5: {
+ dnd5: { // unused drag&drop module
dragStart: function(node, data) { return true; },
dragEnter: function(node, data) { return true; },
- dragDrop: function(node, data) { data.otherNode.copyTo(node, data.hitMode); }
+ dragDrop : function(node, data) { data.otherNode.copyTo(node, data.hitMode); }
},
glyph: glyph_opts,
source: JSON.parse(getTree1()),
//lazyLoad: function(event, data) {
// data.result = {url: "ajax-sub2.json", debugDelay: 1000};
//}
-
+ // renderStatusColumns: Pour le CSS
renderColumns: function(event, data) {
+ // Pour tester ds la console :
//var tree=$.ui.fancytree.getTree("#tree1")
//p1=tree.getNodeByKey('8304986a334211ec853cac220bca9aa6')
//$(p1.tr).find(">td")
-
+
+ //import {createTree, version} from 'jquery.fancytree'
+ //const tree = createTree('#tree', { ... });
+ //var node = tree.getActiveNode();
+
var node = data.node,
$tdList = $(node.tr).find(">td");
var _attr=''
"<form class='was-validated'>"+ //'was-validated' ??
"<div class='form-group'>" +
// "<div class='form-group "+ _attr + "'>" +
- // "<div class='form-group has-error'>" +
+ // "<div class='form-group has-error'>" +
"<input type='input' class='form-control' id='simp1' placeholder='" + node.data.wValue + //TODO:intosugg
"' value='"+node.data.wValue+"' required>"+
//"<div class='valid-feedback'>Valid.</div>"+
)
.addClass(_attr)
.find("input").css('color','black'); //TODO : A placer ds le CSS
- //$tdList.eq(1).css('back-ground,'green') // Update the checkbox validation state TODO: create a CSS class
-
- //$tdList.eq(3).css('color','black') //td
- //$tdList.eq(3).find("input").css('color','black')
-<!-- $tdList.eq(3).html("<simp>"+node.data.wValue+"</simp>"); -->
} else {
- $tdList.eq(2).prop("colspan", 3).nextAll().remove();
+ $tdList.eq(2).prop("colspan", 3).nextAll().remove(); //Merge unused columns for easy keyboard navigation
return;
}
},
- icon: function(event, data) {
- if( data.node.type ) {
- return "ft-ico-" + data.node.type;
- }
- },
- activate: function(event, data) {
- console.log("event.type, data :"+event.type+" , "+data);
- },
- focusTree: function(event, data) {
- console.log("event.type, data :"+event.type+" , "+data);
- },
- activateCell: function(event, data) {
- console.log("event.type, data :"+event.type+" , "+data);
- },
- defaultGridAction: function( event, data ) {
+ defaultGridAction: function( event, data ) { //(used by ext-aria) The user hit enter on the active row or cell.
var node = data.node
- var rValue,rValidite
+ var rValue,rValidite,rChangeIsAccepted
if (node.data.classeAccas == "MCSIMP") {
$input=$(node.tr).find('input')
// Called when ENTER is pressed in cell-mode.
// Return false to prevent default
+ //data.activeTd contains the currently active <td> element or null
+ //data.colIdx contains the 0-based column index or -1
console.log("event.type, data :"+event.type+" , "+data);
if( !data.activeTd ) {
alert( "Custom default action for row: " + data.node.title );
$.ajax({
type : "POST",
url : "{{ url_for('updateSimp') }}",
- data : JSON.stringify({id: node.key, data:value }),
+ data : JSON.stringify({id: node.key, value:value }),
contentType : "application/json; charset=utf-8",
dataType : "json",
// The callback function when the web service return success.
success: function(data, status) {
- alert("Data: " + data + "\nStatus: " + status +"\ndata.changeIsAccepted :" +data.changeIsAccepted );
- rValue=data.source['wValue']; rValidite=data.source['validite'];
+ alert("Successfully Value Sent: " + value + "\nStatus: " + status +"\ndata.changeIsAccepted :" +data.changeIsAccepted );
+ rChangeIsAccepted = data.changeIsAccepted;
+ rValue = data.source['wValue'];
+ rValidite = data.source['validite'];
console.log( {'data': data } );
console.log( {'rValue': rValue } );
console.log( {'rValidite': rValidite } );
+ console.log( {'rChangeIsAccepted': rChangeIsAccepted } );
//node.fromDict()
//source=JSON.parse(getTree1())
+ if ( rChangeIsAccepted ) {
node.data.wValue = rValue
node.data.validite = rValidite
+//node.data = data.source ?? Essayer de remplacer la source complète du noeud
console.log('rValue : '+rValue);
console.log('rValidite : '+rValidite);
+ } else {
+// Gérer le input pour laisser le focus et passer en rouge
+ };
node.render(true,false); //force rendering the node (not parents nor descendants)
+//node.renderStatus(); //CSS element updates
},
// The callback function when the web service return fail.
failure: function(errMsg) {
alert(errMsg);
}
})
-//node.render(true,false); //force rendering the node (not parents nor descendants)
-//node.renderStatus(); //CSS element updates
}
},
lazyLoad: function(event, data) {
data: {key: node.key}
}
},
+ icon: function(event, data) {
+ if( data.node.type ) {
+ return "ft-ico-" + data.node.type;
+ }
+ },
+ activate: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ deactivate: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ beforeActivate: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ beforeSelect: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ activateCell: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ select: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ beforeUpdateViewport: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ click: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ blur: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ blurTree: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ focusTree: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+ keydown: function(event, data) {
+ console.log("event.type, data :"+event.type+" , "+data);
+ },
+
});
});