-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapi.js
425 lines (366 loc) · 15.6 KB
/
api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
'use strict';
const Promise = require("bluebird");
const fs = require('fs');
var self;
class API {
constructor(serialWrapper, lock) {
this.serialWrapper = serialWrapper;
this.lock = lock;
self = this;
}
getNoteFrequency(note) {
let notesFreq = {
'c': 261,
'd': 294,
'e': 329,
'f': 349,
'g': 391,
'gS': 415,
'a': 440,
'aS': 455,
'b': 466,
'cH': 523,
'cSH': 554,
'dH': 587,
'dSH': 622,
'eH': 659,
'fH': 698,
'fSH': 740,
'gH': 784,
'gSH': 830,
'aH': 880,
};
return notesFreq[note];
}
cancelFiscalOperation() {
return self.serialWrapper.runCommand(60);
}
async playMusicSteps(musicSteps) {
await self.lock.acquire();
await Promise.each(musicSteps, function(musicData) {
if (musicData[0] == 0 && musicData[1] == 0) {
return Promise.delay(musicData[2]);
} else {
var data = musicData[0] + ',' + musicData[1];
var delay = parseInt(musicData[1]) + parseInt(musicData[2]);
return self.serialWrapper.runCommand(80, data).delay(delay);
}
}).finally(() => {
self.lock.release();
});
}
async playErrorBeep() {
var musicSteps = [
[self.getNoteFrequency('a'), '1500', '50'],
];
return self.playMusicSteps(musicSteps);
}
async playMusic() {
var musicSteps = [
[self.getNoteFrequency('a'), '500', '30'],
[self.getNoteFrequency('a'), '500', '30'],
[self.getNoteFrequency('a'), '500', '30'],
[self.getNoteFrequency('f'), '350', '30'],
[self.getNoteFrequency('cH'), '150', '30'],
[self.getNoteFrequency('a'), '500', '30'],
[self.getNoteFrequency('f'), '350', '30'],
[self.getNoteFrequency('cH'), '150', '30'],
[self.getNoteFrequency('a'), '150', '30'],
[0, 0, '150'], //end part one
[self.getNoteFrequency('eH'), '500', '30'],
[self.getNoteFrequency('eH'), '500', '30'],
[self.getNoteFrequency('eH'), '500', '30'],
[self.getNoteFrequency('fH'), '350', '30'],
[self.getNoteFrequency('cH'), '150', '30'],
[self.getNoteFrequency('gS'), '500', '30'],
[self.getNoteFrequency('f'), '350', '30'],
[self.getNoteFrequency('cH'), '150', '30'],
[self.getNoteFrequency('a'), '650', '30'],
[0, 0, '150'], //end part two
[self.getNoteFrequency('aH'), '500', '30'],
[self.getNoteFrequency('a'), '300', '30'],
[self.getNoteFrequency('a'), '150', '30'],
[self.getNoteFrequency('aH'), '400', '30'],
[self.getNoteFrequency('gSH'), '200', '30'],
[self.getNoteFrequency('gH'), '200', '30'],
[self.getNoteFrequency('fSH'), '125', '30'],
[self.getNoteFrequency('fH'), '125', '30'],
[self.getNoteFrequency('fSH'), '250', '30'],
[0, 0, '250'], //end part three
[self.getNoteFrequency('aS'), '250', '30'],
[self.getNoteFrequency('dSH'), '400', '30'],
[self.getNoteFrequency('dH'), '200', '30'],
[self.getNoteFrequency('cSH'), '200', '30'],
[self.getNoteFrequency('cH'), '125', '30'],
[self.getNoteFrequency('b'), '125', '30'],
[self.getNoteFrequency('cH'), '250', '30'],
[0, 0, '250'], //end part four
];
return self.playMusicSteps(musicSteps);
}
setHeaders() {
var commands = [
[43, "L,1,96"], //turn on logo and set 96 height
];
return Promise.each(commands, function(line) {
return self.serialWrapper.runCommand(line[0], line[1]).then(function(res) {
console.log(res);
});
});
}
getLastFiscalRecord() {
return self.serialWrapper.runCommand(64, '0').then(function(res) {
console.log(res);
});
}
clearDisplay() {
return self.serialWrapper.runCommand(100, 'asd').then(function(res) {
console.log(res);
});
}
async getDiagnosticInfo() {
await self.lock.acquire();
return self.serialWrapper.runCommand(90, '1').then(function(res) {
return res.data;
}).finally(() => {
self.lock.release();
});
}
filterUndefinedValues(obj) {
const ret = {};
Object.keys(obj)
.filter((key) => obj[key] !== undefined)
.forEach((key) => ret[key] = obj[key]);
return ret;
}
async getStatus() {
await self.lock.acquire();
//74 - command get status
//W - means to wait for fiscal device to print all buffers
return self.serialWrapper.runCommand(74, 'W').then(function(res) {
console.log(res);
}).finally(() => {
self.lock.release();
});
//return Promise.each(fiskalenBonCommands, function(data) {
// return self.serialWrapper.runCommand(data[0], data[1]).then(function(res) {
// //console.log('messages');
// //console.log(res.messages);
// //console.log('status codes');
// //console.log(res.responseStatusCodes);
// //console.log('data');
// //console.log(res.data);
// if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('GENERAL_ERROR')) !== -1) {
// return Promise.reject('General error');
// } else if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('SYNTACS_ERROR')) !== -1) {
// return Promise.reject('Syntax error');
// } else if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('COMMAND_CANNOT_BE_EXECUTED_IN_CURRENT_STATE')) !== -1) {
// return Promise.reject('Cannot be executed');
// }
// });
//}).then(function() {
// return self.getSaleFiscalNumber();
//}).then(function(data) {
// fiscalSaleData.memory = data;
// fiscalSaleData.status = 'ok';
// return fiscalSaleData;
//}).catch(function(error) {
// return self.playErrorBeep().then(function() {
// return self.cancelFiscalOperation().then(function() {
// throw error;
// });
// });
//}).finally(() => {
// self.lock.release();
//});
}
async checkIfHasUnfinishedFiscalOperationAndAbortIt() {
return self.serialWrapper.runCommand(76).then(function(res) {
var splitted = res.data.split(',');
if (splitted[0] == '1') {
return self.serialWrapper.runCommand(60); // cancel fiscal operation
}
});
}
async createSale(options={}) {
var defaultOptions = {
'saleItemText': 'Стоки',
'NSale': null,
'OpCode': "1",
'OpPwd': "1",
'TillNmb': "1",
'Amount': "0.01",
'PaidMode': "P",
'storno': false,
'stornoData': {
'docType': '0', //0 operator error, 1 return/replace, 2 lower amount
'docNumber': '0',
'docDateTime': '0',
'fmNumber': '0',
},
'lines': [],
};
defaultOptions = Object.assign(defaultOptions, this.filterUndefinedValues(options));
//console.log(defaultOptions);
//return;
//NSale Уникален номер на продажба УНП (21 символа CCCCCCCC-CCCC-DDDDDDD
//формат [0-9A-Zaz]{8}-[0-9A-Za-z]{4}-[0-9]{7} ).
//Параметърът е задължителен в първия синтаксис на командата.
//PaidMode Незадължителен код, указващ начина на плащане. Може да има следните стойности:
//‘P’ - Плащане в брой (по подразбиране);
//‘N’ - Плащане с кредит;
//‘C’ - Плащане с дебитна карта;
//‘D’ - Плащане с НЗОК;
//‘I’ - Плащане с ваучер;
//‘J’ - Плащане с купон;
//Б) ФИСКАЛНИ БОНОВЕ.
//Първо се отваря фискален бон, регистрират се продажбите, извършва се плащането и накрая бона се затваря.
//Използват се командите 48 (30H), 49 (31H), 51 (33H), 52 (34H), 53 (35H), 54 (36H), 58 (3AH) и 56 (38H).
//Накрая на деня се извършва дневен финансов отчет с нулиране (Z-отчет), за да се запише информацията във ФП. Това става с
//командата 69 (45H).
var openCommand = [48, "1,1,1"]; //open command without NSale
if (defaultOptions['NSale']) {
openCommand = [48, "1,1,"+defaultOptions['NSale']+",1"]; //open command with NSale
}
//console.log(openCommand);
var fiskalenBonCommands = [
[52, defaultOptions['saleItemText'] + "\t1\t" + defaultOptions['Amount']], //РЕГИСТРИРАНЕ НА ПРОДАЖБА И ПОКАЗВАНЕ НА ДИСПЛЕЯ
//[92, "3"], //LINES=====
//[51, "11"], //МЕЖДИННА СУМА
[53, "\t" + defaultOptions['PaidMode']], //ИЗЧИСЛЯВАНЕ НА СБОР (ТОТАЛ)
[56, null], //close
//[49, "\t1\t-100"], //registrirane na prodajba
//[54, "hello"], //ПЕЧАТАНЕ НА ФИСКАЛЕН СВОБОДЕН ТЕКСТ
//[58, "-1"], //РЕГИСТРИРАНЕ (ПРОДАЖБА) НА АРТИКУЛ
];
defaultOptions.lines.forEach(function(d) {
fiskalenBonCommands.unshift([54, d]);
});
//create open command
if (options.storno) {
//[46, "1,1,DT743818-0008-0000005,1,0,123,2602191309,00000157"],
var commandData = [];
//commandData.push(46); //storno command
commandData.push(1); //operator code
commandData.push(1); //operator password
commandData.push(defaultOptions['NSale']);
commandData.push(defaultOptions['TillNmb']);
commandData.push(defaultOptions['stornoData']['docType']);
commandData.push(defaultOptions['stornoData']['docNumber']);
commandData.push(defaultOptions['stornoData']['docDateTime']);
commandData.push(defaultOptions['stornoData']['fmNumber']);
openCommand = [46, commandData.join(',')];
fiskalenBonCommands.unshift(openCommand);
} else {
fiskalenBonCommands.unshift(openCommand);
}
var fiscalSaleData = {
'status': null,
'memory': null,
};
//console.log(fiskalenBonCommands);
await self.lock.acquire();
await self.checkIfHasUnfinishedFiscalOperationAndAbortIt();
return Promise.each(fiskalenBonCommands, function(data) {
return self.serialWrapper.runCommand(data[0], data[1]).then(function(res) {
console.log('messages');
console.log(res.messages);
console.log('status codes');
console.log(res.responseStatusCodes);
console.log('data');
console.log(res.data);
if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('GENERAL_ERROR')) !== -1) {
return Promise.reject('General error');
} else if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('SYNTACS_ERROR')) !== -1) {
return Promise.reject('Syntax error');
} else if (res.responseStatusCodes.indexOf(self.serialWrapper.getStatusCodes().get('COMMAND_CANNOT_BE_EXECUTED_IN_CURRENT_STATE')) !== -1) {
return Promise.reject('Cannot be executed');
}
});
}).then(function() {
return self.getSaleFiscalNumber();
}).then(function(data) {
fiscalSaleData.memory = data;
fiscalSaleData.status = 'ok';
return fiscalSaleData;
}).catch(function(error) {
return self.playErrorBeep().then(function() {
return self.cancelFiscalOperation().then(function() {
throw error;
});
});
}).finally(() => {
self.lock.release();
});
}
getSaleFiscalNumber() {
return self.serialWrapper.runCommand(48, '*').then(function(res) {
return res.data;
});
}
async runDailyFinancialReport(withNulling=true) {
//Option Незадължителен параметър, управляващ вида на генерирания отчет:
//‘0’ Отпечатва се Z-отчет. Разпечатката завършва с надпис “ФИСКАЛЕН БОН”.
//‘2’ Прави се дневен финансов отчет без нулиране (т. е. не се извършва запис във ФП и нулиране на
//регистрите). Разпечатката завършва с текст “СЛУЖЕБЕН БОН”.
var data = '2';
if (withNulling) {
data = '0';
}
return self.serialWrapper.runCommand(69, data).then(function(res) {
});
}
async runFinancialReportByDate(start, end) {
if (start && !end) {
var data = start;
} else if (start && end) {
var data = start + ',' + end;
}
return self.serialWrapper.runCommand(94, data).then(function(res) {
//console.log(res);
});
}
loadPBMLogo(fileLocation, width=384, height=96) {
//use jpg convertion tool like
//https://convertio.co/jpg-pbm/
//to convert from jpg to pbm p4
var data = fs.readFileSync(fileLocation);
if (data[0] !== 80 && data[1] !== 52) {
console.log('Error: failed to load file, must be PBM P4 format!');
return;
}
var lineData = '';
var lines = [];
var i = 0;
var l = 0;
var r = 0;
data.forEach(function(bt, k) {
if (k > 9) {
var hex = parseInt(bt, 10).toString(16).padStart(2, "0");
lineData += hex;
i++;
r++;
if (r % (height/2) == 0) {
lines.push(l + ',' + lineData);
lineData = '';
l++;
r = 0;
}
}
});
Promise.each(lines, function(line) {
return self.serialWrapper.runCommand(115, line).then(function(res) {
//console.log(res);
});
});
//console.log(lines);
//console.log(lines);
//console.log(data);
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
module.exports = API;