Add dispositifs

This commit is contained in:
2022-09-05 07:25:05 +02:00
parent 0bb915059d
commit 8aa8fc927b
29 changed files with 1425 additions and 329 deletions

View File

@@ -0,0 +1,304 @@
package application
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"time"
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/utils/form-validators"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
agendastorage "git.coopgo.io/coopgo-platform/agenda/storage"
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
"git.coopgo.io/coopgo-platform/groups-management/storage"
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
"github.com/gorilla/mux"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
type EventsByStartdate []agendastorage.Event
func (e EventsByStartdate) Len() int { return len(e) }
func (e EventsByStartdate) Less(i, j int) bool { return e[i].Startdate.Before(e[j].Startdate) }
func (e EventsByStartdate) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
type EventsForm struct {
Name string `json:"name" validate:"required"`
Type string `json:"type" validate:"required"`
Description string `json:"description"`
Address any `json:"address,omitempty"`
Allday bool `json:"allday"`
Startdate *time.Time `json:"startdate"`
Enddate *time.Time `json:"enddate"`
Starttime string `json:"starttime"`
Endtime string `json:"endtime"`
MaxSubscribers int `json:"max_subscribers" validate:"required"`
}
func (h *ApplicationHandler) AgendaHome(w http.ResponseWriter, r *http.Request) {
resp, err := h.services.GRPC.Agenda.GetEvents(context.TODO(), &agenda.GetEventsRequest{
Namespaces: []string{"parcoursmob_dispositifs"},
Mindate: timestamppb.New(time.Now().Add(-24 * time.Hour)),
})
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
responses := []agendastorage.Event{}
groupids := []string{}
for _, e := range resp.Events {
groupids = append(groupids, e.Owners...)
responses = append(responses, e.ToStorageType())
// fmt.Println(e)
// fmt.Println(e.ToStorageType())
}
sort.Sort(EventsByStartdate(responses))
groupsresp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), &groupsmanagement.GetGroupsBatchRequest{
Groupids: groupids,
})
groups := map[string]any{}
if err == nil {
for _, g := range groupsresp.Groups {
groups[g.Id] = g.ToStorageType()
}
}
h.Renderer.AgendaHome(w, r, responses, groups)
}
func (h *ApplicationHandler) AgendaCreateEvent(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Get current group
g := r.Context().Value(identification.GroupKey)
if g == nil {
w.WriteHeader(http.StatusBadRequest)
return
}
group := g.(storage.Group)
eventForm, err := parseEventsForm(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
fmt.Println(eventForm)
data, _ := structpb.NewStruct(map[string]any{
"address": eventForm.Address,
})
request := &agenda.CreateEventRequest{
Event: &agenda.Event{
Namespace: "parcoursmob_dispositifs",
Owners: []string{group.ID},
Type: eventForm.Type,
Name: eventForm.Name,
Description: eventForm.Description,
Startdate: timestamppb.New(*eventForm.Startdate),
Enddate: timestamppb.New(*eventForm.Enddate),
Starttime: eventForm.Starttime,
Endtime: eventForm.Endtime,
Allday: eventForm.Allday,
MaxSubscribers: int64(eventForm.MaxSubscribers),
Data: data,
},
}
resp, err := h.services.GRPC.Agenda.CreateEvent(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", resp.Event.Id), http.StatusFound)
}
h.Renderer.AgendaCreateEvent(w, r)
}
func (h *ApplicationHandler) AgendaDisplayEvent(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
eventid := vars["eventid"]
request := &agenda.GetEventRequest{
Id: eventid,
}
resp, err := h.services.GRPC.Agenda.GetEvent(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
grouprequest := &groupsmanagement.GetGroupRequest{
Id: resp.Event.Owners[0],
}
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
subscribers := map[string]any{}
subscriberresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
context.TODO(),
&mobilityaccounts.GetAccountsBatchRequest{
Accountids: resp.Event.Subscribers,
},
)
if err == nil {
for _, sub := range subscriberresp.Accounts {
subscribers[sub.Id] = sub.ToStorageType()
}
}
g := r.Context().Value(identification.GroupKey)
if g == nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
group := g.(storage.Group)
accountids := []string{}
for _, m := range group.Members {
if !contains(resp.Event.Subscribers, m) {
accountids = append(accountids, m)
}
}
accountresp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(
context.TODO(),
&mobilityaccounts.GetAccountsBatchRequest{
Accountids: accountids,
},
)
accounts := []any{}
if err == nil {
for _, acc := range accountresp.Accounts {
accounts = append(accounts, acc)
}
}
h.Renderer.AgendaDisplayEvent(w, r, resp.Event.ToStorageType(), groupresp.Group.ToStorageType(), subscribers, accounts)
}
func (h *ApplicationHandler) AgendaSubscribeEvent(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
eventid := vars["eventid"]
if err := r.ParseForm(); err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
subscriber := r.FormValue("subscriber")
request := &agenda.SubscribeEventRequest{
Eventid: eventid,
Subscriber: subscriber,
}
_, err := h.services.GRPC.Agenda.SubscribeEvent(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
http.Redirect(w, r, fmt.Sprintf("/app/agenda/%s", eventid), http.StatusFound)
}
func parseEventsForm(r *http.Request) (*EventsForm, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
var startdate *time.Time
var enddate *time.Time
if r.PostFormValue("startdate") != "" {
d, err := time.Parse("2006-01-02", r.PostFormValue("startdate"))
if err != nil {
return nil, err
}
startdate = &d
}
if r.PostFormValue("enddate") != "" {
d, err := time.Parse("2006-01-02", r.PostFormValue("enddate"))
if err != nil {
return nil, err
}
enddate = &d
}
max_subscribers, err := strconv.Atoi(r.PostFormValue("max_subscribers"))
if err != nil {
return nil, err
}
formData := &EventsForm{
Name: r.PostFormValue("name"),
Type: r.PostFormValue("type"),
Description: r.PostFormValue("description"),
Startdate: startdate,
Enddate: enddate,
Starttime: r.PostFormValue("starttime"),
Endtime: r.PostFormValue("endtime"),
MaxSubscribers: max_subscribers,
}
if r.PostFormValue("allday") == "true" {
formData.Allday = true
}
if r.PostFormValue("address") != "" {
var a any
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
formData.Address = a
}
validate := formvalidators.New()
if err := validate.Struct(formData); err != nil {
return nil, err
}
return formData, nil
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}

View File

@@ -16,6 +16,7 @@ import (
formvalidators "git.coopgo.io/coopgo-apps/parcoursmob/utils/form-validators"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
profilepictures "git.coopgo.io/coopgo-apps/parcoursmob/utils/profile-pictures"
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
"git.coopgo.io/coopgo-platform/groups-management/storage"
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
@@ -61,7 +62,7 @@ func (h *ApplicationHandler) BeneficiaryCreate(w http.ResponseWriter, r *http.Re
if r.Method == "POST" {
dataMap, err := parseForm(r)
dataMap, err := parseBeneficiariesForm(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
@@ -128,7 +129,23 @@ func (h *ApplicationHandler) BeneficiaryDisplay(w http.ResponseWriter, r *http.R
//TODO filter namespaces
//TODO filter groups
h.Renderer.BeneficiaryDisplay(w, r, resp.Account.ToStorageType())
bookingsrequest := &fleets.GetDriverBookingsRequest{
Driver: beneficiaryID,
}
bookingsresp, err := h.services.GRPC.Fleets.GetDriverBookings(context.TODO(), bookingsrequest)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
bookings := []any{}
for _, b := range bookingsresp.Bookings {
bookings = append(bookings, b.ToStorageType())
}
h.Renderer.BeneficiaryDisplay(w, r, resp.Account.ToStorageType(), bookings)
}
func (h *ApplicationHandler) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request) {
@@ -137,7 +154,7 @@ func (h *ApplicationHandler) BeneficiaryUpdate(w http.ResponseWriter, r *http.Re
if r.Method == "POST" {
dataMap, err := parseForm(r)
dataMap, err := parseBeneficiariesForm(r)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
@@ -189,56 +206,6 @@ func (h *ApplicationHandler) BeneficiaryUpdate(w http.ResponseWriter, r *http.Re
h.Renderer.BeneficiaryUpdate(w, r, resp.Account.ToStorageType())
}
func parseForm(r *http.Request) (map[string]any, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
var date *time.Time
if r.PostFormValue("birthdate") != "" {
d, err := time.Parse("2006-01-02", r.PostFormValue("birthdate"))
if err != nil {
return nil, err
}
date = &d
}
formData := BeneficiariesForm{
FirstName: r.PostFormValue("first_name"),
LastName: r.PostFormValue("last_name"),
Email: r.PostFormValue("email"),
Birthdate: date,
PhoneNumber: r.PostFormValue("phone_number"),
Gender: r.PostFormValue("gender"),
}
if r.PostFormValue("address") != "" {
var a any
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
formData.Address = a
}
validate := formvalidators.New()
if err := validate.Struct(formData); err != nil {
return nil, err
}
d, err := json.Marshal(formData)
if err != nil {
return nil, err
}
var dataMap map[string]any
err = json.Unmarshal(d, &dataMap)
if err != nil {
return nil, err
}
return dataMap, nil
}
func (h *ApplicationHandler) BeneficiaryPicture(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
beneficiaryID := vars["beneficiaryid"]
@@ -312,3 +279,53 @@ func (h *ApplicationHandler) beneficiaries(r *http.Request) ([]any, error) {
return accounts, err
}
func parseBeneficiariesForm(r *http.Request) (map[string]any, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
var date *time.Time
if r.PostFormValue("birthdate") != "" {
d, err := time.Parse("2006-01-02", r.PostFormValue("birthdate"))
if err != nil {
return nil, err
}
date = &d
}
formData := BeneficiariesForm{
FirstName: r.PostFormValue("first_name"),
LastName: r.PostFormValue("last_name"),
Email: r.PostFormValue("email"),
Birthdate: date,
PhoneNumber: r.PostFormValue("phone_number"),
Gender: r.PostFormValue("gender"),
}
if r.PostFormValue("address") != "" {
var a any
json.Unmarshal([]byte(r.PostFormValue("address")), &a)
formData.Address = a
}
validate := formvalidators.New()
if err := validate.Struct(formData); err != nil {
return nil, err
}
d, err := json.Marshal(formData)
if err != nil {
return nil, err
}
var dataMap map[string]any
err = json.Unmarshal(d, &dataMap)
if err != nil {
return nil, err
}
return dataMap, nil
}

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"time"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
@@ -14,6 +15,7 @@ import (
"github.com/google/uuid"
"github.com/gorilla/mux"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
func (h *ApplicationHandler) VehiclesManagementOverview(w http.ResponseWriter, r *http.Request) {
@@ -182,6 +184,57 @@ func (h ApplicationHandler) VehicleManagementBookingDisplay(w http.ResponseWrite
booking := resp.Booking.ToStorageType()
if r.Method == "POST" {
r.ParseForm()
newbooking := resp.Booking
startdate := r.FormValue("startdate")
if startdate != "" {
newstartdate, _ := time.Parse("2006-01-02", startdate)
newbooking.Startdate = timestamppb.New(newstartdate)
if newstartdate.Before(newbooking.Unavailablefrom.AsTime()) {
newbooking.Unavailablefrom = timestamppb.New(newstartdate)
}
}
enddate := r.FormValue("enddate")
if enddate != "" {
newenddate, _ := time.Parse("2006-01-02", enddate)
newbooking.Enddate = timestamppb.New(newenddate)
if newenddate.After(newbooking.Unavailableto.AsTime()) || newenddate.Equal(newbooking.Unavailableto.AsTime()) {
newbooking.Unavailableto = timestamppb.New(newenddate.Add(24 * time.Hour))
}
}
unavailablefrom := r.FormValue("unavailablefrom")
if unavailablefrom != "" {
newunavailablefrom, _ := time.Parse("2006-01-02", unavailablefrom)
newbooking.Unavailablefrom = timestamppb.New(newunavailablefrom)
}
unavailableto := r.FormValue("unavailableto")
if unavailableto != "" {
newunavailableto, _ := time.Parse("2006-01-02", unavailableto)
newbooking.Unavailableto = timestamppb.New(newunavailableto)
}
request := &fleets.UpdateBookingRequest{
Booking: newbooking,
}
_, err := h.services.GRPC.Fleets.UpdateBooking(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
booking = newbooking.ToStorageType()
}
beneficiaryrequest := &mobilityaccounts.GetAccountRequest{
Id: booking.Driver,
}

View File

@@ -6,10 +6,15 @@ import (
"net/http"
"time"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
"git.coopgo.io/coopgo-platform/groups-management/storage"
mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
"github.com/coreos/go-oidc"
"github.com/google/uuid"
"github.com/gorilla/mux"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -71,6 +76,32 @@ func (h ApplicationHandler) VehiclesSearch(w http.ResponseWriter, r *http.Reques
}
func (h ApplicationHandler) Book(w http.ResponseWriter, r *http.Request) {
// Get Group
g := r.Context().Value(identification.GroupKey)
if g == nil {
fmt.Println("no current group")
w.WriteHeader(http.StatusInternalServerError)
return
}
current_group := g.(storage.Group)
// Get current user ID
u := r.Context().Value(identification.IdtokenKey)
if u == nil {
fmt.Println("no current user")
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_token := u.(*oidc.IDToken)
// Get current user claims
c := r.Context().Value(identification.ClaimsKey)
if c == nil {
fmt.Println("no current user claims")
w.WriteHeader(http.StatusInternalServerError)
return
}
current_user_claims := c.(map[string]any)
vars := mux.Vars(r)
vehicleid := vars["vehicleid"]
@@ -84,6 +115,25 @@ func (h ApplicationHandler) Book(w http.ResponseWriter, r *http.Request) {
startdate, _ := time.Parse("2006-01-02", start)
enddate, _ := time.Parse("2006-01-02", end)
data := map[string]any{
"booked_by": map[string]any{
"user": map[string]any{
"id": current_user_token.Subject,
"display_name": current_user_claims["display_name"],
},
"group": map[string]any{
"id": current_group.ID,
"name": current_group.Data["name"],
},
},
}
datapb, err := structpb.NewStruct(data)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
booking := &fleets.Booking{
Id: uuid.NewString(),
Vehicleid: vehicleid,
@@ -92,13 +142,14 @@ func (h ApplicationHandler) Book(w http.ResponseWriter, r *http.Request) {
Enddate: timestamppb.New(enddate),
Unavailablefrom: timestamppb.New(startdate),
Unavailableto: timestamppb.New(enddate.Add(72 * time.Hour)),
Data: datapb,
}
request := &fleets.CreateBookingRequest{
Booking: booking,
}
_, err := h.services.GRPC.Fleets.CreateBooking(context.TODO(), request)
_, err = h.services.GRPC.Fleets.CreateBooking(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusBadRequest)
@@ -136,16 +187,34 @@ func (h ApplicationHandler) VehicleBookingDisplay(w http.ResponseWriter, r *http
return
}
// grouprequest := &groupsmanagement.GetGroupRequest{
// Id: booking.Vehicle.Administrators[0],
// }
grouprequest := &groupsmanagement.GetGroupRequest{
Id: booking.Vehicle.Administrators[0],
}
// groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
// if err != nil {
// fmt.Println(err)
// w.WriteHeader(http.StatusInternalServerError)
// return
// }
groupresp, err := h.services.GRPC.GroupsManagement.GetGroup(context.TODO(), grouprequest)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
h.Renderer.VehicleBookingDisplay(w, r, booking, booking.Vehicle, beneficiaryresp.Account.ToStorageType(), "")
h.Renderer.VehicleBookingDisplay(w, r, booking, booking.Vehicle, beneficiaryresp.Account.ToStorageType(), groupresp.Group.ToStorageType())
}
func (h ApplicationHandler) VehiclesBookingsList(w http.ResponseWriter, r *http.Request) {
request := &fleets.GetBookingsRequest{}
resp, err := h.services.GRPC.Fleets.GetBookings(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
bookings := []any{}
for _, b := range resp.Bookings {
bookings = append(bookings, b.ToStorageType())
}
h.Renderer.VehicleBookingsList(w, r, bookings)
}