tsk-9: Schedule queued message endpoint (#22)

Closes #9

Reviewed-on: phoenix/textsender-api#22
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-11-09 04:32:30 +00:00
committed by phoenix
parent 0eba955ddf
commit 5f9bfa8fe2
9 changed files with 247 additions and 5 deletions
+1
View File
@@ -5,3 +5,4 @@ const ADD_MESSAGE = "/api/v1/message/new"
const GET_MESSAGE = "/api/v1/message"
const GET_CONTACT = "/api/v1/contact"
const ADD_CONTACT_ENDPOINT = "/api/v1/contact/new"
const ScheduleMessageEndpoint = "/api/v1/schedule/message"
+38
View File
@@ -9,6 +9,7 @@ import (
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
"git.kundeng.us/phoenix/textsender-models/pkg/message"
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
)
type Key struct {
@@ -200,3 +201,40 @@ func (m *MockMessageStore) MessageExists(ctx context.Context, msg *message.Messa
return exists, nil
}
type ScheduledMessageKey struct {
UserId uuid.UUID
}
type MockScheduledMessageStore struct {
ScheduledMessages map[uuid.UUID]*scheduling.ScheduledMessage
ScheduledMessagesByKey map[ScheduledMessageKey]*scheduling.ScheduledMessage
mu sync.RWMutex
Error error // Optional: simulate errors
}
func NewMockScheduledMessageStore() *MockScheduledMessageStore {
return &MockScheduledMessageStore{
ScheduledMessages: make(map[uuid.UUID]*scheduling.ScheduledMessage),
ScheduledMessagesByKey: make(map[ScheduledMessageKey]*scheduling.ScheduledMessage),
}
}
func (m *MockScheduledMessageStore) CreateScheduledMessage(ctx context.Context, schedMsg *scheduling.ScheduledMessage) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.Error != nil {
return m.Error
}
if schedMsg.Id == uuid.Nil {
schedMsg.Id = uuid.New()
}
key := ScheduledMessageKey{UserId: schedMsg.UserId}
m.ScheduledMessages[schedMsg.Id] = schedMsg
m.ScheduledMessagesByKey[key] = schedMsg
return nil
}
+109
View File
@@ -0,0 +1,109 @@
package handler
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"git.kundeng.us/phoenix/textsender-api/internal/store"
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
)
type RequestAddScheduledMessage struct {
Scheduled time.Time `json:"scheduled"`
Created time.Time `json:"created"`
Status string `json:"status"`
UserId uuid.UUID `json:"user_id"`
}
type AddScheduledMessageResponse struct {
Message string `json:"message"`
Data []scheduling.ScheduledMessage `json:"data"`
}
type ScheduledMessageHandler struct {
ScheduledMessageStore store.ScheduledMessageStore
}
func NewScheduledMessageHandler(str store.ScheduledMessageStore) *ScheduledMessageHandler {
return &ScheduledMessageHandler{ScheduledMessageStore: str}
}
func (c *ScheduledMessageHandler) AddScheduledMessage(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req RequestAddScheduledMessage
if err := ExtractFromRequest(r, &req); err != nil {
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
}
defer r.Body.Close()
scheduledMessage := scheduling.ScheduledMessage{Scheduled: req.Scheduled, Status: req.Status, UserId: req.UserId}
var statusCode int
var resp AddScheduledMessageResponse
if scheduledMessage.UserId == uuid.Nil {
statusCode = http.StatusBadRequest
resp.Message = "No UserId"
} else {
ctx := r.Context()
if validStatus, err := isStatusValid(&scheduledMessage); err == nil {
if validStatus {
if valid, err := isScheduledTimeValid(&scheduledMessage); err == nil && valid {
if err = c.ScheduledMessageStore.CreateScheduledMessage(ctx, &scheduledMessage); err == nil {
statusCode = http.StatusCreated
resp.Data = append(resp.Data, scheduledMessage)
resp.Message = "Successful"
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
} else {
statusCode = http.StatusBadRequest
resp.Message = "Invalid scheduled time"
}
} else {
statusCode = http.StatusBadRequest
resp.Message = "Invalid status"
}
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
}
RespondWithJSON(w, statusCode, &resp)
}
func isScheduledTimeValid(schMsg *scheduling.ScheduledMessage) (bool, error) {
now := time.Now()
timeCutOff := now.Add(-5 * time.Minute)
futureCutOff := now.Add((24 * 7) * time.Hour)
if schMsg.Scheduled.After(timeCutOff) {
if schMsg.Scheduled.Before(futureCutOff) {
return true, nil
} else {
return false, fmt.Errorf("Scheduled Time is too far in the future")
}
} else {
return false, nil
}
}
func isStatusValid(schMsg *scheduling.ScheduledMessage) (bool, error) {
schMsg.Status = strings.ToUpper(schMsg.Status)
if schMsg.Status == scheduling.Pending {
return true, nil
} else {
return false, fmt.Errorf("Status is not valid for creating scheduled message %s", schMsg.Status)
}
}
@@ -0,0 +1,48 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
)
type CreateScheduledMessageRequest struct {
Scheduled time.Time `json:"scheduled"`
Status string `json:"status"`
UserId uuid.UUID `json:"user_id"`
}
func TestCreateScheduledMessageWithMock(t *testing.T) {
now := time.Now()
mockStore := NewMockScheduledMessageStore()
handler := NewScheduledMessageHandler(mockStore)
testUserId := uuid.New()
scheduled := now.Add(5 * time.Minute)
testBody := CreateScheduledMessageRequest{Status: scheduling.Pending, UserId: testUserId, Scheduled: scheduled}
jsonValue, _ := json.Marshal(testBody)
req, _ := http.NewRequest("POST", endpoint.ScheduleMessageEndpoint, strings.NewReader(string(jsonValue)))
rr := httptest.NewRecorder()
handler.AddScheduledMessage(rr, req)
assert.Equal(t, http.StatusCreated, rr.Code)
var response AddScheduledMessageResponse
err := json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err, "Error Creating message %v", err)
assert.NotEmpty(t, response.Data, "No Message created")
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
}