A few days ago I was struggling to get to print receipts using ESCPOS Java API but failed since I couldn't find a simple enough USB API to allow the program to print to my thermal printer using a USB interface. I later decided to implement this in Node and ESCPOS module.
I am connecting this application to MySQL database to be able to print receipts from recorded transactions. I am using tables to create a list of products and their respective prices but only by hard coding. My problem now is how to create these tables dynamically. Depending on which products were involved in the transaction, I want the script to query and print only those.
Here is receipt code!
const db = require('./database.js');
const escpos = require('escpos');
const uniqueRandom = require('unique-random');
const random = uniqueRandom(1000, 9999);
const device = new escpos.USB();
const options = { encoding: "GB18030" }
exports.printGeneralReceipt = function(status){
db.getTransactionDetails(function(res){
data = res;
});
const printer = new escpos.Printer(device, options);
console.log("Printer found!");
device.open(function(){
console.log("Receipt generating...");
printer
.font('b')
.align('ct')
.style('bu')
.size(1, 1)
.encode('utf8')
.text('\n*****START OF LEGAL RECEIPT*****'+
'\n\nCOMPUTICKET MALAWI\n'+
'SHOP 31A, GAME COMPLEX\n'+
'LILONGWE MALL\n\nwww.computicket.mw\n+265 (0) 99 974 7576\n')
.table(["BUYER NAME :", "CLIFFORD MWALE", ""])
.table(["RECEIPT # :", random(), ""])
.table(["DATE: ", "12/AUG/2019", ""])
.text("----------ITEM LIST----------\n")
// ITEM LIST STARTS HERE
.table(["MILK","$2"])
.table(["PEANUT BUTTER", "$6"])
// ITEM LIST ENDS HERE
.text("--------------------------------")
.table(["TOTAL PRICE", "$8.00", ""])
.text("Operator: Jon Doe\n-------------------------------\n")
.barcode('123456789012')
.text("\n\nTHANK YOU\n\n*****END OF LEGAL RECEIPT*****")
.beep(1,100)
.cut().close();
console.log("Receipt printed!");
});
}
And here is the function pulling the transaction details from the Database. I'll spare you the overhead of creating a connection.
exports.getTransactionDetails = function(trans_id){
var res = "";
conn.query("SELECT * FROM transactions JOIN products_in_transaction WHERE transactions.trans_id = products_in_transaction.trans_id "+
" transactions.trans_id = '"+trans_id+"'",
function (error, results, fields) {
for(var i = 0; i < results.length; i++){
// SOME OPERATION HERE
}
});
}