package application import ( "bytes" "context" "encoding/json" "fmt" "image/png" "log" "net/http" "strconv" "strings" "time" 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" 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/google/uuid" "github.com/gorilla/mux" "google.golang.org/protobuf/types/known/structpb" ) type BeneficiariesForm struct { FirstName string `json:"first_name" validate:"required"` LastName string `json:"last_name" validate:"required"` Email string `json:"email" validate:"required,email"` Birthdate *time.Time `json:"birthdate"` PhoneNumber string `json:"phone_number" validate:"required,phoneNumber"` Address any `json:"address,omitempty"` Gender string `json:"gender"` } func (h *ApplicationHandler) BeneficiariesList(w http.ResponseWriter, r *http.Request) { g := r.Context().Value(identification.GroupKey) if g == nil { w.WriteHeader(http.StatusBadRequest) return } group := g.(storage.Group) request := &mobilityaccounts.GetAccountsBatchRequest{ Accountids: group.Members, } resp, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } var accounts = []any{} for _, account := range resp.Accounts { if filterAccount(r, account) { a := account.ToStorageType() accounts = append(accounts, a) } } cacheid := uuid.NewString() h.cache.PutWithTTL(cacheid, accounts, 1*time.Hour) h.Renderer.BeneficiariesList(w, r, accounts, cacheid) } func (h *ApplicationHandler) BeneficiaryCreate(w http.ResponseWriter, r *http.Request) { g := r.Context().Value(identification.GroupKey) if g == nil { w.WriteHeader(http.StatusBadRequest) return } group := g.(storage.Group) fmt.Println(group) if r.Method == "POST" { dataMap, err := parseForm(r) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusBadRequest) return } data, err := structpb.NewValue(dataMap) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } request := &mobilityaccounts.RegisterRequest{ Account: &mobilityaccounts.Account{ Namespace: "parcoursmob_beneficiaries", Data: data.GetStructValue(), }, } resp, err := h.services.GRPC.MobilityAccounts.Register(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } subscribe := &groupsmanagement.SubscribeRequest{ Groupid: group.ID, Memberid: resp.Account.Id, } _, err = h.services.GRPC.GroupsManagement.Subscribe(context.TODO(), subscribe) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", resp.Account.Id), http.StatusFound) return } h.Renderer.BeneficiaryCreate(w, r) } func (h *ApplicationHandler) BeneficiaryDisplay(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) beneficiaryID := vars["beneficiaryid"] request := &mobilityaccounts.GetAccountRequest{ Id: beneficiaryID, } resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } //TODO filter namespaces //TODO filter groups h.Renderer.BeneficiaryDisplay(w, r, resp.Account.ToStorageType()) } func (h *ApplicationHandler) BeneficiaryUpdate(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) beneficiaryID := vars["beneficiaryid"] if r.Method == "POST" { dataMap, err := parseForm(r) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusBadRequest) return } data, err := structpb.NewValue(dataMap) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } request := &mobilityaccounts.UpdateDataRequest{ Account: &mobilityaccounts.Account{ Id: beneficiaryID, Namespace: "parcoursmob_beneficiaries", Data: data.GetStructValue(), }, } resp, err := h.services.GRPC.MobilityAccounts.UpdateData(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } http.Redirect(w, r, fmt.Sprintf("/app/beneficiaries/%s", resp.Account.Id), http.StatusFound) return } request := &mobilityaccounts.GetAccountRequest{ Id: beneficiaryID, } resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } //TODO filter namespaces //TODO filter groups 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"] request := &mobilityaccounts.GetAccountRequest{ Id: beneficiaryID, } resp, err := h.services.GRPC.MobilityAccounts.GetAccount(context.TODO(), request) if err != nil { fmt.Println(err) w.WriteHeader(http.StatusInternalServerError) return } account := resp.Account.ToStorageType() firstName := account.Data["first_name"].(string) lastName := account.Data["last_name"].(string) picture := profilepictures.DefaultProfilePicture(strings.ToUpper(firstName[0:1] + lastName[0:1])) buffer := new(bytes.Buffer) if err := png.Encode(buffer, picture); err != nil { log.Println("unable to encode image.") } w.Header().Set("Content-Type", "image/png") w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes()))) if _, err := w.Write(buffer.Bytes()); err != nil { log.Println("unable to write image.") } } func filterAccount(r *http.Request, a *mobilityaccounts.Account) bool { searchFilter, ok := r.URL.Query()["search"] if ok && len(searchFilter[0]) > 0 { name := a.Data.AsMap()["first_name"].(string) + " " + a.Data.AsMap()["last_name"].(string) if !strings.Contains(strings.ToLower(name), strings.ToLower(searchFilter[0])) { return false } } return true }