Files
schedtxt_api/internal/handler/contact.go
T
phoenixandphoenix a51979e724 tsk-58: Update names of Contact endpoint (#67)
Closes #58

Reviewed-on: phoenix/textsender-api#67
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2026-01-07 20:24:30 +00:00

247 lines
7.3 KiB
Go

package handler
import (
"fmt"
"log"
"net/http"
"git.kundeng.us/phoenix/textsender-models/tx0/contact"
"github.com/google/uuid"
"git.kundeng.us/phoenix/textsender-api/internal/app"
"git.kundeng.us/phoenix/textsender-api/internal/store"
)
type ContactHandler struct {
App *app.App
ContactStore store.ContactStore
}
func NewContactHandler(apiApp *app.App, str store.ContactStore) *ContactHandler {
return &ContactHandler{App: apiApp, ContactStore: str}
}
type RequestAddContact struct {
PhoneNumber string `json:"phone_number"`
UserId uuid.UUID `json:"user_id"`
Firstname *string `json:"first_name,omitempty"`
Lastname *string `json:"last_name,omitempty"`
Nickname *string `json:"nickname,omitempty"`
}
type AddContactResponse struct {
Message string `json:"message"`
Data []contact.Contact `json:"data"`
}
// AddContact godoc
// @Summary Add contact
// @Description Add a contact record to have a recipient to send a text to (requires JWT)
// @Tags contacts
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body RequestAddContact true "Data to add contact"
// @Success 201 {object} AddContactResponse
// @Failure 400 {object} AddContactResponse
// @Failure 500 {object} AddContactResponse
// @Router /contact/new [post]
func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
var req RequestAddContact
if err := ExtractFromRequest(r, &req); err != nil {
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
}
defer r.Body.Close()
newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: &req.UserId, Firstname: req.Firstname, Lastname: req.Lastname, Nickname: req.Nickname}
var statusCode int
var resp AddContactResponse
ctx := r.Context()
if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, *newContact.UserId); err != nil {
log.Printf("Error: %v", err)
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
if exists {
statusCode = http.StatusBadRequest
resp.Message = "Cannot create contact"
} else {
if err := c.ContactStore.CreateContact(ctx, &newContact); err != nil {
log.Printf("Error: %v", err)
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
statusCode = http.StatusCreated
resp.Message = "Contact created"
resp.Data = append(resp.Data, newContact)
}
}
}
RespondWithJSON(w, statusCode, &resp)
}
type GetContactResponse struct {
Message string `json:"message"`
Data []contact.Contact `json:"data"`
}
// GetContact godoc
// @Summary Get contact
// @Description Get a contact record to have a recipient to send a text to (requires JWT)
// @Tags contacts
// @Accept json
// @Produce json
// @Param id path string true "Contact Id"
// @Param user_id path string true "User Id"
// @Security BearerAuth
// @Success 200 {object} GetContactResponse
// @Failure 400 {object} GetContactResponse
// @Failure 500 {object} GetContactResponse
// @Router /contact [get]
func (c *ContactHandler) GetContact(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
fmt.Println("Method:", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// One or the other
var id, userId uuid.UUID
queryParams := r.URL.Query()
// Check if parameter exists
if _, exists := queryParams["id"]; !exists {
if _, exists := queryParams["user_id"]; !exists {
fmt.Fprintf(w, "Name parameter not provided")
http.Error(w, "Query params", http.StatusBadRequest)
return
} else {
var err error
userId, err = uuid.Parse(queryParams.Get("user_id"))
if err != nil {
fmt.Fprintf(w, "Name parameter exists: %s", userId)
}
}
} else {
var err error
idTmp := queryParams.Get("id")
id, err = uuid.Parse(idTmp)
if err != nil {
fmt.Println("Error:", err)
http.Error(w, "Error parsing Id", http.StatusBadRequest)
return
}
}
var statusCode int
var resp GetContactResponse
ctx := r.Context()
if id != uuid.Nil {
fmt.Println("Checking with Id")
if con, err := c.ContactStore.GetContactByID(ctx, id); err == nil {
statusCode = http.StatusOK
resp.Message = "Successful"
resp.Data = append(resp.Data, *con)
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
} else if userId != uuid.Nil {
fmt.Println("Checking with User Id")
if contacts, err := c.ContactStore.GetAllContacts(ctx); err == nil {
for _, con := range contacts {
if *con.UserId == userId {
resp.Data = append(resp.Data, *con)
}
}
if len(resp.Data) > 0 {
statusCode = http.StatusOK
resp.Message = "Successful"
} else {
statusCode = http.StatusNotFound
resp.Message = "Contact not found"
}
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
} else {
statusCode = http.StatusBadRequest
resp.Message = "Invalid query parameter"
}
RespondWithJSON(w, statusCode, &resp)
}
type UpdateNameRequest struct {
Nickname *string `json:"nickname,omitempty"`
Firstname *string `json:"first_name,omitempty"`
Lastname *string `json:"last_name,omitempty"`
ContactId uuid.UUID `json:"contact_id"`
UserId uuid.UUID `json:"user_id"`
}
type UpdateNameResponse struct {
Message string `json:"message"`
Data []contact.Contact `json:"data"`
}
// UpdateName godoc
// @Summary Update names of Contact
// @Description Update the first, last, or nickname of a Contact (requires JWT)
// @Tags contacts
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body UpdateNameRequest true "Data to update contact's names"
// @Success 200 {object} UpdateNameResponse
// @Failure 400 {object} UpdateNameResponse
// @Failure 500 {object} UpdateNameResponse
// @Router /contact/update [patch]
func (c *ContactHandler) UpdateName(w http.ResponseWriter, r *http.Request) {
var req UpdateNameRequest
if err := ExtractFromRequest(r, &req); err != nil {
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
}
defer r.Body.Close()
var statusCode int
var resp UpdateNameResponse
if req.UserId == uuid.Nil {
statusCode = http.StatusBadRequest
resp.Message = "User Id not provided"
} else if req.ContactId == uuid.Nil {
statusCode = http.StatusBadRequest
resp.Message = "Contact Id not provided"
} else if req.Firstname == nil && req.Lastname == nil && req.Nickname == nil {
statusCode = http.StatusBadRequest
resp.Message = "No name provided"
} else {
ctx := r.Context()
if con, err := c.ContactStore.GetContactByID(ctx, req.ContactId); err != nil {
resp.Message = err.Error()
statusCode = http.StatusInternalServerError
} else {
if affectedRows, err := c.ContactStore.UpdateNames(ctx, con, req.Firstname, req.Lastname, req.Nickname); err != nil {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
log.Println("Updated", affectedRows, "rows")
statusCode = http.StatusOK
resp.Message = "Successful"
resp.Data = append(resp.Data, *con)
}
}
}
RespondWithJSON(w, statusCode, &resp)
}