Advertisement
Nikoh77

Untitled

Nov 4th, 2022
1,529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var WebSocketServer = require('websocket').server;
  2. var http = require('http');
  3. const axios = require('axios');
  4. var log = require('npmlog')
  5. const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");
  6.  
  7. var logfile = require('npmlog-file')
  8. // write everything npmlog has logged thus far to log.txt
  9.  
  10.  
  11. var server = http.createServer(function (request, response) {
  12.     // Qui possiamo processare la richiesta HTTP
  13.     // Dal momento che ci interessano solo le WebSocket, non dobbiamo implementare nulla
  14. });
  15. server.listen(8080, function () { });
  16. log.info('avvio', 'server websocket in ascolto sulla porta 8080')
  17. logfile.write(log, 'log.txt');
  18.  
  19. const debug_attivo = false;
  20.  
  21.  
  22. // Creazione del server
  23. wsServer = new WebSocketServer({
  24.     httpServer: server
  25. });
  26. function zeroPad(num, places) {
  27.     var zero = places - num.toString().length + 1;
  28.     return Array(+(zero > 0 && zero)).join("0") + num;
  29. }
  30.  
  31. if(debug_attivo){
  32.     setInterval(() => {log.info('ping', 'stato servizio'); logfile.write(log, 'log.txt');}, 5000);
  33. }
  34.  
  35. // Gestione degli eventi
  36. wsServer.on('request', function (request) {
  37.     var connection = request.accept(null, request.origin);
  38.     connection.on('message', function (message) {
  39.         // Metodo eseguito alla ricezione di un messaggio
  40.         if (message.type === 'utf8') {
  41.             // Se il messaggio è una stringa, possiamo leggerlo come segue:
  42.             //console.log('Il messaggio ricevuto è: ' + message.utf8Data);
  43.             log.info('messaggio', 'messaggio ricevuto',message.utf8Data)
  44.             const doc = JSON.parse(message.utf8Data);
  45.             genera_rch(doc,connection)
  46.         }
  47.     });
  48.     connection.on('close', function (connection) {
  49.         log.info('chiusuraconn', 'connessione client chiusa')
  50.     });
  51. });
  52. wsServer.on("close", () => {
  53.     log.info('chiusura', 'connessione client chiusa')
  54.     logfile.write(log, 'log.txt');
  55. });
  56. wsServer.on("connection", () => {
  57.     log.info('connection', 'nuova connessione')
  58.     logfile.write(log, 'log.txt');
  59. });
  60. wsServer.on("message", (messaggio) => {
  61.     log.info('message', 'nuova messaggio',messaggio)
  62.     logfile.write(log, 'log.txt');
  63. });
  64.  
  65. function genera_rch(documento,conn) {
  66.     log.info('genera_rch', 'messaggio ricevuto',documento)
  67.     var comandi = [];
  68.     if (documento.modellostampante == 'RCH' || true) {
  69.         if(documento.tipo =='COMANDO'){
  70.             if(documento.comando =='ANNULLASCONTRINO'){
  71.                 let parametri = documento.parametri_comando.split(";")
  72.                 let data_annullo = parametri[2];
  73.                 const anno = data_annullo.substring(2, 4);
  74.                 const mese = data_annullo.substring(4, 6);
  75.                 const giorno = data_annullo.substring(6, 8);
  76.                 const chiusura = parametri[0];
  77.                 const progressivo = parametri[1];
  78.    
  79.                 const data = giorno+mese+anno
  80.                 comandi.push("=k/&"+data+"/[" + chiusura  + "/]" + progressivo);
  81.                 comandi.push("=K");
  82.             }
  83.             if(documento.comando =='CHIUSURAGG'){
  84.                 comandi.push('=C3');
  85.                 comandi.push('=C10');
  86.                 comandi.push('=C1');
  87.             }
  88.             if(documento.comando =='RISTAMPAULTIMO'){
  89.                 comandi.push('=C1');
  90.                 comandi.push('=T5');
  91.                 comandi.push('=K');
  92.             }
  93.         }
  94.  
  95.  
  96.         if(documento.tipo =='SCNT'){
  97.            
  98.             if (documento.reso == 1) {
  99.                 // this.doSend('"' + documento.azzreso.padStart(4,'0') + '-' + documento.progreso.padStart(4,'0') + '"51F');
  100.             }
  101.    
  102.    
  103.             if (documento.testata.cf) {
  104.                 comandi.push('="/?C/(' + documento.testata.cf + ')');
  105.             }
  106.             // Codice Lotteria
  107.             if (documento.testata.codicelotteria) {
  108.                 comandi.push('="/?L/$1/(' + documento.testata.codicelotteria + ')');
  109.             }
  110.    
  111.             var riga_prec_is_sconto = false;
  112.             let tot = 0;
  113.             documento.righe.forEach(function (element) {
  114.                 element.Descrizione = element.Descrizione.replace('(', '[');
  115.                 element.Descrizione = element.Descrizione.replace(')', ']');
  116.                 var importo = Number(element.Importo);
  117.                 if (importo == 0) {
  118.                     comandi.push('="/(' + element.Descrizione.substr(0, 30) + ')');
  119.                 }
  120.                 if (element.Importo > 0) {
  121.                     comandi.push('=R' + element.Reparto + "/$" + element.Importo + "/*" + element.Quantita + "/(" + element.Descrizione.substr(0, 30) + ")");
  122.                     riga_prec_is_sconto = false;
  123.                 }
  124.                 else if (element.Importo < 0) {
  125.                     comandi.push('=S');
  126.                     importo *= -1;
  127.                     comandi.push('=V/$' + importo + '/(' + element.Descrizione.substr(0, 30) + ')');
  128.                 }
  129.    
  130.                 var lunghezza_max_riga = 30;
  131.                 if (element.Descrizione.length > lunghezza_max_riga) {
  132.                     var chunks = element.Descrizione.match(/.{1,30}/g);
  133.                     for (var i = 1; i < chunks.length; i++) {
  134.                         comandi.push('="/(' + chunks[i] + ')');
  135.                     }
  136.    
  137.                 }
  138.    
  139.                 tot += importo
  140.    
  141.             });
  142.    
  143.             if (documento.reso == 0) {
  144.                 if (documento.scadenze.length == 0) {
  145.                     let scad = { Data: '', Pagamento: documento.pagamento, Tipo: '', Incassata: 0, Descrizione: '', Importo: tot, TipoRT: '' }
  146.                 }
  147.                 for (i = 0; i < documento.scadenze.length; i++) {
  148.                     var item = documento.scadenze[i];
  149.                     if (item.TipoRT != '') {
  150.                         comandi.push('=T' + item.Pagamento + '/$' + item.Importo);
  151.                     }
  152.                     else if (item.Incassata == 1) {
  153.                         comandi.push('=T' + item.Pagamento + '/$' + item.Importo);
  154.                     } else {
  155.                         comandi.push('=T2/$' + item.Importo);
  156.                     }
  157.                 }
  158.             }
  159.    
  160.    
  161.             if (documento.doppia_copia > 0) { //seconda copia
  162.                 comandi.push('=C1');
  163.                 comandi.push('=T5');
  164.                 comandi.push('=C1');
  165.                 comandi.push('=K');
  166.             }
  167.    
  168.         }
  169.  
  170.         log.info('invio comandi', 'messaggio ricevuto',comandi)
  171.         if(comandi.length > 0){
  172.             inviaComandoHTTP_RCH(comandi, documento.ip)
  173.             .then(r=>{
  174.                 //const parser = new DOMParser();
  175.                 //const doc = parser.parseFromString(r.data, "application/xml");
  176.                 const options = {
  177.                     ignoreAttributes: false,
  178.                     attributeNamePrefix : "@_",
  179.                     allowBooleanAttributes: true
  180.                 };
  181.                 const parser = new XMLParser(options);
  182.                 let doc = parser.parse(r.data);
  183.  
  184.  
  185.                 log.info('risposta', 'da printf',doc)
  186.                 //let success =doc.response['@_success'];
  187.                 let error_code = doc.Service.Request.errorCode;
  188.                 let success = doc.Service.Request.errorCode == 0
  189.                 if(success){
  190.                     let zRepNumber =  Number(doc.Service.Request.lastZ)+1;
  191.                     let fiscalReceiptNumber = doc.Service.Request.lastDocF;
  192.  
  193.                     const d = new Date();
  194.                     let text = d.toJSON();
  195.                     let yymmdd = text.substring(2,4) + text.substring(5,7)+ text.substring(8,10)
  196.                     let hhmm = text.substring(11,13)+text.substring(14,16)
  197.  
  198.                     let retval = yymmdd + hhmm +"F"+zeroPad(fiscalReceiptNumber,5)+"A"+zeroPad(zRepNumber,5)
  199.                     let msg = "docprinted:" + retval + ":" + documento.testata.iddocumento
  200.                     log.info('invio risposta', 'documento stampato',msg)
  201.                     conn.send(msg);
  202.                 }
  203.                 else{
  204.                     let msg="ERR "+error_code;
  205.                     conn.send(msg);
  206.                 }
  207.  
  208.             })
  209.             .catch(err=>{
  210.                 log.error('errore', 'errore durante la comunicazione con printf',err);
  211.             })
  212.  
  213.         }
  214.        
  215.  
  216.     }
  217. }
  218.  
  219. function inviaComandoHTTP_RCH(comandi, ip) {
  220.     ip = '192.168.0.10'
  221.     var XML = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>";
  222.     XML += "<Service>";
  223.     for (var j = 0; j < comandi.length; j++) {
  224.         XML += "<cmd>" + comandi[j] + "</cmd>";
  225.     }
  226.     XML += "</Service>";
  227.  
  228.  
  229.     return new Promise((resolve, reject) => {
  230.         axios.post('http://' + ip + '/service.cgi', XML,
  231.             {
  232.                 headers: { 'content-type': 'application/xml' }
  233.             }
  234.         )
  235.             .then(function (response) {
  236.                 log.info('risposta','http',response.data);
  237.                 resolve(response)
  238.             })
  239.             .catch(function (error) {
  240.                 reject(error)
  241.             });
  242.  
  243.     });
  244.  
  245. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement