Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
fix: address PR review comments for send schedule feature
Acho Arnold2b9a45f2391e
diff --git a/api/pkg/di/container.go b/api/pkg/di/container.goindex 66b57468..cf8360f4 100644--- a/api/pkg/di/container.go+++ b/api/pkg/di/container.go@@ -1117,6 +1117,7 @@ func (container *Container) PhoneHandler() (handler *handlers.PhoneHandler) {container.Logger(),container.Tracer(),container.PhoneService(),+ container.MessageSendScheduleService(),container.PhoneHandlerValidator(),)}diff --git a/api/pkg/entities/message_send_schedule.go b/api/pkg/entities/message_send_schedule.goindex 9ffbad12..17b8a7b7 100644--- a/api/pkg/entities/message_send_schedule.go+++ b/api/pkg/entities/message_send_schedule.go@@ -27,9 +27,14 @@ type MessageSendSchedule struct {// ResolveScheduledAt returns the next allowed send time based on the schedule.// If the schedule is inactive, has no windows, or has an invalid timezone,-// the current time is returned in UTC.+// the current time is returned in UTC. An active schedule with no windows+// is treated as inactive (messages are sent immediately).func (schedule *MessageSendSchedule) ResolveScheduledAt(current time.Time) time.Time {- if schedule == nil || !schedule.IsActive || len(schedule.Windows) == 0 {+ if schedule == nil || !schedule.IsActive {+ return current.UTC()+ }++ if len(schedule.Windows) == 0 {return current.UTC()}diff --git a/api/pkg/handlers/message_send_schedule_handler.go b/api/pkg/handlers/message_send_schedule_handler.goindex d7df8cdb..a688987c 100644--- a/api/pkg/handlers/message_send_schedule_handler.go+++ b/api/pkg/handlers/message_send_schedule_handler.go@@ -56,7 +56,7 @@ func (h *MessageSendScheduleHandler) RegisterRoutes(router fiber.Router, middlew// @Security ApiKeyAuth// @Tags Send Schedules// @Produce json-// @Success 200 {array} entities.MessageSendSchedule+// @Success 200 {object} responses.MessageSendSchedulesResponse// @Failure 401 {object} responses.Unauthorized// @Failure 500 {object} responses.InternalServerError// @Router /send-schedules [get]@@ -85,7 +85,7 @@ func (h *MessageSendScheduleHandler) Index(c *fiber.Ctx) error {// @Success 201 {object} responses.MessageSendScheduleResponse// @Failure 400 {object} responses.BadRequest// @Failure 401 {object} responses.Unauthorized-// @Failure 402 {object} responses.BadRequest+// @Failure 402 {object} responses.PaymentRequired// @Failure 422 {object} responses.UnprocessableEntity// @Failure 500 {object} responses.InternalServerError// @Router /send-schedules [post]diff --git a/api/pkg/handlers/phone_handler.go b/api/pkg/handlers/phone_handler.goindex 9e5cbe1c..62ec35b7 100644--- a/api/pkg/handlers/phone_handler.go+++ b/api/pkg/handlers/phone_handler.go@@ -2,10 +2,13 @@ package handlersimport ("fmt"+ "net/url"+ "strings""github.com/NdoleStudio/httpsms/pkg/requests""github.com/NdoleStudio/httpsms/pkg/validators""github.com/davecgh/go-spew/spew"+ "github.com/google/uuid""github.com/NdoleStudio/httpsms/pkg/services""github.com/NdoleStudio/httpsms/pkg/telemetry"@@ -16,10 +19,11 @@ import (// PhoneHandler handles phone http requests.type PhoneHandler struct {handler- logger telemetry.Logger- tracer telemetry.Tracer- service *services.PhoneService- validator *validators.PhoneHandlerValidator+ logger telemetry.Logger+ tracer telemetry.Tracer+ service *services.PhoneService+ scheduleService *services.MessageSendScheduleService+ validator *validators.PhoneHandlerValidator}// NewPhoneHandler creates a new PhoneHandler@@ -27,13 +31,15 @@ func NewPhoneHandler(logger telemetry.Logger,tracer telemetry.Tracer,service *services.PhoneService,+ scheduleService *services.MessageSendScheduleService,validator *validators.PhoneHandlerValidator,) (h *PhoneHandler) {return &PhoneHandler{- logger: logger.WithService(fmt.Sprintf("%T", h)),- tracer: tracer,- validator: validator,- service: service,+ logger: logger.WithService(fmt.Sprintf("%T", h)),+ tracer: tracer,+ validator: validator,+ service: service,+ scheduleService: scheduleService,}}@@ -127,6 +133,15 @@ func (h *PhoneHandler) Upsert(c *fiber.Ctx) error {return h.responseUnprocessableEntity(c, errors, "validation errors while updating phones")}+ if request.ScheduleID != nil && strings.TrimSpace(*request.ScheduleID) != "" {+ scheduleID, _ := uuid.Parse(strings.TrimSpace(*request.ScheduleID))+ if _, err := h.scheduleService.Load(ctx, h.userFromContext(c).ID, scheduleID); err != nil {+ validationErrors := url.Values{}+ validationErrors.Add("schedule_id", "schedule_id does not belong to the authenticated user or does not exist")+ return h.responseUnprocessableEntity(c, validationErrors, "validation errors while updating phones")+ }+ }+phone, err := h.service.Upsert(ctx, request.ToUpsertParams(h.userFromContext(c), c.OriginalURL()))if err != nil {msg := fmt.Sprintf("cannot update phones with params [%+#v]", request)diff --git a/api/pkg/requests/phone_update_request.go b/api/pkg/requests/phone_update_request.goindex bb710024..06876de8 100644--- a/api/pkg/requests/phone_update_request.go+++ b/api/pkg/requests/phone_update_request.go@@ -31,7 +31,7 @@ type PhoneUpsert struct {// SIM is the SIM slot of the phone in case the phone has more than 1 SIM slotSIM string `json:"sim" example:"SIM1"`- ScheduleID *string `json:"schedule_id" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`+ ScheduleID *string `json:"schedule_id,omitempty" example:"32343a19-da5e-4b1b-a767-3298a73703cb" validate:"optional"`}// Sanitize sets defaults to MessageOutstandingdiff --git a/api/pkg/responses/response.go b/api/pkg/responses/response.goindex c61c919e..e23fea0f 100644--- a/api/pkg/responses/response.go+++ b/api/pkg/responses/response.go@@ -38,6 +38,12 @@ type Unauthorized struct {Data string `json:"data" example:"Make sure your API key is set in the [X-API-Key] header in the request"`}+// PaymentRequired is the response with status code is 402+type PaymentRequired struct {+ Status string `json:"status" example:"error"`+ Message string `json:"message" example:"You have reached the maximum number of allowed resources. Please upgrade your plan."`+}+// NoContent is the response when status code is 204type NoContent struct {Status string `json:"status" example:"success"`diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vueindex de6c0b05..cbe4fe6e 100644--- a/web/pages/settings/index.vue+++ b/web/pages/settings/index.vue@@ -1779,10 +1779,10 @@ export default Vue.extend({}const message = messages.find((x: string) =>- x.includes(`Day of week ${index}`),+ x.includes(`day_of_week ${index}`),)return message- ? message.replace(`Day of week ${index}`, this.getWeekday(index))+ ? message.replace(`day_of_week ${index}`, this.getWeekday(index)): null},diff --git a/web/store/index.ts b/web/store/index.tsindex 9e52a240..bd3071e6 100644--- a/web/store/index.ts+++ b/web/store/index.ts@@ -1111,23 +1111,17 @@ export const actions = {getSendSchedules(context: ActionContext<State, State>) {return new Promise<Array<EntitiesSendSchedule>>((resolve, reject) => {axios- .get<ResponsesSendSchedulesResponse>(`/v1/send-schedules`, {- params: {- limit: 100,- },- })+ .get<ResponsesSendSchedulesResponse>(`/v1/send-schedules`).then((response: AxiosResponse<ResponsesSendSchedulesResponse>) => {resolve(response.data.data)}).catch(async (error: AxiosError) => {- await Promise.all([- context.dispatch('addNotification', {- message:- (error.response?.data as any)?.message ??- 'Error while fetching send schedules',- type: 'error',- }),- ])+ await context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while fetching send schedules',+ type: 'error',+ })reject(getErrorMessages(error))})})@@ -1144,14 +1138,12 @@ export const actions = {resolve(response.data.data)}).catch(async (error: AxiosError) => {- await Promise.all([- context.dispatch('addNotification', {- message:- (error.response?.data as any)?.message ??- 'Error while creating send schedule',- type: 'error',- }),- ])+ await context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while creating send schedule',+ type: 'error',+ })reject(getErrorMessages(error))})})@@ -1171,23 +1163,18 @@ export const actions = {resolve(response.data.data)}).catch(async (error: AxiosError) => {- await Promise.all([- context.dispatch('addNotification', {- message:- (error.response?.data as any)?.message ??- 'Error while updating send schedule',- type: 'error',- }),- ])+ await context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while updating send schedule',+ type: 'error',+ })reject(getErrorMessages(error))})})},- deleteSendSchedule(- context: ActionContext<State, State>,- payload: string,- ) {+ deleteSendSchedule(context: ActionContext<State, State>, payload: string) {return new Promise<void>((resolve, reject) => {axios.delete<ResponsesNoContent>(`/v1/send-schedules/${payload}`)@@ -1195,14 +1182,12 @@ export const actions = {resolve()}).catch(async (error: AxiosError) => {- await Promise.all([- context.dispatch('addNotification', {- message:- (error.response?.data as any)?.message ??- 'Error while deleting send schedule',- type: 'error',- }),- ])+ await context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while deleting send schedule',+ type: 'error',+ })reject(getErrorMessages(error))})})