-
Notifications
You must be signed in to change notification settings - Fork 0
/
bill.go
64 lines (51 loc) · 1.61 KB
/
bill.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/mspiewak/renter/model"
)
func (a *App) postBill(w http.ResponseWriter, r *http.Request) (interface{}, error) {
var bill model.Bill
if err := json.NewDecoder(r.Body).Decode(&bill); err != nil {
return nil, fmt.Errorf("cannot decode json: %v", err)
}
noOfDaysRenting, err := a.tenantRepository.GetNumberOfRentingDays(bill.PeriodStart, bill.PeriodEnd)
if err != nil {
return nil, fmt.Errorf("cannot get number of renting days: %v", err)
}
if err := a.billRepository.CreateBill(&bill); err != nil {
return nil, err
}
sum := 0
for _, noOfDays := range noOfDaysRenting {
sum += noOfDays
}
for tenantID, noOfDays := range noOfDaysRenting {
tb := model.TenantBill{
TenantID: tenantID,
Price: float64(noOfDays) * bill.Price / float64(sum),
Bill: model.Bill{
ID: bill.ID,
},
}
if err := a.billRepository.CreateTenantBill(&tb); err != nil {
return nil, fmt.Errorf("cannot create bill for tenant: %v", err)
}
}
return bill, nil
}
func (a *App) getBills(w http.ResponseWriter, r *http.Request) (interface{}, error) {
return a.billRepository.GetAll()
}
func (a *App) getTenantBills(w http.ResponseWriter, r *http.Request) (interface{}, error) {
vars := mux.Vars(r)
tenantID := getRealTenantID(vars["id"])
return a.billRepository.GetByTenantId(tenantID)
}
func (a *App) optionsBills(w http.ResponseWriter, r *http.Request) (interface{}, error) {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "*")
return []interface{}{}, nil
}