diff --git a/routes.go b/routes.go index ba5e6d1..d6177b0 100644 --- a/routes.go +++ b/routes.go @@ -24,7 +24,9 @@ func addRoutes(sm *http.ServeMux, server *Server, staticFiles string) { "health": "/healthz", "list": "/api/v0/list/", "tranx": "/api/v0/tranx/", - "fake": "/fake/", + "cost": "/api/v0/costpermonth/", + + "fake": "/fake/", } if staticFiles == "" { @@ -76,5 +78,6 @@ func addRoutes(sm *http.ServeMux, server *Server, staticFiles string) { sm.HandleFunc(prefix["health"], server.health) sm.HandleFunc(prefix["list"], server.listUsers) sm.HandleFunc(prefix["tranx"], server.tranx) + sm.HandleFunc(prefix["cost"], server.costPerMonth) sm.HandleFunc(prefix["fake"], server.fakeSetup) } diff --git a/server.go b/server.go index e5c5a7d..97f21ed 100644 --- a/server.go +++ b/server.go @@ -117,7 +117,7 @@ func (s *Server) tranx(w http.ResponseWriter, r *http.Request) { } defer r.Body.Close() - users[u].addTranx( + users[u].txs = append(users[u].txs, tranx{ Cost: t.Cost, Store: t.Store, @@ -128,6 +128,47 @@ func (s *Server) tranx(w http.ResponseWriter, r *http.Request) { } } +func (s *Server) costPerMonth(w http.ResponseWriter, r *http.Request) { + //TODO add back in oauth + //w.Header().Set("Content-Type", "application/json") + //session, _ := store.Get(r, "creds") + //if err != nil { + // http.Error(w, err.Error(), http.StatusInternalServerError) + // return + //} + //if loggedIn := session.Values["authenticated"]; loggedIn != true { + // http.Redirect(w, r, "/", http.StatusTemporaryRedirect) + // return + //} + switch r.Method { + default: + b, _ := json.Marshal(NewFailure("Allowed method: GET")) + http.Error(w, string(b), http.StatusBadRequest) + return + case "GET": + u, err := getUser("derekmcquay@gmail.com") //TODO will grab this from session + if err != nil { + b, _ := json.Marshal(NewFailure(err.Error())) + http.Error(w, string(b), http.StatusInternalServerError) + return + } + monthCost := make(map[time.Month]float32) + for _, t := range users[u].txs { + c, ok := monthCost[t.Month] + if !ok { + monthCost[t.Month] = t.Cost + continue + } + monthCost[t.Month] = t.Cost + c + } + err = json.NewEncoder(w).Encode(monthCost) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + } +} + func (s *Server) listUsers(w http.ResponseWriter, r *http.Request) { //TODO add back in oauth //w.Header().Set("Content-Type", "application/json")