Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
fix: handle review feedback
giresse199de415629800
diff --git a/api/pkg/handlers/send_schedule_handler.go b/api/pkg/handlers/send_schedule_handler.goindex 22b47deb..70918cdd 100644--- a/api/pkg/handlers/send_schedule_handler.go+++ b/api/pkg/handlers/send_schedule_handler.go@@ -21,21 +21,30 @@ type SendScheduleHandler struct {service *services.SendScheduleService}-func NewSendScheduleHandler(logger telemetry.Logger, tracer telemetry.Tracer, validator *validators.SendScheduleHandlerValidator, service *services.SendScheduleService) *SendScheduleHandler {- return &SendScheduleHandler{logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleHandler{})), tracer: tracer, validator: validator, service: service}+func NewSendScheduleHandler(+ logger telemetry.Logger,+ tracer telemetry.Tracer,+ validator *validators.SendScheduleHandlerValidator,+ service *services.SendScheduleService,+) *SendScheduleHandler {+ return &SendScheduleHandler{+ logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleHandler{})),+ tracer: tracer,+ validator: validator,+ service: service,+ }}func (h *SendScheduleHandler) RegisterRoutes(router fiber.Router, middlewares ...fiber.Handler) {router.Get("/v1/send-schedules", h.computeRoute(middlewares, h.Index)...)router.Post("/v1/send-schedules", h.computeRoute(middlewares, h.Store)...)- router.Get("/v1/send-schedules/:scheduleID", h.computeRoute(middlewares, h.Show)...)router.Put("/v1/send-schedules/:scheduleID", h.computeRoute(middlewares, h.Update)...)router.Delete("/v1/send-schedules/:scheduleID", h.computeRoute(middlewares, h.Delete)...)}// Index godoc// @Summary List send schedules-// @Description Lists the send schedules owned by the authenticated user.+// @Description List all send schedules owned by the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Produce json@@ -46,47 +55,19 @@ func (h *SendScheduleHandler) RegisterRoutes(router fiber.Router, middlewares ..func (h *SendScheduleHandler) Index(c *fiber.Ctx) error {ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)defer span.End()+schedules, err := h.service.Index(ctx, h.userIDFomContext(c))if err != nil {ctxLogger.Error(stacktrace.Propagate(err, "cannot list send schedules"))return h.responseInternalServerError(c)}- return h.responseOK(c, "send schedules fetched successfully", schedules)-}-// Show godoc-// @Summary Show send schedule-// @Description Loads a single send schedule owned by the authenticated user.-// @Security ApiKeyAuth-// @Tags Send Schedules-// @Produce json-// @Param scheduleID path string true "Schedule ID"-// @Success 200 {object} responses.SendScheduleResponse-// @Failure 401 {object} responses.Unauthorized-// @Failure 404 {object} responses.NotFound-// @Failure 500 {object} responses.InternalServerError-// @Router /send-schedules/{scheduleID} [get]-func (h *SendScheduleHandler) Show(c *fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()- scheduleID, err := uuid.Parse(c.Params("scheduleID"))- if err != nil {- return h.responseBadRequest(c, err)- }- schedule, err := h.service.Load(ctx, h.userIDFomContext(c), scheduleID)- if err != nil {- ctxLogger.Error(stacktrace.Propagate(err, "cannot load send schedule"))- if stacktrace.GetCode(err) == 404 {- return h.responseNotFound(c, err.Error())- }- return h.responseInternalServerError(c)- }- return h.responseOK(c, "send schedule fetched successfully", schedule)+ return h.responseOK(c, "send schedules fetched successfully", schedules)}// Store godoc// @Summary Create send schedule-// @Description Creates a send schedule for the authenticated user.+// @Description Create a new send schedule for the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Accept json@@ -101,26 +82,34 @@ func (h *SendScheduleHandler) Show(c *fiber.Ctx) error {func (h *SendScheduleHandler) Store(c *fiber.Ctx) error {ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)defer span.End()+var request requests.SendScheduleStoreif err := c.BodyParser(&request); err != nil {return h.responseBadRequest(c, err)}+request = request.Sanitize()if errors := h.validator.ValidateStore(ctx, request); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewError(fmt.Sprintf("validation errors [%s], while storing send schedule [%+#v]", spew.Sdump(errors), request)))+ ctxLogger.Warn(stacktrace.NewError(fmt.Sprintf(+ "validation errors [%s], while storing send schedule [%+#v]",+ spew.Sdump(errors),+ request,+ )))return h.responseUnprocessableEntity(c, errors, "validation errors while saving send schedule")}+schedule, err := h.service.Store(ctx, request.ToParams(h.userFromContext(c)))if err != nil {ctxLogger.Error(stacktrace.Propagate(err, "cannot create send schedule"))return h.responseInternalServerError(c)}+return h.responseCreated(c, "send schedule created successfully", schedule)}// Update godoc// @Summary Update send schedule-// @Description Updates a send schedule owned by the authenticated user.+// @Description Update a send schedule owned by the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Accept json@@ -137,19 +126,28 @@ func (h *SendScheduleHandler) Store(c *fiber.Ctx) error {func (h *SendScheduleHandler) Update(c *fiber.Ctx) error {ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)defer span.End()+scheduleID, err := uuid.Parse(c.Params("scheduleID"))if err != nil {return h.responseBadRequest(c, err)}+var request requests.SendScheduleStoreif err = c.BodyParser(&request); err != nil {return h.responseBadRequest(c, err)}+request = request.Sanitize()if errors := h.validator.ValidateStore(ctx, request); len(errors) != 0 {return h.responseUnprocessableEntity(c, errors, "validation errors while updating send schedule")}- schedule, err := h.service.Update(ctx, h.userIDFomContext(c), scheduleID, request.ToParams(h.userFromContext(c)))++ schedule, err := h.service.Update(+ ctx,+ h.userIDFomContext(c),+ scheduleID,+ request.ToParams(h.userFromContext(c)),+ )if err != nil {ctxLogger.Error(stacktrace.Propagate(err, "cannot update send schedule"))if stacktrace.GetCode(err) == 404 {@@ -157,12 +155,13 @@ func (h *SendScheduleHandler) Update(c *fiber.Ctx) error {}return h.responseInternalServerError(c)}+return h.responseOK(c, "send schedule updated successfully", schedule)}// Delete godoc// @Summary Delete send schedule-// @Description Deletes a send schedule owned by the authenticated user.+// @Description Delete a send schedule owned by the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Produce json@@ -170,18 +169,25 @@ func (h *SendScheduleHandler) Update(c *fiber.Ctx) error {// @Success 204 {object} responses.NoContent// @Failure 400 {object} responses.BadRequest// @Failure 401 {object} responses.Unauthorized+// @Failure 404 {object} responses.NotFound// @Failure 500 {object} responses.InternalServerError// @Router /send-schedules/{scheduleID} [delete]func (h *SendScheduleHandler) Delete(c *fiber.Ctx) error {ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)defer span.End()+scheduleID, err := uuid.Parse(c.Params("scheduleID"))if err != nil {return h.responseBadRequest(c, err)}+if err = h.service.Delete(ctx, h.userIDFomContext(c), scheduleID); err != nil {ctxLogger.Error(stacktrace.Propagate(err, "cannot delete send schedule"))+ if stacktrace.GetCode(err) == 404 {+ return h.responseNotFound(c, err.Error())+ }return h.responseInternalServerError(c)}+return h.responseNoContent(c, "send schedule deleted successfully")}diff --git a/api/pkg/services/phone_notification_service.go b/api/pkg/services/phone_notification_service.goindex e8b7e013..38c577b5 100644--- a/api/pkg/services/phone_notification_service.go+++ b/api/pkg/services/phone_notification_service.go@@ -40,7 +40,7 @@ func NewNotificationService(dispatcher *EventDispatcher,) (s *PhoneNotificationService) {return &PhoneNotificationService{- logger: logger.WithService(fmt.Sprintf("%T", s)),+ logger: logger.WithService(fmt.Sprintf("%T", &PhoneNotificationService{})),tracer: tracer,messagingClient: messagingClient,phoneNotificationRepository: phoneNotificationRepository,@@ -95,7 +95,13 @@ func (service *PhoneNotificationService) SendHeartbeatFCM(ctx context.Context, preturn nil}- ctxLogger.Info(fmt.Sprintf("successfully sent heartbeat FCM [%s] to phone with ID [%s] for user [%s] and monitor [%s]", result, payload.PhoneID, payload.UserID, payload.MonitorID))+ ctxLogger.Info(fmt.Sprintf(+ "successfully sent heartbeat FCM [%s] to phone with ID [%s] for user [%s] and monitor [%s]",+ result,+ payload.PhoneID,+ payload.UserID,+ payload.MonitorID,+ ))return nil}@@ -137,7 +143,15 @@ func (service *PhoneNotificationService) Send(ctx context.Context, params *PhoneToken: *phone.FcmToken,})if err != nil {- ctxLogger.Warn(stacktrace.Propagate(err, fmt.Sprintf("cannot send FCM to phone with ID [%s] for user with ID [%s] and message [%s]", phone.ID, phone.UserID, params.MessageID)))+ ctxLogger.Warn(stacktrace.Propagate(+ err,+ fmt.Sprintf(+ "cannot send FCM to phone with ID [%s] for user with ID [%s] and message [%s]",+ phone.ID,+ phone.UserID,+ params.MessageID,+ ),+ ))msg := fmt.Sprintf("cannot send notification for to your phone [%s]. Reinstall the httpSMS app on your Android phone.", phone.PhoneNumber)return service.handleNotificationFailed(ctx, errors.New(msg), params)}@@ -184,12 +198,13 @@ func (service *PhoneNotificationService) Schedule(ctx context.Context, params *Pvar schedule *entities.SendScheduleif phone.ScheduleID != nil {schedule, err = service.sendScheduleRepository.Load(ctx, params.UserID, *phone.ScheduleID)- if err != nil && stacktrace.GetCode(err) != repositories.ErrCodeNotFound {- msg := fmt.Sprintf("cannot load send schedule [%s] for phone [%s]", *phone.ScheduleID, phone.ID)- return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {schedule = nil+ err = nil+ }+ if err != nil {+ msg := fmt.Sprintf("cannot load send schedule [%s] for phone [%s]", *phone.ScheduleID, phone.ID)+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}}@@ -206,11 +221,20 @@ func (service *PhoneNotificationService) Schedule(ctx context.Context, params *Preturn service.tracer.WrapErrorSpan(span, err)}- ctxLogger.Info(fmt.Sprintf("message with id [%s] notification scheduled for [%s] with id [%s]", params.MessageID, notification.ScheduledAt, notification.ID))+ ctxLogger.Info(fmt.Sprintf(+ "message with id [%s] notification scheduled for [%s] with id [%s]",+ params.MessageID,+ notification.ScheduledAt,+ notification.ID,+ ))return nil}-func (service *PhoneNotificationService) dispatchMessageNotificationSend(ctx context.Context, source string, notification *entities.PhoneNotification) error {+func (service *PhoneNotificationService) dispatchMessageNotificationSend(+ ctx context.Context,+ source string,+ notification *entities.PhoneNotification,+) error {event, err := service.createMessageNotificationSendEvent(source, &events.MessageNotificationSendPayload{MessageID: notification.MessageID,UserID: notification.UserID,@@ -228,7 +252,11 @@ func (service *PhoneNotificationService) dispatchMessageNotificationSend(ctx conreturn nil}-func (service *PhoneNotificationService) dispatchMessageNotificationScheduled(ctx context.Context, params *PhoneNotificationScheduleParams, notification *entities.PhoneNotification) error {+func (service *PhoneNotificationService) dispatchMessageNotificationScheduled(+ ctx context.Context,+ params *PhoneNotificationScheduleParams,+ notification *entities.PhoneNotification,+) error {event, err := service.createMessageNotificationScheduledEvent(params.Source, &events.MessageNotificationScheduledPayload{MessageID: notification.MessageID,Owner: params.Owner,@@ -273,7 +301,12 @@ func (service *PhoneNotificationService) handleNotificationFailed(ctx context.Coreturn nil}-func (service *PhoneNotificationService) handleNotificationSent(ctx context.Context, phone *entities.Phone, result string, params *PhoneNotificationSendParams) error {+func (service *PhoneNotificationService) handleNotificationSent(+ ctx context.Context,+ phone *entities.Phone,+ result string,+ params *PhoneNotificationSendParams,+) error {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -294,15 +327,26 @@ func (service *PhoneNotificationService) handleNotificationSent(ctx context.Contreturn nil}-func (service *PhoneNotificationService) createMessageNotificationScheduledEvent(source string, payload *events.MessageNotificationScheduledPayload) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationScheduledEvent(+ source string,+ payload *events.MessageNotificationScheduledPayload,+) (cloudevents.Event, error) {return service.createEvent(events.EventTypeMessageNotificationScheduled, source, payload)}-func (service *PhoneNotificationService) createMessageNotificationSendEvent(source string, payload *events.MessageNotificationSendPayload) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationSendEvent(+ source string,+ payload *events.MessageNotificationSendPayload,+) (cloudevents.Event, error) {return service.createEvent(events.EventTypeMessageNotificationSend, source, payload)}-func (service *PhoneNotificationService) createMessageNotificationSentEvent(source string, phone *entities.Phone, fcmMessageID string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationSentEvent(+ source string,+ phone *entities.Phone,+ fcmMessageID string,+ params *PhoneNotificationSendParams,+) (cloudevents.Event, error) {event := cloudevents.NewEvent()event.SetSource(source)@@ -329,7 +373,11 @@ func (service *PhoneNotificationService) createMessageNotificationSentEvent(sourreturn event, nil}-func (service *PhoneNotificationService) createMessageNotificationFailedEvent(source string, errorMessage string, params *PhoneNotificationSendParams) (cloudevents.Event, error) {+func (service *PhoneNotificationService) createMessageNotificationFailedEvent(+ source string,+ errorMessage string,+ params *PhoneNotificationSendParams,+) (cloudevents.Event, error) {event := cloudevents.NewEvent()event.SetSource(source)@@ -354,7 +402,11 @@ func (service *PhoneNotificationService) createMessageNotificationFailedEvent(soreturn event, nil}-func (service *PhoneNotificationService) updateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) {+func (service *PhoneNotificationService) updateStatus(+ ctx context.Context,+ notificationID uuid.UUID,+ status entities.PhoneNotificationStatus,+) {ctx, span := service.tracer.Start(ctx)defer span.End()@@ -362,9 +414,9 @@ func (service *PhoneNotificationService) updateStatus(ctx context.Context, notiferr := service.phoneNotificationRepository.UpdateStatus(ctx, notificationID, status)if err != nil {- msg := fmt.Sprintf("cannot update status of notificaiton with id [%s] to [%s]", notificationID, status)+ msg := fmt.Sprintf("cannot update status of notification with id [%s] to [%s]", notificationID, status)ctxLogger.Error(stacktrace.Propagate(err, msg))}- ctxLogger.Info(fmt.Sprintf("updated status of notificaiton with id [%s] to [%s]", notificationID, status))+ ctxLogger.Info(fmt.Sprintf("updated status of notification with id [%s] to [%s]", notificationID, status))}diff --git a/api/pkg/validators/send_schedule_handler_validator.go b/api/pkg/validators/send_schedule_handler_validator.goindex a199f398..313eba9d 100644--- a/api/pkg/validators/send_schedule_handler_validator.go+++ b/api/pkg/validators/send_schedule_handler_validator.go@@ -11,17 +11,28 @@ import ("github.com/thedevsaddam/govalidator")+const maxWindowsPerDay = 6+type SendScheduleHandlerValidator struct {validatorlogger telemetry.Loggertracer telemetry.Tracer}-func NewSendScheduleHandlerValidator(logger telemetry.Logger, tracer telemetry.Tracer) *SendScheduleHandlerValidator {- return &SendScheduleHandlerValidator{logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleHandlerValidator{})), tracer: tracer}+func NewSendScheduleHandlerValidator(+ logger telemetry.Logger,+ tracer telemetry.Tracer,+) *SendScheduleHandlerValidator {+ return &SendScheduleHandlerValidator{+ logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleHandlerValidator{})),+ tracer: tracer,+ }}-func (validator *SendScheduleHandlerValidator) ValidateStore(_ context.Context, request requests.SendScheduleStore) url.Values {+func (validator *SendScheduleHandlerValidator) ValidateStore(+ _ context.Context,+ request requests.SendScheduleStore,+) url.Values {v := govalidator.New(govalidator.Options{Data: &request,Rules: govalidator.MapData{@@ -29,27 +40,77 @@ func (validator *SendScheduleHandlerValidator) ValidateStore(_ context.Context,"timezone": []string{"required", "min:2", "max:100"},},})+result := v.ValidateStruct()validator.validateWindows(result, request.Windows)+if _, err := time.LoadLocation(request.Timezone); err != nil {result.Add("timezone", "timezone must be a valid IANA timezone")}+return result}-func (validator *SendScheduleHandlerValidator) validateWindows(result url.Values, windows []requests.SendScheduleWindow) {+func (validator *SendScheduleHandlerValidator) validateWindows(+ result url.Values,+ windows []requests.SendScheduleWindow,+) {+ windowsPerDay := make(map[int]int)+for index, item := range windows {- if item.DayOfWeek < 0 || item.DayOfWeek > 6 {- result.Add("windows", fmt.Sprintf("windows[%d].day_of_week must be between 0 and 6", index))- }- if item.StartMinute < 0 || item.StartMinute > 1439 {- result.Add("windows", fmt.Sprintf("windows[%d].start_minute must be between 0 and 1439", index))- }- if item.EndMinute < 1 || item.EndMinute > 1440 {- result.Add("windows", fmt.Sprintf("windows[%d].end_minute must be between 1 and 1440", index))- }- if item.EndMinute <= item.StartMinute {- result.Add("windows", fmt.Sprintf("windows[%d].end_minute must be greater than start_minute", index))- }+ validator.validateDayOfWeek(result, index, item, windowsPerDay)+ validator.validateStartMinute(result, index, item)+ validator.validateEndMinute(result, index, item)+ validator.validateWindowRange(result, index, item)+ }+}++func (validator *SendScheduleHandlerValidator) validateDayOfWeek(+ result url.Values,+ index int,+ item requests.SendScheduleWindow,+ windowsPerDay map[int]int,+) {+ if item.DayOfWeek < 0 || item.DayOfWeek > 6 {+ result.Add("windows", fmt.Sprintf("windows[%d].day_of_week must be between 0 and 6", index))+ return+ }++ windowsPerDay[item.DayOfWeek]+++ if windowsPerDay[item.DayOfWeek] > maxWindowsPerDay {+ result.Add(+ "windows",+ fmt.Sprintf("day_of_week %d cannot have more than %d windows", item.DayOfWeek, maxWindowsPerDay),+ )+ }+}++func (validator *SendScheduleHandlerValidator) validateStartMinute(+ result url.Values,+ index int,+ item requests.SendScheduleWindow,+) {+ if item.StartMinute < 0 || item.StartMinute > 1439 {+ result.Add("windows", fmt.Sprintf("windows[%d].start_minute must be between 0 and 1439", index))+ }+}++func (validator *SendScheduleHandlerValidator) validateEndMinute(+ result url.Values,+ index int,+ item requests.SendScheduleWindow,+) {+ if item.EndMinute < 1 || item.EndMinute > 1440 {+ result.Add("windows", fmt.Sprintf("windows[%d].end_minute must be between 1 and 1440", index))+ }+}++func (validator *SendScheduleHandlerValidator) validateWindowRange(+ result url.Values,+ index int,+ item requests.SendScheduleWindow,+) {+ if item.EndMinute <= item.StartMinute {+ result.Add("windows", fmt.Sprintf("windows[%d].end_minute must be greater than start_minute", index))}}diff --git a/web/models/api.ts b/web/models/api.tsindex 660e7493..c305c134 100644--- a/web/models/api.ts+++ b/web/models/api.ts@@ -172,6 +172,8 @@ export interface EntitiesPhone {missed_call_auto_reply?: string/** @example "+18005550199" */phone_number: string+ /** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */+ schedule_id?: string | null/** SIM card that received the message */sim: string/** @example "2022-06-05T14:26:10.303278+03:00" */@@ -255,6 +257,62 @@ export interface EntitiesWebhook {user_id: string}+export interface EntitiesSendScheduleWindow {+ /** @example 1 */+ day_of_week: number+ /** @example 1020 */+ end_minute: number+ /** @example 540 */+ start_minute: number+}++export interface EntitiesSendSchedule {+ /** @example true */+ is_active: boolean+ /** @example "2022-06-05T14:26:02.302718+03:00" */+ created_at: string+ /** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */+ id: string+ /** @example "Business Hours" */+ name: string+ /** @example "Africa/Accra" */+ timezone: string+ /** @example "2022-06-05T14:26:10.303278+03:00" */+ updated_at: string+ /** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */+ user_id: string+ windows: EntitiesSendScheduleWindow[]+}++export interface RequestsSendScheduleWindow {+ day_of_week: number+ end_minute: number+ start_minute: number+}++export interface RequestsSendScheduleStore {+ is_active: boolean+ name: string+ timezone: string+ windows: RequestsSendScheduleWindow[]+}++export interface ResponsesSendScheduleResponse {+ data: EntitiesSendSchedule+ /** @example "Request handled successfully" */+ message: string+ /** @example "success" */+ status: string+}++export interface ResponsesSendSchedulesResponse {+ data: EntitiesSendSchedule[]+ /** @example "Request handled successfully" */+ message: string+ /** @example "success" */+ status: string+}+export interface RequestsDiscordStore {incoming_channel_id: stringname: stringdiff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vueindex c6ef9474..56178d9e 100644--- a/web/pages/settings/index.vue+++ b/web/pages/settings/index.vue@@ -50,6 +50,7 @@@change="updateTimezone"></v-autocomplete></div>+<h5 class="text-h4 mb-3 mt-3">API Key</h5><p class="text--secondary">Use your API Key in the <code>x-api-key</code> HTTP Header when@@ -256,6 +257,7 @@>Documentation</v-btn></div>+<h5 id="discord-settings" class="text-h4 mb-3 mt-12">Discord Integration</h5>@@ -322,6 +324,7 @@></v-img>Add Discord</v-btn>+<h5 id="phones" class="text-h4 mb-3 mt-12">Phones</h5><p class="text--secondary">List of mobile phones which are registered for sending and@@ -382,6 +385,7 @@</tbody></template></v-simple-table>+<h5 id="email-notifications" class="text-h4 mb-3 mt-12">Email Notifications</h5>@@ -427,7 +431,11 @@<v-icon left>{{ mdiContentSave }}</v-icon>Save Notification Settings</v-btn>- <h5 id="email-notifications" class="text-h4 error--text mb-3 mt-12">++ <h5+ id="email-notifications"+ class="text-h4 error--text mb-3 mt-12"+ >Delete Account</h5><p v-if="hasActiveSubscription" class="text--secondary">@@ -497,6 +505,7 @@</v-row></v-container></div>+<v-dialog v-model="showPhoneEdit" overlay-opacity="0.9" max-width="700px"><v-card><v-card-title>Edit Phone</v-card-title>@@ -605,7 +614,12 @@</v-card-actions></v-card></v-dialog>- <v-dialog v-model="showWebhookEdit" overlay-opacity="0.9" max-width="600px">++ <v-dialog+ v-model="showWebhookEdit"+ overlay-opacity="0.9"+ max-width="600px"+ ><v-card><v-card-title><span v-if="!activeWebhook.id">Add a new </span>@@ -720,7 +734,12 @@</v-card-actions></v-card></v-dialog>- <v-dialog v-model="showDiscordEdit" overlay-opacity="0.9" max-width="700px">++ <v-dialog+ v-model="showDiscordEdit"+ overlay-opacity="0.9"+ max-width="700px"+ ><v-card><v-card-title><span v-if="!activeDiscord.id">Add a new </span>@@ -853,7 +872,7 @@ import {mdiSquareEditOutline,mdiQrcode,} from '@mdi/js'-import axios from '~/plugins/axios'+import { EntitiesSendSchedule } from '~/models/api'import { toCanvas } from 'qrcode'import { ErrorMessages } from '~/plugins/errors'import LoadingButton from '~/components/LoadingButton.vue'@@ -1263,13 +1282,15 @@ export default Vue.extend({})},- async loadSendSchedules() {- try {- const response = await axios.get('/v1/send-schedules')- this.sendSchedules = response.data?.data || []- } catch (error) {- this.sendSchedules = []- }+ loadSendSchedules() {+ this.$store+ .dispatch('getSendSchedules')+ .then((sendSchedules) => {+ this.sendSchedules = sendSchedules+ })+ .catch(() => {+ this.sendSchedules = []+ })},loadWebhooks() {diff --git a/web/pages/settings/send-schedules/index.vue b/web/pages/settings/send-schedules/index.vueindex 05d098c1..d271f7a2 100644--- a/web/pages/settings/send-schedules/index.vue+++ b/web/pages/settings/send-schedules/index.vue@@ -1,5 +1,9 @@<template>- <v-container fluid class="px-0 pt-0" :fill-height="$vuetify.breakpoint.lgAndUp">+ <v-container+ fluid+ class="px-0 pt-0"+ :fill-height="$vuetify.breakpoint.lgAndUp"+ ><div class="w-full h-full"><v-app-bar height="60" fixed :dense="$vuetify.breakpoint.mdAndDown"><v-btn icon to="/settings">@@ -9,120 +13,284 @@<div class="py-16">Send Schedules</div></v-toolbar-title></v-app-bar>+<v-container class="mt-16"><v-row><v-col cols="12" md="9" offset-md="1" xl="8" offset-xl="2">- <p class="text--secondary">- Create reusable availability schedules and attach them to phones- from the Settings page. Outgoing messages respect both the phone- send rate and the selected schedule.+ <p class="text--secondary mb-4">+ Send schedules allow you to set custom time intervals when+ outgoing messages will be sent. You can create one schedule and+ attach it to multiple phone numbers from the Settings page.</p>- <div class="d-flex mb-4">- <v-btn color="primary" @click="openCreateDialog">+ <div class="d-flex flex-wrap mb-6">+ <v-btn color="primary" @click="openCreateForm"><v-icon left>{{ mdiPlus }}</v-icon>- Add Schedule+ Add Send Schedule</v-btn></div>- <div v-if="loading" class="mb-4">- <v-progress-circular :size="60" :width="2" color="primary" indeterminate></v-progress-circular>+ <div v-if="loading" class="mb-6">+ <v-progress-circular+ :size="60"+ :width="2"+ color="primary"+ indeterminate+ /></div>- <v-row v-else-if="schedules.length">- <v-col v-for="schedule in schedules" :key="schedule.id" cols="12" md="6">- <v-card outlined>- <v-card-title class="d-flex align-center">- <span class="text-h6">{{ schedule.name }}</span>- <v-spacer></v-spacer>- <v-chip small :color="schedule.is_active ? 'success' : 'grey'" text-color="white">- {{ schedule.is_active ? 'Active' : 'Inactive' }}- </v-chip>- </v-card-title>- <v-card-subtitle>{{ schedule.timezone }}</v-card-subtitle>- <v-card-text>- <div v-for="line in scheduleSummary(schedule)" :key="line">{{ line }}</div>+ <template v-else>+ <v-row v-if="schedules.length" class="mb-6">+ <v-col+ v-for="schedule in schedules"+ :key="schedule.id"+ cols="12"+ md="6"+ >+ <v-card outlined class="h-full">+ <v-card-title class="d-flex align-center">+ <span class="text-h6 text-break">{{ schedule.name }}</span>+ <v-spacer />+ <v-chip+ small+ :color="isScheduleActive(schedule) ? 'success' : 'grey'"+ text-color="white"+ >+ {{ isScheduleActive(schedule) ? 'Active' : 'Inactive' }}+ </v-chip>+ </v-card-title>++ <v-card-subtitle>{{ schedule.timezone }}</v-card-subtitle>++ <v-card-text>+ <div+ v-for="line in scheduleSummary(schedule)"+ :key="`${schedule.id}-${line}`"+ class="mb-1"+ >+ {{ line }}+ </div>+ </v-card-text>++ <v-card-actions>+ <v-btn+ small+ color="primary"+ @click="openEditForm(schedule)"+ >+ <v-icon left>{{ mdiSquareEditOutline }}</v-icon>+ Edit+ </v-btn>++ <v-spacer />++ <v-btn+ small+ text+ color="error"+ @click="confirmDelete(schedule)"+ >+ <v-icon left>{{ mdiDelete }}</v-icon>+ Delete+ </v-btn>+ </v-card-actions>+ </v-card>+ </v-col>+ </v-row>++ <v-alert v-else outlined type="info" class="mb-6">+ No schedules yet. Create your first send schedule.+ </v-alert>+ </template>++ <v-card outlined>+ <v-card-title class="d-flex align-center">+ <span>{{+ activeSchedule.id ? 'Edit Send Schedule' : 'Add Send Schedule'+ }}</span>+ <v-spacer />+ <v-btn+ v-if="hasEditorChanges"+ text+ color="secondary"+ @click="resetEditor"+ >+ Cancel+ </v-btn>+ </v-card-title>++ <v-card-text>+ <v-row>+ <v-col cols="12" md="6">+ <v-text-field+ v-model="activeSchedule.name"+ outlined+ dense+ label="Schedule name"+ placeholder="Business Hours"+ :error="errorMessages.has('name')"+ :error-messages="errorMessages.get('name')"+ />+ </v-col>++ <v-col cols="12" md="6">+ <v-autocomplete+ v-model="activeSchedule.timezone"+ dense+ outlined+ :items="timezones"+ label="Timezone"+ :error="errorMessages.has('timezone')"+ :error-messages="errorMessages.get('timezone')"+ />+ </v-col>++ <v-col cols="12">+ <v-switch+ v-model="activeSchedule.is_active"+ inset+ label="Active"+ class="mt-0"+ />+ </v-col>+ </v-row>++ <v-alert+ v-if="errorMessages.has('windows')"+ dense+ outlined+ type="error"+ class="mb-4"+ >+ <div+ v-for="message in errorMessages.get('windows')"+ :key="message"+ >+ {{ message }}+ </div>+ </v-alert>++ <v-card+ v-for="day in weekDays"+ :key="day.value"+ outlined+ class="mb-4"+ >+ <v-card-text class="pb-2">+ <div class="d-flex align-center flex-wrap mb-3">+ <div+ class="font-weight-medium mr-4"+ style="min-width: 110px"+ >+ {{ day.label }}+ </div>++ <v-switch+ :input-value="dayEnabled(day.value)"+ inset+ dense+ hide-details+ class="mt-0 pt-0"+ @change="toggleDay(day.value, $event)"+ />++ <v-spacer />++ <v-btn+ small+ text+ color="primary"+ :disabled="!dayEnabled(day.value)"+ @click="addWindow(day.value)"+ >+ <v-icon left small>{{ mdiPlus }}</v-icon>+ Add window+ </v-btn>+ </div>++ <div+ v-if="windowsForDay(day.value).length === 0"+ class="text--secondary"+ >+ Unavailable+ </div>++ <div+ v-for="(window, index) in windowsForDay(day.value)"+ :key="`${day.value}-${index}`"+ class="d-flex align-center flex-wrap schedule-window-row"+ >+ <div class="schedule-time-field mr-2 mb-2">+ <v-text-field+ v-model="window.start_time"+ dense+ outlined+ type="time"+ label="Start"+ hide-details="auto"+ />+ </div>++ <div class="schedule-separator mb-2 mr-2">–</div>++ <div class="schedule-time-field mr-2 mb-2">+ <v-text-field+ v-model="window.end_time"+ dense+ outlined+ type="time"+ label="End"+ hide-details="auto"+ />+ </div>++ <div class="mb-2">+ <v-btn+ icon+ color="error"+ @click="removeWindow(day.value, index)"+ >+ <v-icon>{{ mdiDelete }}</v-icon>+ </v-btn>+ </div>+ </div></v-card-text>- <v-card-actions>- <v-btn small color="primary" @click="openEditDialog(schedule)">- <v-icon left>{{ mdiSquareEditOutline }}</v-icon>- Edit- </v-btn>- <v-spacer></v-spacer>- <v-btn small text color="error" @click="confirmDelete(schedule)">- <v-icon left>{{ mdiDelete }}</v-icon>- Delete- </v-btn>- </v-card-actions></v-card>- </v-col>- </v-row>+ </v-card-text>- <v-alert v-else outlined type="info">- No schedules yet. Create your first availability schedule.- </v-alert>+ <v-card-actions>+ <v-btn+ color="primary"+ :loading="saving"+ @click="saveSchedule"+ >+ <v-icon left>{{ mdiContentSave }}</v-icon>+ Save+ </v-btn>++ <v-spacer />++ <v-btn text @click="resetEditor">Reset</v-btn>+ </v-card-actions>+ </v-card></v-col></v-row></v-container></div>- <v-dialog v-model="showDialog" :fullscreen="$vuetify.breakpoint.smAndDown" max-width="900">- <v-card>- <v-card-title>{{ activeSchedule.id ? 'Edit Schedule' : 'Add Schedule' }}</v-card-title>- <v-card-text>- <v-row>- <v-col cols="12" md="6">- <v-text-field v-model="activeSchedule.name" outlined dense label="Schedule name"></v-text-field>- </v-col>- <v-col cols="12" md="6">- <v-autocomplete v-model="activeSchedule.timezone" dense outlined :items="timezones" label="Timezone"></v-autocomplete>- </v-col>- <v-col cols="12" md="3">- <v-switch v-model="activeSchedule.is_active" inset label="Active"></v-switch>- </v-col>- </v-row>-- <div v-for="day in weekDays" :key="day.value" class="mb-4 pa-3 rounded schedule-day">- <div class="d-flex align-center mb-2">- <div class="font-weight-medium">{{ day.label }}</div>- <v-spacer></v-spacer>- <v-btn small text color="primary" @click="addWindow(day.value)">Add window</v-btn>- </div>- <div v-if="windowsForDay(day.value).length === 0" class="text--secondary">Unavailable</div>- <v-row v-for="(window, index) in windowsForDay(day.value)" :key="`${day.value}-${index}`">- <v-col cols="5" sm="4">- <v-text-field v-model="window.start_time" dense outlined type="time" label="Start"></v-text-field>- </v-col>- <v-col cols="5" sm="4">- <v-text-field v-model="window.end_time" dense outlined type="time" label="End"></v-text-field>- </v-col>- <v-col cols="2" sm="4" class="d-flex align-center">- <v-btn icon color="error" @click="removeWindow(day.value, index)">- <v-icon>{{ mdiDelete }}</v-icon>- </v-btn>- </v-col>- </v-row>- </div>- </v-card-text>- <v-card-actions>- <v-btn color="primary" :loading="saving" @click="saveSchedule">Save</v-btn>- <v-spacer></v-spacer>- <v-btn text @click="showDialog = false">Close</v-btn>- </v-card-actions>- </v-card>- </v-dialog>-<v-dialog v-model="showDeleteDialog" max-width="500"><v-card><v-card-title>Delete schedule</v-card-title><v-card-text>- Are you sure you want to delete <b>{{ activeSchedule.name }}</b>?+ Are you sure you want to delete <b>{{ scheduleToDelete?.name }}</b>?Phones attached to this schedule will no longer have schedule-basedrestrictions.</v-card-text><v-card-actions>- <v-btn color="error" :loading="saving" @click="deleteSchedule">Delete</v-btn>- <v-spacer></v-spacer>+ <v-btn color="error" :loading="saving" @click="deleteSchedule">+ Delete+ </v-btn>+ <v-spacer /><v-btn text @click="showDeleteDialog = false">Cancel</v-btn></v-card-actions></v-card>@@ -132,8 +300,14 @@<script>import Vue from 'vue'-import { mdiArrowLeft, mdiDelete, mdiPlus, mdiSquareEditOutline } from '@mdi/js'-import axios from '~/plugins/axios'+import {+ mdiArrowLeft,+ mdiContentSave,+ mdiDelete,+ mdiPlus,+ mdiSquareEditOutline,+} from '@mdi/js'+import { ErrorMessages } from '~/plugins/errors'export default Vue.extend({name: 'SendSchedulesPage',@@ -141,18 +315,19 @@ export default Vue.extend({data() {return {mdiArrowLeft,+ mdiContentSave,mdiDelete,mdiPlus,mdiSquareEditOutline,loading: false,saving: false,- showDialog: false,showDeleteDialog: false,schedules: [],+ scheduleToDelete: null,activeSchedule: {id: null,- name: 'Business Hours',- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ name: '',+ timezone: '',is_active: true,windows: [],},@@ -165,140 +340,294 @@ export default Vue.extend({{ value: 6, label: 'Saturday' },{ value: 0, label: 'Sunday' },],+ errorMessages: new ErrorMessages(),}},head() {- return { title: 'Send Schedules - httpSMS' }+ return {+ title: 'Send Schedules - httpSMS',+ }},computed: {timezones() {- return Intl.supportedValuesOf('timeZone')+ try {+ return Intl.supportedValuesOf('timeZone')+ } catch {+ return []+ }+ },+ hasEditorChanges() {+ return (+ this.activeSchedule.id !== null ||+ this.activeSchedule.name !== '' ||+ this.activeSchedule.windows.length > 0 ||+ this.activeSchedule.is_active !== true ||+ this.activeSchedule.timezone !== this.defaultTimezone()+ )},},async mounted() {+ this.resetEditor()await this.loadSchedules()},methods: {+ resetErrors() {+ this.errorMessages = new ErrorMessages()+ },++ defaultTimezone() {+ return (+ this.$store.getters.getUser?.timezone ||+ Intl.DateTimeFormat().resolvedOptions().timeZone+ )+ },++ resetEditor() {+ this.resetErrors()+ this.activeSchedule = {+ id: null,+ name: '',+ timezone: this.defaultTimezone(),+ is_active: true,+ windows: [],+ }+ },+minuteToClock(value) {const hours = String(Math.floor(value / 60)).padStart(2, '0')const minutes = String(value % 60).padStart(2, '0')return `${hours}:${minutes}`},+clockToMinute(value) {+ if (!value || !value.includes(':')) {+ return 0+ }+const [hours, minutes] = value.split(':').map((x) => parseInt(x, 10))return hours * 60 + minutes},++ isScheduleActive(schedule) {+ if (typeof schedule.is_active !== 'undefined') {+ return schedule.is_active+ }+ return Boolean(schedule.active)+ },+windowsForDay(dayOfWeek) {- return this.activeSchedule.windows.filter((x) => x.day_of_week === dayOfWeek)+ return this.activeSchedule.windows.filter(+ (x) => x.day_of_week === dayOfWeek,+ )},++ dayEnabled(dayOfWeek) {+ return this.windowsForDay(dayOfWeek).length > 0+ },++ toggleDay(dayOfWeek, enabled) {+ if (enabled) {+ if (!this.dayEnabled(dayOfWeek)) {+ this.addWindow(dayOfWeek)+ }+ return+ }++ this.activeSchedule.windows = this.activeSchedule.windows.filter(+ (x) => x.day_of_week !== dayOfWeek,+ )+ },+addWindow(dayOfWeek) {- this.activeSchedule.windows.push({ day_of_week: dayOfWeek, start_time: '09:00', end_time: '17:00' })+ this.activeSchedule.windows.push({+ day_of_week: dayOfWeek,+ start_time: '09:00',+ end_time: '17:00',+ })},+removeWindow(dayOfWeek, index) {- const matches = this.activeSchedule.windows.filter((x) => x.day_of_week === dayOfWeek)+ const matches = this.activeSchedule.windows.filter(+ (x) => x.day_of_week === dayOfWeek,+ )const target = matches[index]- this.activeSchedule.windows = this.activeSchedule.windows.filter((x) => x !== target)+ this.activeSchedule.windows = this.activeSchedule.windows.filter(+ (x) => x !== target,+ )},+scheduleSummary(schedule) {return this.weekDays.map((day) => {- const windows = (schedule.windows || []).filter((x) => x.day_of_week === day.value)- if (windows.length === 0) return `${day.label}: Unavailable`- return `${day.label}: ${windows.map((w) => `${this.minuteToClock(w.start_minute)}-${this.minuteToClock(w.end_minute)}`).join(', ')}`+ const windows = (schedule.windows || []).filter(+ (x) => x.day_of_week === day.value,+ )++ if (windows.length === 0) {+ return `${day.label}: Unavailable`+ }++ return `${day.label}: ${windows+ .map(+ (w) =>+ `${this.minuteToClock(w.start_minute)}-${this.minuteToClock(+ w.end_minute,+ )}`,+ )+ .join(', ')}`})},- openCreateDialog() {- this.activeSchedule = {- id: null,- name: 'Business Hours',- timezone: this.$store.getters.getUser?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,- is_active: true,- windows: [- { day_of_week: 1, start_time: '09:00', end_time: '17:00' },- { day_of_week: 2, start_time: '09:00', end_time: '17:00' },- { day_of_week: 3, start_time: '09:00', end_time: '17:00' },- { day_of_week: 4, start_time: '09:00', end_time: '17:00' },- { day_of_week: 5, start_time: '09:00', end_time: '17:00' },- ],- }- this.showDialog = true++ openCreateForm() {+ this.resetEditor()+ this.activeSchedule.windows = [+ { day_of_week: 1, start_time: '09:00', end_time: '17:00' },+ { day_of_week: 2, start_time: '09:00', end_time: '17:00' },+ { day_of_week: 3, start_time: '09:00', end_time: '17:00' },+ { day_of_week: 4, start_time: '09:00', end_time: '17:00' },+ { day_of_week: 5, start_time: '09:00', end_time: '17:00' },+ ]+ this.$vuetify.goTo(0)},- openEditDialog(schedule) {++ openEditForm(schedule) {+ this.resetErrors()this.activeSchedule = {id: schedule.id,name: schedule.name,timezone: schedule.timezone,- is_active: schedule.is_active,- windows: (schedule.windows || []).map((x) => ({ day_of_week: x.day_of_week, start_time: this.minuteToClock(x.start_minute), end_time: this.minuteToClock(x.end_minute) })),+ is_active: this.isScheduleActive(schedule),+ windows: (schedule.windows || []).map((x) => ({+ day_of_week: x.day_of_week,+ start_time: this.minuteToClock(x.start_minute),+ end_time: this.minuteToClock(x.end_minute),+ })),}- this.showDialog = true++ this.$vuetify.goTo(0)},+confirmDelete(schedule) {- this.activeSchedule = { ...schedule }+ this.scheduleToDelete = schedulethis.showDeleteDialog = true},+async loadSchedules() {this.loading = truetry {- const response = await axios.get('/v1/send-schedules')- this.schedules = response.data?.data || []- } catch (error) {+ this.schedules = await this.$store.dispatch('getSendSchedules')+ } catch (errors) {this.$store.dispatch('addNotification', {type: 'error',message: 'Failed to load send schedules',})+ this.schedules = []} finally {this.loading = false}},++ buildPayload() {+ return {+ name: this.activeSchedule.name,+ timezone: this.activeSchedule.timezone,+ is_active: this.activeSchedule.is_active,+ windows: (this.activeSchedule.windows || []).map((window) => ({+ day_of_week: window.day_of_week,+ start_minute: this.clockToMinute(window.start_time),+ end_minute: this.clockToMinute(window.end_time),+ })),+ }+ },+async saveSchedule() {+ this.resetErrors()this.saving = true+try {- const payload = {- name: this.activeSchedule.name,- timezone: this.activeSchedule.timezone,- is_active: this.activeSchedule.is_active,- windows: (this.activeSchedule.windows || []).map((window) => ({- day_of_week: window.day_of_week,- start_minute: this.clockToMinute(window.start_time),- end_minute: this.clockToMinute(window.end_time),- })),- }+ const payload = this.buildPayload()+if (this.activeSchedule.id) {- await axios.put(`/v1/send-schedules/${this.activeSchedule.id}`, payload)+ await this.$store.dispatch('updateSendSchedule', {+ id: this.activeSchedule.id,+ ...payload,+ })} else {- await axios.post('/v1/send-schedules', payload)+ await this.$store.dispatch('createSendSchedule', payload)}- this.$store.dispatch('addNotification', { type: 'success', message: 'Send schedule saved successfully' })- this.showDialog = false- await this.loadSchedules()- } catch (error) {+this.$store.dispatch('addNotification', {- type: 'error',- message: error?.response?.data?.message || 'Failed to save send schedule',+ type: 'success',+ message: 'Send schedule saved successfully',})- } finally {- this.saving = false- }- },- async deleteSchedule() {- this.saving = true- try {- await axios.delete(`/v1/send-schedules/${this.activeSchedule.id}`)- this.$store.dispatch('addNotification', { type: 'success', message: 'Send schedule deleted successfully' })- this.showDeleteDialog = false+await this.loadSchedules()- } catch (error) {- this.$store.dispatch('addNotification', { type: 'error', message: 'Failed to delete send schedule' })+ this.resetEditor()+ } catch (errors) {+ this.errorMessages = errors} finally {this.saving = false}},- },++async deleteSchedule() {+ if (!this.scheduleToDelete?.id) {+ return+ }++ const deletedScheduleId = this.scheduleToDelete.id+ this.saving = true++ try {+ await this.$store.dispatch('deleteSendSchedule', deletedScheduleId)++ this.$store.dispatch('addNotification', {+ type: 'success',+ message: 'Send schedule deleted successfully',+ })++ this.showDeleteDialog = false+ this.scheduleToDelete = null++ await this.loadSchedules()++ if (this.activeSchedule.id === deletedScheduleId) {+ this.resetEditor()+ }+ } catch (error) {+ this.$store.dispatch('addNotification', {+ type: 'error',+ message: 'Failed to delete send schedule',+ })+ } finally {+ this.saving = false+ }+},+},})</script><style scoped>-.schedule-day {- border: 1px solid rgba(0, 0, 0, 0.12);+.schedule-window-row {+ gap: 0;+}++.schedule-time-field {+ width: 170px;+ max-width: 100%;+}++.schedule-separator {+ font-size: 18px;+ line-height: 40px;+}++@media (max-width: 600px) {+ .schedule-time-field {+ width: 100%;+ }++ .schedule-separator {+ display: none;+ }}</style>diff --git a/web/store/index.ts b/web/store/index.tsindex 3ced97f0..9e52a240 100644--- a/web/store/index.ts+++ b/web/store/index.ts@@ -11,10 +11,12 @@ import {EntitiesMessage,EntitiesPhone,EntitiesPhoneAPIKey,+ EntitiesSendSchedule,EntitiesUser,EntitiesWebhook,RequestsDiscordStore,RequestsDiscordUpdate,+ RequestsSendScheduleStore,RequestsUserNotificationUpdate,RequestsUserPaymentInvoice,RequestsWebhookStore,@@ -26,6 +28,8 @@ import {ResponsesOkString,ResponsesPhoneAPIKeyResponse,ResponsesPhoneAPIKeysResponse,+ ResponsesSendScheduleResponse,+ ResponsesSendSchedulesResponse,ResponsesUnprocessableEntity,ResponsesUserResponse,ResponsesUserSubscriptionPaymentsResponse,@@ -366,8 +370,8 @@ export const actions = {context: ActionContext<State, State>,phone: EntitiesPhone,) {- await axios- .put(`/v1/phones`, {+ try {+ const response = await axios.put(`/v1/phones`, {fcm_token: phone.fcm_token,sim: phone.sim,phone_number: phone.phone_number,@@ -377,19 +381,18 @@ export const actions = {missed_call_auto_reply: phone.missed_call_auto_reply,max_send_attempts: parseInt(phone.max_send_attempts.toString()),messages_per_minute: parseInt(phone.messages_per_minute.toString()),- schedule_id: (phone as any).schedule_id || null,- })- .catch((error: AxiosError) => {- context.dispatch('handleAxiosError', error)+ schedule_id: phone.schedule_id ?? null,})- .then((response: any) => {- context.dispatch('addNotification', {- message: response.data.message,- type: 'success',- })++ context.dispatch('addNotification', {+ message: response.data.message,+ type: 'success',})- await context.dispatch('loadPhones', true)+ await context.dispatch('loadPhones', true)+ } catch (error) {+ await context.dispatch('handleAxiosError', error as AxiosError)+ }},sendBulkMessages(context: ActionContext<State, State>, document: File) {@@ -1105,6 +1108,106 @@ export const actions = {})},+ getSendSchedules(context: ActionContext<State, State>) {+ return new Promise<Array<EntitiesSendSchedule>>((resolve, reject) => {+ axios+ .get<ResponsesSendSchedulesResponse>(`/v1/send-schedules`, {+ params: {+ limit: 100,+ },+ })+ .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',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },++ createSendSchedule(+ context: ActionContext<State, State>,+ payload: RequestsSendScheduleStore,+ ) {+ return new Promise<EntitiesSendSchedule>((resolve, reject) => {+ axios+ .post<ResponsesSendScheduleResponse>(`/v1/send-schedules`, payload)+ .then((response: AxiosResponse<ResponsesSendScheduleResponse>) => {+ 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',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },++ updateSendSchedule(+ context: ActionContext<State, State>,+ payload: RequestsSendScheduleStore & { id: string },+ ) {+ return new Promise<EntitiesSendSchedule>((resolve, reject) => {+ axios+ .put<ResponsesSendScheduleResponse>(+ `/v1/send-schedules/${payload.id}`,+ payload,+ )+ .then((response: AxiosResponse<ResponsesSendScheduleResponse>) => {+ 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',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },++ deleteSendSchedule(+ context: ActionContext<State, State>,+ payload: string,+ ) {+ return new Promise<void>((resolve, reject) => {+ axios+ .delete<ResponsesNoContent>(`/v1/send-schedules/${payload}`)+ .then(() => {+ 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',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },+createWebhook(context: ActionContext<State, State>,payload: RequestsWebhookStore,