/
main.go
267 lines (197 loc) · 5.93 KB
/
main.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
import "regexp"
import "HuliTest/helper"
import "HuliTest/models"
import "HuliTest/webservice"
func main() {
//Init Router
r := mux.NewRouter()
// invoice routes
r.HandleFunc("/api/invoices", getInvoices).Methods("GET")
r.HandleFunc("/api/invoices", createInvoice).Methods("POST")
r.HandleFunc("/api/invoices/{id}", getInvoice).Methods("GET")
r.HandleFunc("/api/invoices/{id}", updateInvoice).Methods("PUT")
r.HandleFunc("/api/invoices/{id}", deleteInvoice).Methods("DELETE")
// Pay invoice
r.HandleFunc("/api/invoices/pay", createInvoicePayment).Methods("POST")
// set port address
log.Fatal(http.ListenAndServe(":7000", r))
}
func getInvoices(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var invoices []models.Invoice
//Connection mongoDB with helper class
collection := helper.ConnectDB().Collection("invoices")
cur, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
helper.GetError(err, w)
return
}
// Close the cursor once finished
defer cur.Close(context.TODO())
for cur.Next(context.TODO()) {
// create a value into which the single document can be decoded
var invoice models.Invoice
err := cur.Decode(&invoice) // decode
if err != nil {
log.Fatal(err)
}
// add item to array
invoices = append(invoices, invoice)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
json.NewEncoder(w).Encode(invoices) // encode
}
func createInvoice(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var invoice models.Invoice
var re = regexp.MustCompile(`(?m)^[0-9]+(-[0-9]+)+(-[0-9]+)+$`)
fmt.Println(json.NewDecoder(r.Body).Decode(&invoice))
_ = json.NewDecoder(r.Body).Decode(&invoice)
if len(re.FindAllString(invoice.Client.Id, -1)) < 1 {
w.WriteHeader(http.StatusUnprocessableEntity)
json.NewEncoder(w).Encode("client id must have atleast 3 group of integers")
} else {
rate := webservice.ConvertDollarsColones()
lnArr := []models.Line{}
var taxTotal = 0.0
var discountTotal = 0.0
var subTotal = 0.0
var balance = 0.0
if s, err := strconv.ParseFloat(rate, 64); err == nil {
fmt.Println(s) // 3.14159265
for i := 0; i < len(invoice.Line); i++ {
line := invoice.Line[i]
taxTotal = taxTotal + line.TaxRate
discountTotal = discountTotal + line.DiscountRate
if line.Currency != "CRC" {
line.PriceSrc = s * line.Price
line.Currency = "CRC"
} else {
line.PriceSrc = line.Price
}
subTotal = subTotal + line.PriceSrc
lnArr = append(lnArr, line)
}
}
invoice.TaxTotal = taxTotal
invoice.DiscountTotal = discountTotal
invoice.Subtotal = subTotal
invoice.Total = taxTotal + subTotal - discountTotal
invoice.Balance = balance
invoice.Line = lnArr
// connect db
collection := helper.ConnectDB().Collection("invoices")
// insert model.
result, err := collection.InsertOne(context.TODO(), invoice)
fmt.Println(invoice.Line)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
}
}
func getInvoice(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
var invoice models.Invoice
var params = mux.Vars(r)
// string to primitive.ObjectID
id, _ := primitive.ObjectIDFromHex(params["id"])
collection := helper.ConnectDB().Collection("invoices")
filter := bson.M{"_id": id}
err := collection.FindOne(context.TODO(), filter).Decode(&invoice)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(invoice)
}
func updateInvoice(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
//Get id from parameters
id, _ := primitive.ObjectIDFromHex(params["id"])
var invoice models.Invoice
collection := helper.ConnectDB().Collection("invoices")
// Create filter
filter := bson.M{"_id": id}
// Read update model from body request
_ = json.NewDecoder(r.Body).Decode(&invoice)
// prepare update model.
update := bson.D{
{"$set", bson.D{
{"line", invoice.Line},
{"client", bson.D{
{"id", invoice.Client.Id},
{"name", invoice.Client.Name},
}},
}},
}
err := collection.FindOneAndUpdate(context.TODO(), filter, update).Decode(&invoice)
if err != nil {
helper.GetError(err, w)
return
}
invoice.Id = id
json.NewEncoder(w).Encode(invoice)
}
func deleteInvoice(w http.ResponseWriter, r *http.Request) {
// Set header
w.Header().Set("Content-Type", "application/json")
// get params
var params = mux.Vars(r)
id, err := primitive.ObjectIDFromHex(params["id"])
collection := helper.ConnectDB().Collection("invoices")
filter := bson.M{"_id": id}
deleteResult, err := collection.DeleteOne(context.TODO(), filter)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(deleteResult)
}
// Invoice Payment
func createInvoicePayment(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var pay models.PayInvoice
var pay2 models.PayInvoice
fmt.Println(json.NewDecoder(r.Body).Decode(&pay))
_ = json.NewDecoder(r.Body).Decode(&pay)
// Find if already a payment
var id = pay.InvoiceId
// connect db
collection := helper.ConnectDB().Collection("payment")
// prepare filter.
filter := bson.M{"invoice_id": id}
err1 := collection.FindOne(context.TODO(), filter).Decode(&pay2)
if err1 != nil{
fmt.Println(err1)
// we decode our body request params
_ = json.NewDecoder(r.Body).Decode(&pay)
// insert our book model.
result, err := collection.InsertOne(context.TODO(), pay)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
} else {
json.NewEncoder(w).Encode("Invoice can not be over paid")
}
fmt.Println(pay2.InvoiceId)
}