forked from wisepythagoras/pos-system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceipt.go
199 lines (158 loc) · 4.76 KB
/
receipt.go
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
package main
import (
"bytes"
"encoding/base64"
"encoding/hex"
"errors"
"io/ioutil"
"os"
"os/exec"
"strconv"
"text/template"
"time"
"github.com/phin1x/go-ipp"
"github.com/skip2/go-qrcode"
"github.com/wisepythagoras/pos-system/crypto"
)
// ReceiptTmplData describes the template data for the receipt.
type ReceiptTmplData struct {
Total float64
Order *OrderJSON
Products *[]AggregateProduct
Qrcode string
Name string
Address1 string
Address2 string
DateString string
}
// Receipt describes the receipt object. It should contain an order and the config.
type Receipt struct {
Order *OrderJSON
Total float64
Config *Config
Client *ipp.IPPClient
printerId int
}
// GetPrinter returns the index of the selected printer in the configuration array.
func (r *Receipt) GetPrinter() int {
printerId := r.printerId
if printerId <= 0 {
printerId = 1
}
printerIdx := 0
for i, p := range r.Config.Printers {
if p.ID == printerId {
printerIdx = i
break
}
}
return printerIdx
}
// ConnectToPrinter connects to the printer server.
func (r *Receipt) ConnectToPrinter() error {
if len(r.Config.Printers) == 0 {
return errors.New("no printers were specified in the config")
}
printerIdx := r.GetPrinter()
// TODO: In order to support multiple printers, this should take a specific index.
server := r.Config.Printers[printerIdx].Server
port := r.Config.Printers[printerIdx].Port
username := r.Config.Printers[printerIdx].Username
password := r.Config.Printers[printerIdx].Password
// Connect to the printer server.
r.Client = ipp.NewIPPClient(server, port, username, password, true)
return nil
}
// Print prints the receipt.
func (r *Receipt) Print() (int, error) {
// Connect to the printer if the connection died.
if r.Client.TestConnection() != nil {
r.ConnectToPrinter()
}
// Create the file.
data, err := ioutil.ReadFile("templates/receipt.html")
if err != nil {
return 99, err
}
t, err := template.New("receipt").Parse(string(data))
if err != nil {
return 99, err
}
fileName := "receipt-" + strconv.Itoa(int(r.Order.ID))
// Create a file for the rendered receipt.
receiptFile, err := os.OpenFile("receipts/"+fileName+".html", os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return 99, err
}
defer receiptFile.Close()
encryptJSON := `{"i": ` + strconv.Itoa(int(r.Order.ID)) + `}`
encryptedId, _ := crypto.EncryptGCM([]byte(encryptJSON), []byte(r.Config.Key))
hexEncryptedId := hex.EncodeToString(encryptedId)
png, _ := qrcode.Encode(hexEncryptedId, qrcode.Medium, 160)
// This is the new buffer that will contain the executedtemplate.
buff := new(bytes.Buffer)
var aggregateProducts []AggregateProduct
var aggregateMap map[uint64]uint = make(map[uint64]uint)
var products map[uint64]ProductJSON = make(map[uint64]ProductJSON)
// Find how many of each products we have.
for _, product := range r.Order.Products {
if val, ok := aggregateMap[product.ID]; ok {
aggregateMap[product.ID] = val + 1
} else {
aggregateMap[product.ID] = 1
products[product.ID] = ProductJSON{
ID: product.ID,
Name: product.Name,
Price: product.Price,
Type: product.ProductType.Name,
Discontinued: product.Discontinued,
SoldOut: product.SoldOut,
}
}
}
// Now compose the aggregate product array.
for productId, quantity := range aggregateMap {
product := products[productId]
aggregateProduct := AggregateProduct{
Quantity: quantity,
ID: product.ID,
Name: product.Name,
Price: float64(quantity) * product.Price,
Type: product.ProductType.Name,
}
aggregateProducts = append(aggregateProducts, aggregateProduct)
}
tmplData := ReceiptTmplData{
Total: r.Total,
Order: r.Order,
Qrcode: base64.StdEncoding.EncodeToString(png),
Products: &aggregateProducts,
Name: r.Config.Name,
Address1: r.Config.Address1,
Address2: r.Config.Address2,
DateString: r.Order.CreatedAt.Format(time.RFC1123),
}
// Execute the receipt.
err = t.Execute(buff, tmplData)
receiptFile.WriteString(buff.String())
cwd, _ := os.Getwd()
input := cwd + "/receipts/" + fileName + ".html"
output := cwd + "/receipts/" + fileName + ".pdf"
// Now we want to convert the receipt to a PDF so that the printer can render it.
cmd := exec.Command("wkhtmltopdf", "--page-width", "80", "--page-height", "200", input, output)
err = cmd.Start()
if err != nil {
return 99, err
}
err = cmd.Wait()
if err != nil {
return 99, err
}
if len(r.Config.Printers) == 0 {
return -1, errors.New("No printers are set up")
}
printerIdx := r.GetPrinter()
printer := r.Config.Printers[printerIdx].Name
// Finally, call the printer to print the receipt.
return r.Client.PrintFile(output, printer, map[string]interface{}{})
}