Calcul du hash lors du `storageToFields` car c'est la qu'on verra s'il y a de "réelles" modifications par l'utilisateur + Vérification du hash lors de `fieldsToStorage` [POUR LES PHONE.FICHES]

This commit is contained in:
xdrm-brackets 2016-10-21 14:11:47 +02:00
parent 0d38d1c684
commit 0e961f69b9
2 changed files with 68 additions and 67 deletions

View File

@ -42,41 +42,29 @@ inputPhoneFiche.prototype = {
inputPhoneFiche.prototype.fieldsToStorage = function(){
console.group('[phone.fiche] fields to storage');
// {1} Pour chaque formulaire de contact présent //
var i, l, deflater, deflated, existingData, obj, hash;
/* (1) Pour chaque formulaire de contact présent
---------------------------------------------------------*/
var existingFiches = $$('[data-sublink="phone"] article.relation-panel .fiche-relation');
for( var i = 0 ; i < existingFiches.length ; i++ ){
for( i = 0, l = existingFiches.length ; i < l ; i++ ){
// {2} On initialise notre deflater pour récupérer les valeurs //
var deflater = new FormDeflater(existingFiches[i], ['input', 'select'], ['data-name']);
/* (1) On initialise notre deflater pour récupérer les valeurs */
deflater = new FormDeflater(existingFiches[i], ['input', 'select'], ['data-name']);
// {3} On enregistre ce contact si le numéro n'est pas vide et soit pseudo/prénom/nom //
var deflated = deflater.deflate();
// On crée le hash
var deflatedHash = crc32(JSON.stringify(deflated));
/* (2) On récupère les données */
deflated = deflater.deflate();
/* (3) On récupère les données du LSI si elles existent */
existingData = lsi.get('p_fiches', deflated.uid);
// console.log( deflated );
// {4} On récupère les données du LSI si elles existent //
var existingData = lsi.get('p_fiches', deflated.uid);
// Si n'existe pas, on passe au suivant
// Si erreur, on passe à la fiche suivante
if( existingData === false )
continue;
// {5} On récupère et met en forme les valeurs du deflater //
// Si le hash est le même, on ne fait rien
if( existingData != null && existingData.hash != null )
if( existingData.hash === 0 )
console.log('FICHE#'+existingData.uid+' UPDATED BUT NO TIMESTAMP UPDATE');
else if( existingData.hash == deflatedHash )
return;
var obj = {
/* (4) On récupère et met en forme les valeurs du deflater */
obj = {
contact: parseInt(deflated.contact),
uid: parseInt(deflated.uid),
sexe: deflated.sexe,
@ -95,38 +83,30 @@ inputPhoneFiche.prototype.fieldsToStorage = function(){
contextSpecial: deflated.contextSpecial,
freq: deflated.freq,
connect: deflated.connect,
connectSpecial: deflated.connectSpecial,
hash: deflatedHash
connectSpecial: deflated.connectSpecial
};
/* (5) On calcule/compare le hash */
/* (6) On vérifie la validité des données et on l'enregistre dans l'objet avec la date de modification */
// {5.1} On calcule le hash //
hash = crc32( JSON.stringify(obj) );
// {5.2} Si le hash est identique, on ne fait rien //
if( existingData != null && existingData.hash != null && hash == existingData.hash )
continue;
// {5.3} On enregistre le hash //
obj.hash = hash;
/* (6) On calcule la validité des données */
obj.valid = this.check(obj);
// On met à jour la date de modification, si on a pas qu'@uid de différent
// {6.1} Si on doit mettre à jour //
if( existingData.hash !== 0 ){
/* (7) On met à jour le `timestamp` (car à ce point, on a une modification) */
obj.timestamp = Date.now();
console.warn('> FICHE UPDATE ('+(obj.timestamp-input_ts)+')');
// Si on a des modifications, on met à jour le `timestamp` //
if( diff(existingData, obj, ['hash', 'valid', 'timestamp']).length > 0 ){
console.log( diff(existingData, obj, ['hash', 'valid', 'timestamp']) );
obj.timestamp = Date.now();
console.warn('> FICHE UPDATE ('+(obj.timestamp-input_ts)+')');
}
if( existingData['timestamp'] == undefined || !isNaN(existingData.timestamp) )
obj.timestamp = Date.now();
// {6.2} Initialisation du `timestamp` si pas encore fait //
}else if( existingData['timestamp'] == undefined || !isNaN(existingData.timestamp) )
obj.timestamp = 0;
/* (7) On enregistre les données dans le 'localStorage' */
console.warn('saving fiche#'+obj.uid+' with timestamp of '+obj.timestam+' and hash of '+existingData.hash+' and now '+obj.hash);
/* (8) On enregistre les données dans le 'localStorage' */
lsi.set('p_fiches', obj.uid, obj);
}
@ -327,16 +307,38 @@ inputPhoneFiche.prototype.add = function(objectData){
inputPhoneFiche.prototype.storageToFields = function(){
console.group('[phone.fiche] storage to fields');
// {1} Pour chaque contact du 'localStorage' //
var clone, hash;
/* (1) On récupère les fiches du 'localStorage' */
var ficheData = lsi.export('p_fiches');
// On réinitialise le HTML
/* (2) On réinitialise le HTML */
this.container.innerHTML = '';
for( var key in ficheData )
if( ficheData[key].uid == this.selected )
/* (3) Pour chaque fiche */
for( var key in ficheData ){
// {3.1} Pour toutes les fiches //
// On enregistre le hash (sans `timestamp`, `hash`, `valid`)
clone = cloneObject( ficheData[key] );
delete clone['hash'];
delete clone['timestamp'];
delete clone['valid'];
ficheData[key].hash = crc32( JSON.stringify(clone) );
// On enregistre dans le `localStorage`
lsi.set('p_fiches', ficheData[key].uid, ficheData[key]);
// {3.2} Pour la fiche à rendre graphiquement //
if( ficheData[key].uid == this.selected ){
this.add(ficheData[key]);
}
}
// {4} On met à jour la navigation //
this.updateNavBar();

View File

@ -1,7 +1,6 @@
function inputPhoneFiche(a,c){this.container=a;this.nav_container=c;this.top_size=10}inputPhoneFiche.prototype={container:this.container,nav_container:this.nav_container,selected:0,handler:null,defaultData:{sexe:"2",age:".",job:".",famsit:"0",studies:"0",reltype:"0",reltypeSpecial:"",city:"",quartier:"",cp:"",loc:"0",duration:["",""],context:"0",contextSpecial:["","",""],freq:["4","9","14","19","24"],connect:"1 3 5 7 9 11".split(" "),connectSpecial:["",""],timestamp:0,valid:!1}};
inputPhoneFiche.prototype.fieldsToStorage=function(){console.group("[phone.fiche] fields to storage");for(var a=$$('[data-sublink="phone"] article.relation-panel .fiche-relation'),c=0;c<a.length;c++){var b=(new FormDeflater(a[c],["input","select"],["data-name"])).deflate(),h=crc32(JSON.stringify(b)),g=lsi.get("p_fiches",b.uid);if(!1!==g){if(null!=g&&null!=g.hash)if(0===g.hash)console.log("FICHE#"+g.uid+" UPDATED BUT NO TIMESTAMP UPDATE");else if(g.hash==h)return;b={contact:parseInt(b.contact),uid:parseInt(b.uid),
sexe:b.sexe,age:b.age,job:b.job,famsit:b.famsit,studies:b.studies,reltype:b.reltype,reltypeSpecial:b.reltypeSpecial,city:b.city,quartier:b.quartier,cp:b.cp,loc:b.loc,duration:b.duration,context:b.context,contextSpecial:b.contextSpecial,freq:b.freq,connect:b.connect,connectSpecial:b.connectSpecial,hash:h};b.valid=this.check(b);0!==g.hash?(0<diff(g,b,["hash","valid","timestamp"]).length&&(console.log(diff(g,b,["hash","valid","timestamp"])),b.timestamp=Date.now(),console.warn("> FICHE UPDATE ("+(b.timestamp-
input_ts)+")")),void 0!=g.timestamp&&isNaN(g.timestamp)||(b.timestamp=Date.now())):void 0!=g.timestamp&&isNaN(g.timestamp)||(b.timestamp=0);console.warn("saving fiche#"+b.uid+" with timestamp of "+b.timestam+" and hash of "+g.hash+" and now "+b.hash);lsi.set("p_fiches",b.uid,b)}}console.groupEnd()};
inputPhoneFiche.prototype.fieldsToStorage=function(){console.group("[phone.fiche] fields to storage");var a,c,b,d,k,e=$$('[data-sublink="phone"] article.relation-panel .fiche-relation');a=0;for(c=e.length;a<c;a++)if(b=new FormDeflater(e[a],["input","select"],["data-name"]),d=b.deflate(),b=lsi.get("p_fiches",d.uid),!1!==b&&(d={contact:parseInt(d.contact),uid:parseInt(d.uid),sexe:d.sexe,age:d.age,job:d.job,famsit:d.famsit,studies:d.studies,reltype:d.reltype,reltypeSpecial:d.reltypeSpecial,city:d.city,
quartier:d.quartier,cp:d.cp,loc:d.loc,duration:d.duration,context:d.context,contextSpecial:d.contextSpecial,freq:d.freq,connect:d.connect,connectSpecial:d.connectSpecial},k=crc32(JSON.stringify(d)),null==b||null==b.hash||k!=b.hash))d.hash=k,d.valid=this.check(d),d.timestamp=Date.now(),console.warn("> FICHE UPDATE ("+(d.timestamp-input_ts)+")"),lsi.set("p_fiches",d.uid,d);console.groupEnd()};
inputPhoneFiche.prototype.add=function(a){if(null==a.uid||isNaN(a.uid)||null==a.contact||isNaN(a.contact))return!1;a.city=null!=a.city?a.city:this.defaultData.city;a.quartier=null!=a.quartier?a.quartier:this.defaultData.quartier;a.cp=null!=a.cp?a.cp:this.defaultData.cp;a.duration[0]=null!=a.duration[0]?a.duration[0]:this.defaultData.duration[0];a.duration[1]=null!=a.duration[1]?a.duration[1]:this.defaultData.duration[1];a.reltypeSpecial=null!=a.reltypeSpecial?a.reltypeSpecial:this.defaultData.reltypeSpecial;
a.contextSpecial[0]=null!=a.contextSpecial[0]?a.contextSpecial[0]:this.defaultData.contextSpecial[0];a.contextSpecial[1]=null!=a.contextSpecial[1]?a.contextSpecial[1]:this.defaultData.contextSpecial[1];a.contextSpecial[2]=null!=a.contextSpecial[2]?a.contextSpecial[2]:this.defaultData.contextSpecial[2];a.connectSpecial[0]=null!=a.connectSpecial[0]?a.connectSpecial[0]:this.defaultData.connectSpecial[0];a.connectSpecial[1]=null!=a.connectSpecial[1]?a.connectSpecial[1]:this.defaultData.connectSpecial[1];
a.job=null!=a.job?a.job:this.defaultData.job;a.studies=null!=a.studies?a.studies:this.defaultData.studies;a.age=null!=a.age?a.age:this.defaultData.age;a.sexe=null!=a.sexe?a.sexe:this.defaultData.sexe;a.famsit=null!=a.famsit?a.famsit:this.defaultData.famsit;a.reltype=null!=a.reltype?a.reltype:this.defaultData.reltype;a.loc=null!=a.loc?a.loc:this.defaultData.loc;a.context=null!=a.context?a.context:this.defaultData.context;a.freq=null!=a.freq?a.freq:this.defaultData.freq;a.connect=null!=a.connect?a.connect:
@ -12,13 +11,13 @@ contextspecial2:a.contextSpecial[2],connectspecial0:a.connectSpecial[0],connects
a.uid+'"] ~ h5>input[type="radio"][data-name="famsit"]');for(c=0;c<b.length;c++)b[c].value==a.famsit?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked");b=$$('[data-sublink="phone"] article.fiche-relation input[data-name="uid"][value="'+a.uid+'"] ~ h5>input[type="radio"][data-name="reltype"]');for(c=0;c<b.length;c++)b[c].value==a.reltype?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked");b=$$('[data-sublink="phone"] article.fiche-relation input[data-name="uid"][value="'+
a.uid+'"] ~ h5>input[type="radio"][data-name="loc"]');for(c=0;c<b.length;c++)b[c].value==a.loc?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked");b=$$('[data-sublink="phone"] article.fiche-relation input[data-name="uid"][value="'+a.uid+'"] ~ h5>input[type="radio"][data-name="context"]');for(c=0;c<b.length;c++)b[c].value==a.context?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked");b=$$('[data-sublink="phone"] article.fiche-relation input[data-name="uid"][value="'+
a.uid+'"] ~ h5>input[type="radio"][data-name="freq"]');for(c=0;c<b.length;c++)-1<a.freq.indexOf(b[c].value)?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked");b=$$('[data-sublink="phone"] article.fiche-relation input[data-name="uid"][value="'+a.uid+'"] ~ h5>input[type="radio"][data-name="connect"]');for(c=0;c<b.length;c++)-1<a.connect.indexOf(b[c].value)?b[c].setAttribute("checked","checked"):b[c].removeAttribute("checked")};
inputPhoneFiche.prototype.storageToFields=function(){console.group("[phone.fiche] storage to fields");var a=lsi["export"]("p_fiches");this.container.innerHTML="";for(var c in a)a[c].uid==this.selected&&this.add(a[c]);this.updateNavBar();console.groupEnd()};
inputPhoneFiche.prototype.sync=function(){console.group("[phone.fiche] synchronisation");var a=lsi["export"]("p_contacts"),c=[],b,h=lsi.keys("p_contacts").length<2*this.top_size?lsi.keys("p_contacts").length:2*this.top_size,g;for(g in a){for(ficheUid=0;-1<c.indexOf(ficheUid)&&ficheUid<h;)ficheUid++;c.push(ficheUid);a=lsi.get("p_fiches",ficheUid);!a&&(a=this.defaultData);a.uid=ficheUid;a.contact=parseInt(g);lsi.set("p_fiches",ficheUid,a);if(c.length>=h)break}var d,e,k,h={};g={};var a=lsi["export"]("p_fiches"),
c=lsi["export"]("p_mini-fiches"),l;for(l in a)if(d=lsi.get("p_contacts",a[l].contact),!(0<d.username.length&&void 0!=h[d.username]||0==d.username.length&&void 0!=g[d.existing])&&(0<d.username.length?h[d.username]=0:g[d.existing]=0,d)){var f=[["fiche",a[l]]];for(b in a)e=lsi.get("p_contacts",a[b].contact),b!=l&&e&&(k=0<e.username.length&&d.username===e.username,e=!isNaN(e.existing)&&d.existing===e.existing,(k||e)&&f.push(["fiche",a[b]]));for(b in c)e=lsi.get("p_contacts",c[b].contact),k=0<e.username.length&&
d.username===e.username,e=!isNaN(e.existing)&&d.existing===e.existing,(k||e)&&f.push(["mini",c[b]]);if(1!==f.length){k=[];for(b in f)k[b]=f[b][1].hasOwnProperty("timestamp")?f[b][1].timestamp:0;e=k.indexOf(Math.max.apply(Math,k));for(b in f)b!=e&&(f[b][0]==f[e][0]?(console.warn("copying fiche#"+f[e][1].uid+" to fiche#"+f[b][1].uid,k[e]-input_ts,k[b]-input_ts),d=cloneObject(f[e][1]),d.uid=f[b][1].uid,d.hash=0,lsi.set("p_fiches",d.uid,d)):"fiche"==f[e][0]?(console.warn("copying fiche#"+f[e][1].uid+
" to mini#"+f[b][1].uid,k[e]-input_ts,k[b]-input_ts),d=cloneObject(f[b][1]),d.age=f[e][1].age,d.sexe=f[e][1].sexe,d.loc=f[e][1].loc,d.reltype=f[e][1].reltype,d.reltypeSpecial=f[e][1].reltypeSpecial,d.hash=0,lsi.set("p_mini-fiches",d.uid,d)):(console.warn("copying mini#"+f[e][1].uid+" to fiche#"+f[b][1].uid,k[e]-input_ts,k[b]-input_ts),d=cloneObject(f[b][1]),d.age=f[e][1].age,d.sexe=f[e][1].sexe,d.loc=f[e][1].loc,d.reltype=f[e][1].reltype,d.reltypeSpecial=f[e][1].reltypeSpecial,d.hash=0,lsi.set("p_fiches",
d.uid,d)))}}console.groupEnd()};inputPhoneFiche.prototype.nav=function(a){if(!(a instanceof Element&&a.getData("n"))||isNaN(a.getData("n"))||"p_nav-fiche"!=a.parentNode.id)return!1;for(var c=$$('[data-sublink="phone"] #p_nav-fiche > span.active'),b=0;b<c.length;b++)c[b].remClass("active");a.addClass("active");this.selected=parseInt(a.getData("n"))};
inputPhoneFiche.prototype.updateNavBar=function(){var a=lsi["export"]("p_fiches");this.nav_container.innerHTML="";for(var c=Object.keys(a),b=0;b<c.length;b++){var h=parseInt(c[b]);0==h&&(this.nav_container.innerHTML+="<span>APPELS</span>");20>h&&b<c.length-1&&20<=c[b+1]?this.nav_container.innerHTML+='<span data-n="'+h+'" class="lc">'+(h%20+1)+"</span>&nbsp;&nbsp;":(20==h&&(this.nav_container.innerHTML+='<br><span class="fc">&nbsp;&nbsp; SMS &nbsp;&nbsp;</span>'),this.nav_container.innerHTML+='<span data-n="'+
h+'">'+(h%20+1)+"</span>")}for(var g in a)c=$('[data-sublink="phone"] #p_nav-fiche [data-n="'+a[g].uid+'"]'),null!=c&&(!0===a[g].valid?c.addClass("done"):c.remClass("done"));this.nav($('[data-sublink="phone"] #p_nav-fiche [data-n="'+this.selected+'"]'))};
inputPhoneFiche.prototype.storageToFields=function(){console.group("[phone.fiche] storage to fields");var a,c=lsi["export"]("p_fiches");this.container.innerHTML="";for(var b in c)a=cloneObject(c[b]),delete a.hash,delete a.timestamp,delete a.valid,c[b].hash=crc32(JSON.stringify(a)),lsi.set("p_fiches",c[b].uid,c[b]),c[b].uid==this.selected&&this.add(c[b]);this.updateNavBar();console.groupEnd()};
inputPhoneFiche.prototype.sync=function(){console.group("[phone.fiche] synchronisation");var a=lsi["export"]("p_contacts"),c=[],b,d=lsi.keys("p_contacts").length<2*this.top_size?lsi.keys("p_contacts").length:2*this.top_size,k;for(k in a){for(ficheUid=0;-1<c.indexOf(ficheUid)&&ficheUid<d;)ficheUid++;c.push(ficheUid);a=lsi.get("p_fiches",ficheUid);!a&&(a=this.defaultData);a.uid=ficheUid;a.contact=parseInt(k);lsi.set("p_fiches",ficheUid,a);if(c.length>=d)break}var e,f,h,d={};k={};var a=lsi["export"]("p_fiches"),
c=lsi["export"]("p_mini-fiches"),l;for(l in a)if(e=lsi.get("p_contacts",a[l].contact),!(0<e.username.length&&void 0!=d[e.username]||0==e.username.length&&void 0!=k[e.existing])&&(0<e.username.length?d[e.username]=0:k[e.existing]=0,e)){var g=[["fiche",a[l]]];for(b in a)f=lsi.get("p_contacts",a[b].contact),b!=l&&f&&(h=0<f.username.length&&e.username===f.username,f=!isNaN(f.existing)&&e.existing===f.existing,(h||f)&&g.push(["fiche",a[b]]));for(b in c)f=lsi.get("p_contacts",c[b].contact),h=0<f.username.length&&
e.username===f.username,f=!isNaN(f.existing)&&e.existing===f.existing,(h||f)&&g.push(["mini",c[b]]);if(1!==g.length){h=[];for(b in g)h[b]=g[b][1].hasOwnProperty("timestamp")?g[b][1].timestamp:0;f=h.indexOf(Math.max.apply(Math,h));for(b in g)b!=f&&(g[b][0]==g[f][0]?(console.warn("copying fiche#"+g[f][1].uid+" to fiche#"+g[b][1].uid,h[f]-input_ts,h[b]-input_ts),e=cloneObject(g[f][1]),e.uid=g[b][1].uid,e.hash=0,lsi.set("p_fiches",e.uid,e)):"fiche"==g[f][0]?(console.warn("copying fiche#"+g[f][1].uid+
" to mini#"+g[b][1].uid,h[f]-input_ts,h[b]-input_ts),e=cloneObject(g[b][1]),e.age=g[f][1].age,e.sexe=g[f][1].sexe,e.loc=g[f][1].loc,e.reltype=g[f][1].reltype,e.reltypeSpecial=g[f][1].reltypeSpecial,e.hash=0,lsi.set("p_mini-fiches",e.uid,e)):(console.warn("copying mini#"+g[f][1].uid+" to fiche#"+g[b][1].uid,h[f]-input_ts,h[b]-input_ts),e=cloneObject(g[b][1]),e.age=g[f][1].age,e.sexe=g[f][1].sexe,e.loc=g[f][1].loc,e.reltype=g[f][1].reltype,e.reltypeSpecial=g[f][1].reltypeSpecial,e.hash=0,lsi.set("p_fiches",
e.uid,e)))}}console.groupEnd()};inputPhoneFiche.prototype.nav=function(a){if(!(a instanceof Element&&a.getData("n"))||isNaN(a.getData("n"))||"p_nav-fiche"!=a.parentNode.id)return!1;for(var c=$$('[data-sublink="phone"] #p_nav-fiche > span.active'),b=0;b<c.length;b++)c[b].remClass("active");a.addClass("active");this.selected=parseInt(a.getData("n"))};
inputPhoneFiche.prototype.updateNavBar=function(){var a=lsi["export"]("p_fiches");this.nav_container.innerHTML="";for(var c=Object.keys(a),b=0;b<c.length;b++){var d=parseInt(c[b]);0==d&&(this.nav_container.innerHTML+="<span>APPELS</span>");20>d&&b<c.length-1&&20<=c[b+1]?this.nav_container.innerHTML+='<span data-n="'+d+'" class="lc">'+(d%20+1)+"</span>&nbsp;&nbsp;":(20==d&&(this.nav_container.innerHTML+='<br><span class="fc">&nbsp;&nbsp; SMS &nbsp;&nbsp;</span>'),this.nav_container.innerHTML+='<span data-n="'+
d+'">'+(d%20+1)+"</span>")}for(var k in a)c=$('[data-sublink="phone"] #p_nav-fiche [data-n="'+a[k].uid+'"]'),null!=c&&(!0===a[k].valid?c.addClass("done"):c.remClass("done"));this.nav($('[data-sublink="phone"] #p_nav-fiche [data-n="'+this.selected+'"]'))};
inputPhoneFiche.prototype.check=function(a){if(2>a.city.length||isNaN(parseInt(a.duration[0]))&&0<a.duration[0].length||isNaN(parseInt(a.duration[1]))&&0<a.duration[1].length||0==a.duration[0].length+a.duration[1].length||"."==a.job||"."==a.studies||"."==a.age||""==a.sexe||""==a.famsit||""==a.reltype||""==a.loc||""==a.context)return!1;for(var c=0;c<a.freq.length;c++)if(""==a.freq[c])return!1;for(c=0;c<a.connect.length;c++)if(""==a.connect[c])return!1;return"10"==a.reltype&&2>a.reltypeSpecial.length||
"11"==a.context&&2>a.contextSpecial[0].length||"12"==a.context&&2>a.contextSpecial[1].length||"13"==a.context&&2>a.contextSpecial[2].length?!1:!0};inputPhoneFiche.prototype.attach=function(a){console.group("[phone.fiche] attaching events");lsi.createDataset("p_fiches");this.storageToFields();this.handler=a;this.nav_container.addEventListener("click",function(a){this.nav(a.target);this.handler(a.target)}.bind(this),!1);console.groupEnd()};