module Api.User exposing ( createUser , deleteUser , fetchMyInfo , fetchUsers , resetUserPassword , updateUserWorkHours ) import Api.Decoders exposing (userDecoder) import Http import Json.Decode as Decode import Json.Encode as Encode import Types.Model exposing (NewUser) import Types.Msg exposing (Msg(..)) fetchUsers : String -> Cmd Msg fetchUsers token = Http.request { method = "GET" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/admin/users/list" , body = Http.emptyBody , expect = Http.expectJson UsersReceived (Decode.list userDecoder) , timeout = Nothing , tracker = Nothing } fetchMyInfo : String -> Cmd Msg fetchMyInfo token = Http.request { method = "GET" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/my-info" , body = Http.emptyBody , expect = Http.expectJson MyInfoReceived userDecoder , timeout = Nothing , tracker = Nothing } createUser : String -> NewUser -> Cmd Msg createUser token user = Http.request { method = "POST" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/admin/users" , body = Http.jsonBody <| Encode.object [ ( "username", Encode.string user.username ) , ( "password", Encode.string user.password ) , ( "is_admin", Encode.bool user.isAdmin ) ] , expect = Http.expectWhatever UserCreated , timeout = Nothing , tracker = Nothing } deleteUser : String -> Int -> Cmd Msg deleteUser token userId = Http.request { method = "DELETE" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/admin/users/delete?id=" ++ String.fromInt userId , body = Http.emptyBody , expect = Http.expectWhatever UserDeleted , timeout = Nothing , tracker = Nothing } updateUserWorkHours : String -> Int -> String -> Cmd Msg updateUserWorkHours token userId hours = case String.toFloat hours of Just workHours -> Http.request { method = "PUT" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/admin/users/" ++ String.fromInt userId , body = Http.jsonBody <| Encode.object [ ( "yearly_hours", Encode.float workHours ) ] , expect = Http.expectWhatever UserWorkHoursSaved , timeout = Nothing , tracker = Nothing } Nothing -> Cmd.none resetUserPassword : String -> Int -> String -> Cmd Msg resetUserPassword token userId newPassword = Http.request { method = "PUT" , headers = [ Http.header "Authorization" ("Bearer " ++ token) ] , url = "/api/admin/users/" ++ String.fromInt userId ++ "/reset-password" , body = Http.jsonBody <| Encode.object [ ( "new_password", Encode.string newPassword ) ] , expect = Http.expectWhatever ResetPasswordSaved , timeout = Nothing , tracker = Nothing }