Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
fix: handle review feedback
giresse1979c2d0c1a367
diff --git a/api/docs/docs.go b/api/docs/docs.goindex 9b3adba6..b1ab5f07 100644--- a/api/docs/docs.go+++ b/api/docs/docs.go@@ -2186,7 +2186,7 @@ const docTemplate = `{"ApiKeyAuth": []}],- "description": "Lists the send schedules owned by the authenticated user.",+ "description": "List all send schedules owned by the authenticated user.","produces": ["application/json"],@@ -2198,7 +2198,10 @@ const docTemplate = `{"200": {"description": "OK","schema": {- "$ref": "#/definitions/responses.SendSchedulesResponse"+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.MessageSendSchedule"+ }}},"401": {@@ -2221,7 +2224,7 @@ const docTemplate = `{"ApiKeyAuth": []}],- "description": "Creates a send schedule for the authenticated user.",+ "description": "Create a new send schedule for the authenticated user.","consumes": ["application/json"],@@ -2278,63 +2281,13 @@ const docTemplate = `{}},"/send-schedules/{scheduleID}": {- "get": {- "security": [- {- "ApiKeyAuth": []- }- ],- "description": "Loads a single send schedule owned by the authenticated user.",- "produces": [- "application/json"- ],- "tags": [- "Send Schedules"- ],- "summary": "Show send schedule",- "parameters": [- {- "type": "string",- "description": "Schedule ID",- "name": "scheduleID",- "in": "path",- "required": true- }- ],- "responses": {- "200": {- "description": "OK",- "schema": {- "$ref": "#/definitions/responses.SendScheduleResponse"- }- },- "401": {- "description": "Unauthorized",- "schema": {- "$ref": "#/definitions/responses.Unauthorized"- }- },- "404": {- "description": "Not Found",- "schema": {- "$ref": "#/definitions/responses.NotFound"- }- },- "500": {- "description": "Internal Server Error",- "schema": {- "$ref": "#/definitions/responses.InternalServerError"- }- }- }- },"put": {"security": [{"ApiKeyAuth": []}],- "description": "Updates a send schedule owned by the authenticated user.",+ "description": "Update a send schedule owned by the authenticated user.","consumes": ["application/json"],@@ -2408,7 +2361,7 @@ const docTemplate = `{"ApiKeyAuth": []}],- "description": "Deletes a send schedule owned by the authenticated user.",+ "description": "Delete a send schedule owned by the authenticated user.","produces": ["application/json"],@@ -2427,10 +2380,7 @@ const docTemplate = `{],"responses": {"204": {- "description": "No Content",- "schema": {- "$ref": "#/definitions/responses.NoContent"- }+ "description": "No Content"},"400": {"description": "Bad Request",@@ -2444,6 +2394,12 @@ const docTemplate = `{"$ref": "#/definitions/responses.Unauthorized"}},+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },"500": {"description": "Internal Server Error","schema": {@@ -2729,6 +2685,13 @@ const docTemplate = `{"schema": {"$ref": "#/definitions/requests.UserPaymentInvoice"}+ },+ {+ "type": "string",+ "description": "ID of the subscription invoice to generate the PDF for",+ "name": "subscriptionInvoiceID",+ "in": "path",+ "required": true}],"responses": {@@ -3353,6 +3316,7 @@ const docTemplate = `{"entities.Message": {"type": "object","required": [+ "attachments","contact","content","created_at",@@ -3370,6 +3334,12 @@ const docTemplate = `{"user_id"],"properties": {+ "attachments": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },"contact": {"type": "string","example": "+18005550100"@@ -3482,6 +3452,77 @@ const docTemplate = `{}}},+ "entities.MessageSendSchedule": {+ "type": "object",+ "required": [+ "created_at",+ "id",+ "is_active",+ "name",+ "timezone",+ "updated_at",+ "user_id",+ "windows"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "id": {+ "type": "string",+ "example": "32343a19-da5e-4b1b-a767-3298a73703cb"+ },+ "is_active": {+ "type": "boolean",+ "example": true+ },+ "name": {+ "type": "string",+ "example": "Business Hours"+ },+ "timezone": {+ "type": "string",+ "example": "Europe/Tallinn"+ },+ "updated_at": {+ "type": "string",+ "example": "2022-06-05T14:26:10.303278+03:00"+ },+ "user_id": {+ "type": "string",+ "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"+ },+ "windows": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.MessageSendScheduleWindow"+ }+ }+ }+ },+ "entities.MessageSendScheduleWindow": {+ "type": "object",+ "required": [+ "day_of_week",+ "end_minute",+ "start_minute"+ ],+ "properties": {+ "day_of_week": {+ "type": "integer",+ "example": 1+ },+ "end_minute": {+ "type": "integer",+ "example": 1020+ },+ "start_minute": {+ "type": "integer",+ "example": 540+ }+ }+ },"entities.MessageThread": {"type": "object","required": [@@ -3689,77 +3730,6 @@ const docTemplate = `{"SIM2"]},- "entities.SendSchedule": {- "type": "object",- "required": [- "created_at",- "id",- "is_active",- "name",- "timezone",- "updated_at",- "user_id",- "windows"- ],- "properties": {- "created_at": {- "type": "string",- "example": "2022-06-05T14:26:02.302718+03:00"- },- "id": {- "type": "string",- "example": "32343a19-da5e-4b1b-a767-3298a73703cb"- },- "is_active": {- "type": "boolean",- "example": true- },- "name": {- "type": "string",- "example": "Business Hours"- },- "timezone": {- "type": "string",- "example": "Europe/Tallinn"- },- "updated_at": {- "type": "string",- "example": "2022-06-05T14:26:10.303278+03:00"- },- "user_id": {- "type": "string",- "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"- },- "windows": {- "type": "array",- "items": {- "$ref": "#/definitions/entities.SendScheduleWindow"- }- }- }- },- "entities.SendScheduleWindow": {- "type": "object",- "required": [- "day_of_week",- "end_minute",- "start_minute"- ],- "properties": {- "day_of_week": {- "type": "integer",- "example": 1- },- "end_minute": {- "type": "integer",- "example": 1020- },- "start_minute": {- "type": "integer",- "example": 540- }- }- },"entities.SubscriptionName": {"type": "string","enum": [@@ -3994,11 +3964,17 @@ const docTemplate = `{"type": "object","required": ["content",- "encrypted","from","to"],"properties": {+ "attachments": {+ "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS",+ "type": "array",+ "items": {+ "type": "string"+ }+ },"content": {"type": "string","example": "This is a sample text message"@@ -4132,6 +4108,13 @@ const docTemplate = `{"to"],"properties": {+ "attachments": {+ "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS",+ "type": "array",+ "items": {+ "type": "string"+ }+ },"content": {"type": "string","example": "This is a sample text message"@@ -4852,31 +4835,7 @@ const docTemplate = `{],"properties": {"data": {- "$ref": "#/definitions/entities.SendSchedule"- },- "message": {- "type": "string",- "example": "Request handled successfully"- },- "status": {- "type": "string",- "example": "success"- }- }- },- "responses.SendSchedulesResponse": {- "type": "object",- "required": [- "data",- "message",- "status"- ],- "properties": {- "data": {- "type": "array",- "items": {- "$ref": "#/definitions/entities.SendSchedule"- }+ "$ref": "#/definitions/entities.MessageSendSchedule"},"message": {"type": "string",diff --git a/api/docs/swagger.json b/api/docs/swagger.jsonindex 430e52b1..99f54ac5 100644--- a/api/docs/swagger.json+++ b/api/docs/swagger.json@@ -2183,7 +2183,7 @@"ApiKeyAuth": []}],- "description": "Lists the send schedules owned by the authenticated user.",+ "description": "List all send schedules owned by the authenticated user.","produces": ["application/json"],@@ -2195,7 +2195,10 @@"200": {"description": "OK","schema": {- "$ref": "#/definitions/responses.SendSchedulesResponse"+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.MessageSendSchedule"+ }}},"401": {@@ -2218,7 +2221,7 @@"ApiKeyAuth": []}],- "description": "Creates a send schedule for the authenticated user.",+ "description": "Create a new send schedule for the authenticated user.","consumes": ["application/json"],@@ -2275,63 +2278,13 @@}},"/send-schedules/{scheduleID}": {- "get": {- "security": [- {- "ApiKeyAuth": []- }- ],- "description": "Loads a single send schedule owned by the authenticated user.",- "produces": [- "application/json"- ],- "tags": [- "Send Schedules"- ],- "summary": "Show send schedule",- "parameters": [- {- "type": "string",- "description": "Schedule ID",- "name": "scheduleID",- "in": "path",- "required": true- }- ],- "responses": {- "200": {- "description": "OK",- "schema": {- "$ref": "#/definitions/responses.SendScheduleResponse"- }- },- "401": {- "description": "Unauthorized",- "schema": {- "$ref": "#/definitions/responses.Unauthorized"- }- },- "404": {- "description": "Not Found",- "schema": {- "$ref": "#/definitions/responses.NotFound"- }- },- "500": {- "description": "Internal Server Error",- "schema": {- "$ref": "#/definitions/responses.InternalServerError"- }- }- }- },"put": {"security": [{"ApiKeyAuth": []}],- "description": "Updates a send schedule owned by the authenticated user.",+ "description": "Update a send schedule owned by the authenticated user.","consumes": ["application/json"],@@ -2405,7 +2358,7 @@"ApiKeyAuth": []}],- "description": "Deletes a send schedule owned by the authenticated user.",+ "description": "Delete a send schedule owned by the authenticated user.","produces": ["application/json"],@@ -2424,10 +2377,7 @@],"responses": {"204": {- "description": "No Content",- "schema": {- "$ref": "#/definitions/responses.NoContent"- }+ "description": "No Content"},"400": {"description": "Bad Request",@@ -2441,6 +2391,12 @@"$ref": "#/definitions/responses.Unauthorized"}},+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },"500": {"description": "Internal Server Error","schema": {@@ -2726,6 +2682,13 @@"schema": {"$ref": "#/definitions/requests.UserPaymentInvoice"}+ },+ {+ "type": "string",+ "description": "ID of the subscription invoice to generate the PDF for",+ "name": "subscriptionInvoiceID",+ "in": "path",+ "required": true}],"responses": {@@ -3350,6 +3313,7 @@"entities.Message": {"type": "object","required": [+ "attachments","contact","content","created_at",@@ -3367,6 +3331,12 @@"user_id"],"properties": {+ "attachments": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },"contact": {"type": "string","example": "+18005550100"@@ -3479,6 +3449,77 @@}}},+ "entities.MessageSendSchedule": {+ "type": "object",+ "required": [+ "created_at",+ "id",+ "is_active",+ "name",+ "timezone",+ "updated_at",+ "user_id",+ "windows"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "id": {+ "type": "string",+ "example": "32343a19-da5e-4b1b-a767-3298a73703cb"+ },+ "is_active": {+ "type": "boolean",+ "example": true+ },+ "name": {+ "type": "string",+ "example": "Business Hours"+ },+ "timezone": {+ "type": "string",+ "example": "Europe/Tallinn"+ },+ "updated_at": {+ "type": "string",+ "example": "2022-06-05T14:26:10.303278+03:00"+ },+ "user_id": {+ "type": "string",+ "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"+ },+ "windows": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.MessageSendScheduleWindow"+ }+ }+ }+ },+ "entities.MessageSendScheduleWindow": {+ "type": "object",+ "required": [+ "day_of_week",+ "end_minute",+ "start_minute"+ ],+ "properties": {+ "day_of_week": {+ "type": "integer",+ "example": 1+ },+ "end_minute": {+ "type": "integer",+ "example": 1020+ },+ "start_minute": {+ "type": "integer",+ "example": 540+ }+ }+ },"entities.MessageThread": {"type": "object","required": [@@ -3686,77 +3727,6 @@"SIM2"]},- "entities.SendSchedule": {- "type": "object",- "required": [- "created_at",- "id",- "is_active",- "name",- "timezone",- "updated_at",- "user_id",- "windows"- ],- "properties": {- "created_at": {- "type": "string",- "example": "2022-06-05T14:26:02.302718+03:00"- },- "id": {- "type": "string",- "example": "32343a19-da5e-4b1b-a767-3298a73703cb"- },- "is_active": {- "type": "boolean",- "example": true- },- "name": {- "type": "string",- "example": "Business Hours"- },- "timezone": {- "type": "string",- "example": "Europe/Tallinn"- },- "updated_at": {- "type": "string",- "example": "2022-06-05T14:26:10.303278+03:00"- },- "user_id": {- "type": "string",- "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"- },- "windows": {- "type": "array",- "items": {- "$ref": "#/definitions/entities.SendScheduleWindow"- }- }- }- },- "entities.SendScheduleWindow": {- "type": "object",- "required": [- "day_of_week",- "end_minute",- "start_minute"- ],- "properties": {- "day_of_week": {- "type": "integer",- "example": 1- },- "end_minute": {- "type": "integer",- "example": 1020- },- "start_minute": {- "type": "integer",- "example": 540- }- }- },"entities.SubscriptionName": {"type": "string","enum": [@@ -3991,11 +3961,17 @@"type": "object","required": ["content",- "encrypted","from","to"],"properties": {+ "attachments": {+ "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS",+ "type": "array",+ "items": {+ "type": "string"+ }+ },"content": {"type": "string","example": "This is a sample text message"@@ -4129,6 +4105,13 @@"to"],"properties": {+ "attachments": {+ "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS",+ "type": "array",+ "items": {+ "type": "string"+ }+ },"content": {"type": "string","example": "This is a sample text message"@@ -4849,31 +4832,7 @@],"properties": {"data": {- "$ref": "#/definitions/entities.SendSchedule"- },- "message": {- "type": "string",- "example": "Request handled successfully"- },- "status": {- "type": "string",- "example": "success"- }- }- },- "responses.SendSchedulesResponse": {- "type": "object",- "required": [- "data",- "message",- "status"- ],- "properties": {- "data": {- "type": "array",- "items": {- "$ref": "#/definitions/entities.SendSchedule"- }+ "$ref": "#/definitions/entities.MessageSendSchedule"},"message": {"type": "string",diff --git a/api/docs/swagger.yaml b/api/docs/swagger.yamlindex e4bc41b1..97907da0 100644--- a/api/docs/swagger.yaml+++ b/api/docs/swagger.yaml@@ -102,6 +102,10 @@ definitions:type: objectentities.Message:properties:+ attachments:+ items:+ type: string+ type: arraycontact:example: "+18005550100"type: string@@ -189,6 +193,7 @@ definitions:example: WB7DRDWrJZRGbYrv2CKGkqbzvqdCtype: stringrequired:+ - attachments- contact- content- created_at@@ -205,6 +210,59 @@ definitions:- updated_at- user_idtype: object+ entities.MessageSendSchedule:+ properties:+ created_at:+ example: "2022-06-05T14:26:02.302718+03:00"+ type: string+ id:+ example: 32343a19-da5e-4b1b-a767-3298a73703cb+ type: string+ is_active:+ example: true+ type: boolean+ name:+ example: Business Hours+ type: string+ timezone:+ example: Europe/Tallinn+ type: string+ updated_at:+ example: "2022-06-05T14:26:10.303278+03:00"+ type: string+ user_id:+ example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC+ type: string+ windows:+ items:+ $ref: '#/definitions/entities.MessageSendScheduleWindow'+ type: array+ required:+ - created_at+ - id+ - is_active+ - name+ - timezone+ - updated_at+ - user_id+ - windows+ type: object+ entities.MessageSendScheduleWindow:+ properties:+ day_of_week:+ example: 1+ type: integer+ end_minute:+ example: 1020+ type: integer+ start_minute:+ example: 540+ type: integer+ required:+ - day_of_week+ - end_minute+ - start_minute+ type: objectentities.MessageThread:properties:color:@@ -365,59 +423,6 @@ definitions:x-enum-varnames:- SIM1- SIM2- entities.SendSchedule:- properties:- created_at:- example: "2022-06-05T14:26:02.302718+03:00"- type: string- id:- example: 32343a19-da5e-4b1b-a767-3298a73703cb- type: string- is_active:- example: true- type: boolean- name:- example: Business Hours- type: string- timezone:- example: Europe/Tallinn- type: string- updated_at:- example: "2022-06-05T14:26:10.303278+03:00"- type: string- user_id:- example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC- type: string- windows:- items:- $ref: '#/definitions/entities.SendScheduleWindow'- type: array- required:- - created_at- - id- - is_active- - name- - timezone- - updated_at- - user_id- - windows- type: object- entities.SendScheduleWindow:- properties:- day_of_week:- example: 1- type: integer- end_minute:- example: 1020- type: integer- start_minute:- example: 540- type: integer- required:- - day_of_week- - end_minute- - start_minute- type: objectentities.SubscriptionName:enum:- free@@ -592,6 +597,12 @@ definitions:type: objectrequests.MessageBulkSend:properties:+ attachments:+ description: Attachments are optional. When you provide a list of attachments,+ the message will be sent out as an MMS+ items:+ type: string+ type: arraycontent:example: This is a sample text messagetype: string@@ -617,7 +628,6 @@ definitions:type: arrayrequired:- content- - encrypted- from- totype: object@@ -700,6 +710,12 @@ definitions:type: objectrequests.MessageSend:properties:+ attachments:+ description: Attachments are optional. When you provide a list of attachments,+ the message will be sent out as an MMS+ items:+ type: string+ type: arraycontent:example: This is a sample text messagetype: string@@ -1228,24 +1244,7 @@ definitions:responses.SendScheduleResponse:properties:data:- $ref: '#/definitions/entities.SendSchedule'- message:- example: Request handled successfully- type: string- status:- example: success- type: string- required:- - data- - message- - status- type: object- responses.SendSchedulesResponse:- properties:- data:- items:- $ref: '#/definitions/entities.SendSchedule'- type: array+ $ref: '#/definitions/entities.MessageSendSchedule'message:example: Request handled successfullytype: string@@ -2883,14 +2882,16 @@ paths:- Phones/send-schedules:get:- description: Lists the send schedules owned by the authenticated user.+ description: List all send schedules owned by the authenticated user.produces:- application/jsonresponses:"200":description: OKschema:- $ref: '#/definitions/responses.SendSchedulesResponse'+ items:+ $ref: '#/definitions/entities.MessageSendSchedule'+ type: array"401":description: Unauthorizedschema:@@ -2907,7 +2908,7 @@ paths:post:consumes:- application/json- description: Creates a send schedule for the authenticated user.+ description: Create a new send schedule for the authenticated user.parameters:- description: Payload of new send schedule.in: body@@ -2945,7 +2946,7 @@ paths:- Send Schedules/send-schedules/{scheduleID}:delete:- description: Deletes a send schedule owned by the authenticated user.+ description: Delete a send schedule owned by the authenticated user.parameters:- description: Schedule IDin: path@@ -2957,8 +2958,6 @@ paths:responses:"204":description: No Content- schema:- $ref: '#/definitions/responses.NoContent'"400":description: Bad Requestschema:@@ -2967,34 +2966,6 @@ paths:description: Unauthorizedschema:$ref: '#/definitions/responses.Unauthorized'- "500":- description: Internal Server Error- schema:- $ref: '#/definitions/responses.InternalServerError'- security:- - ApiKeyAuth: []- summary: Delete send schedule- tags:- - Send Schedules- get:- description: Loads a single send schedule owned by the authenticated user.- parameters:- - description: Schedule ID- in: path- name: scheduleID- required: true- type: string- produces:- - application/json- responses:- "200":- description: OK- schema:- $ref: '#/definitions/responses.SendScheduleResponse'- "401":- description: Unauthorized- schema:- $ref: '#/definitions/responses.Unauthorized'"404":description: Not Foundschema:@@ -3005,13 +2976,13 @@ paths:$ref: '#/definitions/responses.InternalServerError'security:- ApiKeyAuth: []- summary: Show send schedule+ summary: Delete send scheduletags:- Send Schedulesput:consumes:- application/json- description: Updates a send schedule owned by the authenticated user.+ description: Update a send schedule owned by the authenticated user.parameters:- description: Schedule IDin: path@@ -3314,6 +3285,11 @@ paths:required: trueschema:$ref: '#/definitions/requests.UserPaymentInvoice'+ - description: ID of the subscription invoice to generate the PDF for+ in: path+ name: subscriptionInvoiceID+ required: true+ type: stringproduces:- application/pdfresponses:diff --git a/api/pkg/di/container.go b/api/pkg/di/container.goindex e8c015d8..a1fcbb3b 100644--- a/api/pkg/di/container.go+++ b/api/pkg/di/container.go@@ -128,6 +128,7 @@ func NewContainer(projectID string, version string) (container *Container) {container.RegisterUserRoutes()container.RegisterSendScheduleRoutes()+ container.RegisterSendScheduleListeners()container.RegisterUserListeners()container.RegisterPhoneRoutes()@@ -362,8 +363,8 @@ ALTER TABLE discords ADD CONSTRAINT IF NOT EXISTS uni_discords_server_id CHECK (container.logger.Fatal(stacktrace.Propagate(err, fmt.Sprintf("cannot migrate %T", &entities.User{})))}- if err = db.AutoMigrate(&entities.SendSchedule{}); err != nil {- container.logger.Fatal(stacktrace.Propagate(err, fmt.Sprintf("cannot migrate %T", &entities.SendSchedule{})))+ if err = db.AutoMigrate(&entities.MessageSendSchedule{}); err != nil {+ container.logger.Fatal(stacktrace.Propagate(err, fmt.Sprintf("cannot migrate %T", &entities.MessageSendSchedule{})))}if err = db.AutoMigrate(&entities.Phone{}); err != nil {@@ -1139,6 +1140,20 @@ func (container *Container) RegisterMessageListeners() {}}+// RegisterSendScheduleListeners registers event listeners for listeners.SendScheduleListener+func (container *Container) RegisterSendScheduleListeners() {+ container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.SendScheduleListener{}))+ _, routes := listeners.NewSendScheduleListener(+ container.Logger(),+ container.Tracer(),+ container.SendScheduleService(),+ )++ for event, handler := range routes {+ container.EventDispatcher().Subscribe(event, handler)+ }+}+// LemonsqueezyService creates a new instance of services.LemonsqueezyServicefunc (container *Container) LemonsqueezyService() (service *services.LemonsqueezyService) {container.logger.Debug(fmt.Sprintf("creating %T", service))diff --git a/api/pkg/entities/phone.go b/api/pkg/entities/phone.goindex 80d2c8f2..f97212ce 100644--- a/api/pkg/entities/phone.go+++ b/api/pkg/entities/phone.go@@ -8,14 +8,14 @@ import (// Phone represents an android phone which has installed the http sms apptype Phone struct {- ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`- UserID UserID `json:"user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`- FcmToken *string `json:"fcm_token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." validate:"optional"`- PhoneNumber string `json:"phone_number" example:"+18005550199"`- MessagesPerMinute uint `json:"messages_per_minute" example:"1"`- SIM SIM `json:"sim" gorm:"default:SIM1"`- ScheduleID *uuid.UUID `json:"schedule_id" gorm:"type:uuid" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`- Schedule *SendSchedule `json:"-" gorm:"foreignKey:ScheduleID;constraint:OnDelete:SET NULL"`+ ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`+ UserID UserID `json:"user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`+ FcmToken *string `json:"fcm_token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." validate:"optional"`+ PhoneNumber string `json:"phone_number" example:"+18005550199"`+ MessagesPerMinute uint `json:"messages_per_minute" example:"1"`+ SIM SIM `json:"sim" gorm:"default:SIM1"`+ ScheduleID *uuid.UUID `json:"schedule_id" gorm:"type:uuid" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`+ Schedule *MessageSendSchedule `json:"-" gorm:"foreignKey:ScheduleID;constraint:OnDelete:SET NULL"`// MaxSendAttempts determines how many times to retry sending an SMS messageMaxSendAttempts uint `json:"max_send_attempts" example:"2"`diff --git a/api/pkg/entities/send_schedule.go b/api/pkg/entities/send_schedule.goindex 55a8e07c..9ffbad12 100644--- a/api/pkg/entities/send_schedule.go+++ b/api/pkg/entities/send_schedule.go@@ -6,21 +6,98 @@ import ("github.com/google/uuid")-// SendScheduleWindow represents a single availability window for a day of the week.-type SendScheduleWindow struct {+// MessageSendScheduleWindow represents a single availability window for a day of the week.+type MessageSendScheduleWindow struct {DayOfWeek int `json:"day_of_week" example:"1"`StartMinute int `json:"start_minute" example:"540"`EndMinute int `json:"end_minute" example:"1020"`}-// SendSchedule controls when a phone is allowed to send outgoing SMS messages.-type SendSchedule struct {- ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`- UserID UserID `json:"user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`- Name string `json:"name" example:"Business Hours"`- Timezone string `json:"timezone" example:"Europe/Tallinn"`- IsActive bool `json:"is_active" gorm:"default:true" example:"true"`- Windows []SendScheduleWindow `json:"windows" gorm:"type:jsonb;serializer:json"`- CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`- UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`+// MessageSendSchedule controls when a phone is allowed to send outgoing SMS messages.+type MessageSendSchedule struct {+ ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`+ UserID UserID `json:"user_id" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`+ Name string `json:"name" example:"Business Hours"`+ Timezone string `json:"timezone" example:"Europe/Tallinn"`+ IsActive bool `json:"is_active" gorm:"default:true" example:"true"`+ Windows []MessageSendScheduleWindow `json:"windows" gorm:"type:jsonb;serializer:json"`+ CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`+ UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`+}++// 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.+func (schedule *MessageSendSchedule) ResolveScheduledAt(current time.Time) time.Time {+ if schedule == nil || !schedule.IsActive || len(schedule.Windows) == 0 {+ return current.UTC()+ }++ location, err := time.LoadLocation(schedule.Timezone)+ if err != nil {+ return current.UTC()+ }++ base := current.In(location)+ var best time.Time++ for dayOffset := 0; dayOffset <= 7; dayOffset++ {+ day := base.AddDate(0, 0, dayOffset)+ weekday := int(day.Weekday())++ for _, window := range schedule.Windows {+ if window.DayOfWeek != weekday {+ continue+ }++ start := time.Date(+ day.Year(),+ day.Month(),+ day.Day(),+ 0,+ 0,+ 0,+ 0,+ location,+ ).Add(time.Duration(window.StartMinute) * time.Minute)++ end := time.Date(+ day.Year(),+ day.Month(),+ day.Day(),+ 0,+ 0,+ 0,+ 0,+ location,+ ).Add(time.Duration(window.EndMinute) * time.Minute)++ var candidate time.Time++ switch {+ case dayOffset == 0 && base.Before(start):+ candidate = start+ case dayOffset == 0 && (base.Equal(start) || (base.After(start) && base.Before(end))):+ candidate = base+ case dayOffset > 0:+ candidate = start+ default:+ continue+ }++ if best.IsZero() || candidate.Before(best) {+ best = candidate+ }+ }++ if !best.IsZero() {+ break+ }+ }++ if best.IsZero() {+ return current.UTC()+ }++ return best.UTC()}diff --git a/api/pkg/handlers/send_schedule_handler.go b/api/pkg/handlers/send_schedule_handler.goindex 70918cdd..cb636f49 100644--- a/api/pkg/handlers/send_schedule_handler.go+++ b/api/pkg/handlers/send_schedule_handler.go@@ -3,6 +3,7 @@ package handlersimport ("fmt"+ "github.com/NdoleStudio/httpsms/pkg/repositories""github.com/NdoleStudio/httpsms/pkg/requests""github.com/NdoleStudio/httpsms/pkg/services""github.com/NdoleStudio/httpsms/pkg/telemetry"@@ -13,6 +14,7 @@ import ("github.com/palantir/stacktrace")+// SendScheduleHandler handles HTTP requests for message send schedules.type SendScheduleHandler struct {handlerlogger telemetry.Logger@@ -21,6 +23,7 @@ type SendScheduleHandler struct {service *services.SendScheduleService}+// NewSendScheduleHandler creates a new SendScheduleHandler.func NewSendScheduleHandler(logger telemetry.Logger,tracer telemetry.Tracer,@@ -35,6 +38,7 @@ func NewSendScheduleHandler(}}+// RegisterRoutes registers send schedule routes.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)...)@@ -42,13 +46,14 @@ func (h *SendScheduleHandler) RegisterRoutes(router fiber.Router, middlewares ..router.Delete("/v1/send-schedules/:scheduleID", h.computeRoute(middlewares, h.Delete)...)}-// Index godoc+// Index lists all send schedules for the authenticated user.+//// @Summary List send schedules// @Description List all send schedules owned by the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Produce json-// @Success 200 {object} responses.SendSchedulesResponse+// @Success 200 {array} entities.MessageSendSchedule// @Failure 401 {object} responses.Unauthorized// @Failure 500 {object} responses.InternalServerError// @Router /send-schedules [get]@@ -65,7 +70,8 @@ func (h *SendScheduleHandler) Index(c *fiber.Ctx) error {return h.responseOK(c, "send schedules fetched successfully", schedules)}-// Store godoc+// Store creates a new send schedule for the authenticated user.+//// @Summary Create send schedule// @Description Create a new send schedule for the authenticated user.// @Security ApiKeyAuth@@ -90,11 +96,11 @@ func (h *SendScheduleHandler) Store(c *fiber.Ctx) error {request = request.Sanitize()if errors := h.validator.ValidateStore(ctx, request); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewError(fmt.Sprintf(+ ctxLogger.Warn(stacktrace.NewError("validation errors [%s], while storing send schedule [%+#v]",spew.Sdump(errors),request,- )))+ ))return h.responseUnprocessableEntity(c, errors, "validation errors while saving send schedule")}@@ -107,7 +113,8 @@ func (h *SendScheduleHandler) Store(c *fiber.Ctx) error {return h.responseCreated(c, "send schedule created successfully", schedule)}-// Update godoc+// Update updates a send schedule owned by the authenticated user.+//// @Summary Update send schedule// @Description Update a send schedule owned by the authenticated user.// @Security ApiKeyAuth@@ -150,7 +157,7 @@ func (h *SendScheduleHandler) Update(c *fiber.Ctx) error {)if err != nil {ctxLogger.Error(stacktrace.Propagate(err, "cannot update send schedule"))- if stacktrace.GetCode(err) == 404 {+ if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {return h.responseNotFound(c, err.Error())}return h.responseInternalServerError(c)@@ -159,14 +166,15 @@ func (h *SendScheduleHandler) Update(c *fiber.Ctx) error {return h.responseOK(c, "send schedule updated successfully", schedule)}-// Delete godoc+// Delete removes a send schedule owned by the authenticated user.+//// @Summary Delete send schedule// @Description Delete a send schedule owned by the authenticated user.// @Security ApiKeyAuth// @Tags Send Schedules// @Produce json// @Param scheduleID path string true "Schedule ID"-// @Success 204 {object} responses.NoContent+// @Success 204// @Failure 400 {object} responses.BadRequest// @Failure 401 {object} responses.Unauthorized// @Failure 404 {object} responses.NotFound@@ -181,9 +189,17 @@ func (h *SendScheduleHandler) Delete(c *fiber.Ctx) error {return h.responseBadRequest(c, err)}+ if _, err = h.service.Load(ctx, h.userIDFomContext(c), scheduleID); err != nil {+ ctxLogger.Error(stacktrace.Propagate(err, "cannot load send schedule for deletion"))+ if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {+ return h.responseNotFound(c, err.Error())+ }+ return h.responseInternalServerError(c)+ }+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 {+ if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {return h.responseNotFound(c, err.Error())}return h.responseInternalServerError(c)diff --git a/api/pkg/listeners/send_schedule_listener.go b/api/pkg/listeners/send_schedule_listener.gonew file mode 100644index 00000000..08a66f97--- /dev/null+++ b/api/pkg/listeners/send_schedule_listener.go@@ -0,0 +1,73 @@+package listeners++import (+ "context"+ "fmt"++ "github.com/NdoleStudio/httpsms/pkg/events"+ "github.com/NdoleStudio/httpsms/pkg/services"+ "github.com/NdoleStudio/httpsms/pkg/telemetry"+ cloudevents "github.com/cloudevents/sdk-go/v2"+ "github.com/palantir/stacktrace"+)++// SendScheduleListener handles cloud events related to message send schedules.+type SendScheduleListener struct {+ logger telemetry.Logger+ tracer telemetry.Tracer+ service *services.SendScheduleService+}++// NewSendScheduleListener creates a new instance of SendScheduleListener.+func NewSendScheduleListener(+ logger telemetry.Logger,+ tracer telemetry.Tracer,+ service *services.SendScheduleService,+) (l *SendScheduleListener, routes map[string]events.EventListener) {+ l = &SendScheduleListener{+ logger: logger.WithService(fmt.Sprintf("%T", l)),+ tracer: tracer,+ service: service,+ }++ return l, map[string]events.EventListener{+ events.UserAccountDeleted: l.onUserAccountDeleted,+ }+}++// onUserAccountDeleted removes all message send schedules for a deleted user account.+func (listener *SendScheduleListener) onUserAccountDeleted(+ ctx context.Context,+ event cloudevents.Event,+) error {+ ctx, span := listener.tracer.Start(ctx)+ defer span.End()++ var payload events.UserAccountDeletedPayload+ if err := event.DataAs(&payload); err != nil {+ return listener.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot decode [%s] into [%T]",+ event.Data(),+ payload,+ ),+ )+ }++ if err := listener.service.DeleteAllForUser(ctx, payload.UserID); err != nil {+ return listener.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot delete [entities.MessageSendSchedule] for user [%s] on [%s] event with ID [%s]",+ payload.UserID,+ event.Type(),+ event.ID(),+ ),+ )+ }++ return nil+}diff --git a/api/pkg/repositories/gorm_phone_notification_repository.go b/api/pkg/repositories/gorm_phone_notification_repository.goindex 9a1d29d1..8cc16f1e 100644--- a/api/pkg/repositories/gorm_phone_notification_repository.go+++ b/api/pkg/repositories/gorm_phone_notification_repository.go@@ -15,40 +15,57 @@ import ("gorm.io/gorm")-// gormPhoneNotificationRepository is responsible for persisting entities.PhoneNotification+// gormPhoneNotificationRepository persists entities.PhoneNotification records.type gormPhoneNotificationRepository struct {logger telemetry.Loggertracer telemetry.Tracerdb *gorm.DB}-// NewGormPhoneNotificationRepository creates the GORM version of the PhoneNotificationRepository+// NewGormPhoneNotificationRepository creates a GORM-backed PhoneNotificationRepository.func NewGormPhoneNotificationRepository(logger telemetry.Logger,tracer telemetry.Tracer,db *gorm.DB,) PhoneNotificationRepository {return &gormPhoneNotificationRepository{- logger: logger.WithService(fmt.Sprintf("%T", &gormHeartbeatRepository{})),+ logger: logger.WithService(fmt.Sprintf("%T", &gormPhoneNotificationRepository{})),tracer: tracer,db: db,}}-func (repository *gormPhoneNotificationRepository) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {+// DeleteAllForUser deletes all phone notifications that belong to a user.+func (repository *gormPhoneNotificationRepository) DeleteAllForUser(+ ctx context.Context,+ userID entities.UserID,+) error {ctx, span := repository.tracer.Start(ctx)defer span.End()- if err := repository.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&entities.PhoneNotification{}).Error; err != nil {- msg := fmt.Sprintf("cannot delete all [%T] for user with ID [%s]", &entities.PhoneNotification{}, userID)- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ if err := repository.db.WithContext(ctx).+ Where("user_id = ?", userID).+ Delete(&entities.PhoneNotification{}).Error; err != nil {+ return repository.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot delete all [%T] for user with ID [%s]",+ &entities.PhoneNotification{},+ userID,+ ),+ )}return nil}-// UpdateStatus of an entities.PhoneNotification-func (repository *gormPhoneNotificationRepository) UpdateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) error {+// UpdateStatus updates the status of a phone notification.+func (repository *gormPhoneNotificationRepository) UpdateStatus(+ ctx context.Context,+ notificationID uuid.UUID,+ status entities.PhoneNotificationStatus,+) error {ctx, span := repository.tracer.Start(ctx)defer span.End()@@ -58,120 +75,131 @@ func (repository *gormPhoneNotificationRepository) UpdateStatus(ctx context.ContUpdate("status", status).Errorif err != nil {- msg := fmt.Sprintf("cannot update notification [%s] with status [%s]", notificationID, status)- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ return repository.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot update notification [%s] with status [%s]",+ notificationID,+ status,+ ),+ )}return nil}-// Schedule a notification to be sent in the future-func (repository *gormPhoneNotificationRepository) Schedule(ctx context.Context, messagesPerMinute uint, schedule *entities.SendSchedule, notification *entities.PhoneNotification) error {+// Schedule stores a phone notification and calculates its final scheduled time.+// The final time is determined by combining:+// 1. the next allowed time from the message send schedule+// 2. the phone send-rate limit derived from the latest scheduled notification+func (repository *gormPhoneNotificationRepository) Schedule(+ ctx context.Context,+ messagesPerMinute uint,+ schedule *entities.MessageSendSchedule,+ notification *entities.PhoneNotification,+) error {ctx, span := repository.tracer.Start(ctx)defer span.End()+ now := time.Now().UTC()+if messagesPerMinute == 0 {- notification.ScheduledAt = repository.resolveScheduledAt(time.Now().UTC(), schedule)+ notification.ScheduledAt = repository.resolveScheduledAt(schedule, now)return repository.insert(ctx, notification)}err := crdbgorm.ExecuteTx(ctx, repository.db, nil, func(tx *gorm.DB) error {lastNotification := new(entities.PhoneNotification)+err := tx.WithContext(ctx).Where("phone_id = ?", notification.PhoneID).Order("scheduled_at desc").First(lastNotification).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {- msg := fmt.Sprintf("cannot fetch last notification with phone ID [%s]", notification.PhoneID)- return stacktrace.Propagate(err, msg)+ return stacktrace.Propagate(+ err,+ "cannot fetch last notification with phone ID [%s]",+ notification.PhoneID,+ )}- notification.ScheduledAt = repository.resolveScheduledAt(time.Now().UTC(), schedule)+ notification.ScheduledAt = repository.resolveScheduledAt(schedule, now)+if err == nil {- rateLimitedAt := lastNotification.ScheduledAt.Add(time.Duration(60/messagesPerMinute) * time.Second)- notification.ScheduledAt = repository.resolveScheduledAt(repository.maxTime(notification.ScheduledAt, rateLimitedAt), schedule)+ rateLimitedAt := lastNotification.ScheduledAt.Add(+ time.Duration(60/messagesPerMinute) * time.Second,+ )++ nextCandidate := repository.maxTime(notification.ScheduledAt, rateLimitedAt)+ notification.ScheduledAt = repository.resolveScheduledAt(schedule, nextCandidate)}if err = tx.WithContext(ctx).Create(notification).Error; err != nil {- msg := fmt.Sprintf("cannot create new notification with id [%s] and schedule [%s]", notification.ID, notification.ScheduledAt.String())- return stacktrace.Propagate(err, msg)+ return stacktrace.Propagate(+ err,+ "cannot create new notification with id [%s] and schedule [%s]",+ notification.ID,+ notification.ScheduledAt.String(),+ )}+return nil})if err != nil {- msg := fmt.Sprintf("cannot schedule phone notification with ID [%s]", notification.ID)- return stacktrace.Propagate(err, msg)+ return repository.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot schedule phone notification with ID [%s]",+ notification.ID,+ ),+ )}return nil}-func (repository *gormPhoneNotificationRepository) resolveScheduledAt(current time.Time, schedule *entities.SendSchedule) time.Time {- if schedule == nil || !schedule.IsActive || len(schedule.Windows) == 0 {- return current.UTC()- }-- location, err := time.LoadLocation(schedule.Timezone)- if err != nil {+// resolveScheduledAt returns the next time the notification is allowed to be sent.+// If no schedule is attached, the provided time is returned unchanged in UTC.+func (repository *gormPhoneNotificationRepository) resolveScheduledAt(+ schedule *entities.MessageSendSchedule,+ current time.Time,+) time.Time {+ if schedule == nil {return current.UTC()}- base := current.In(location)- var best time.Time- for dayOffset := 0; dayOffset <= 7; dayOffset++ {- day := base.AddDate(0, 0, dayOffset)- weekday := int(day.Weekday())- for _, window := range schedule.Windows {- if window.DayOfWeek != weekday {- continue- }-- start := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, location).Add(time.Duration(window.StartMinute) * time.Minute)- end := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, location).Add(time.Duration(window.EndMinute) * time.Minute)-- var candidate time.Time- switch {- case dayOffset == 0 && base.Before(start):- candidate = start- case dayOffset == 0 && (base.Equal(start) || (base.After(start) && base.Before(end))):- candidate = base- case dayOffset > 0:- candidate = start- default:- continue- }-- if best.IsZero() || candidate.Before(best) {- best = candidate- }- }- if !best.IsZero() {- break- }- }-- if best.IsZero() {- return current.UTC()- }- return best.UTC()+ return schedule.ResolveScheduledAt(current)}+// maxTime returns the later of the two times.func (repository *gormPhoneNotificationRepository) maxTime(a, b time.Time) time.Time {- if a.Unix() > b.Unix() {+ if a.After(b) {return a}return b}-func (repository *gormPhoneNotificationRepository) insert(ctx context.Context, notification *entities.PhoneNotification) error {+// insert stores a single phone notification.+func (repository *gormPhoneNotificationRepository) insert(+ ctx context.Context,+ notification *entities.PhoneNotification,+) error {ctx, span := repository.tracer.Start(ctx)defer span.End()- err := repository.db.WithContext(ctx).Create(notification).Error- if err != nil {- msg := fmt.Sprintf("cannot store notification with id [%s]", notification.ID)- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ if err := repository.db.WithContext(ctx).Create(notification).Error; err != nil {+ return repository.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ "cannot store notification with id [%s]",+ notification.ID,+ ),+ )}+return nil}diff --git a/api/pkg/repositories/gorm_send_schedule_repository.go b/api/pkg/repositories/gorm_send_schedule_repository.goindex 83405d40..afd09472 100644--- a/api/pkg/repositories/gorm_send_schedule_repository.go+++ b/api/pkg/repositories/gorm_send_schedule_repository.go@@ -12,72 +12,157 @@ import ("gorm.io/gorm")+// gormSendScheduleRepository persists and loads entities.MessageSendSchedule using GORM.type gormSendScheduleRepository struct {logger telemetry.Loggertracer telemetry.Tracerdb *gorm.DB}-func NewGormSendScheduleRepository(logger telemetry.Logger, tracer telemetry.Tracer, db *gorm.DB) SendScheduleRepository {- return &gormSendScheduleRepository{logger: logger.WithService(fmt.Sprintf("%T", &gormSendScheduleRepository{})), tracer: tracer, db: db}+// NewGormSendScheduleRepository creates a new GORM-backed SendScheduleRepository.+func NewGormSendScheduleRepository(+ logger telemetry.Logger,+ tracer telemetry.Tracer,+ db *gorm.DB,+) SendScheduleRepository {+ return &gormSendScheduleRepository{+ logger: logger.WithService(fmt.Sprintf("%T", &gormSendScheduleRepository{})),+ tracer: tracer,+ db: db,+ }}-func (r *gormSendScheduleRepository) Store(ctx context.Context, schedule *entities.SendSchedule) error {+// Store saves a new message send schedule.+func (r *gormSendScheduleRepository) Store(+ ctx context.Context,+ schedule *entities.MessageSendSchedule,+) error {ctx, span := r.tracer.Start(ctx)defer span.End()+if err := r.db.WithContext(ctx).Create(schedule).Error; err != nil {- return r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot store send schedule [%s]", schedule.ID)))+ return r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot store send schedule [%s]", schedule.ID),+ )}+return nil}-func (r *gormSendScheduleRepository) Update(ctx context.Context, schedule *entities.SendSchedule) error {+// Update persists changes to an existing message send schedule.+func (r *gormSendScheduleRepository) Update(+ ctx context.Context,+ schedule *entities.MessageSendSchedule,+) error {ctx, span := r.tracer.Start(ctx)defer span.End()+if err := r.db.WithContext(ctx).Save(schedule).Error; err != nil {- return r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot update send schedule [%s]", schedule.ID)))+ return r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot update send schedule [%s]", schedule.ID),+ )}+return nil}-func (r *gormSendScheduleRepository) Load(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) (*entities.SendSchedule, error) {+// Load fetches a message send schedule by user ID and schedule ID.+func (r *gormSendScheduleRepository) Load(+ ctx context.Context,+ userID entities.UserID,+ scheduleID uuid.UUID,+) (*entities.MessageSendSchedule, error) {ctx, span := r.tracer.Start(ctx)defer span.End()- item := new(entities.SendSchedule)- err := r.db.WithContext(ctx).Where("user_id = ?", userID).Where("id = ?", scheduleID).First(item).Error++ item := new(entities.MessageSendSchedule)+ err := r.db.WithContext(ctx).+ Where("user_id = ?", userID).+ Where("id = ?", scheduleID).+ First(item).Errorif errors.Is(err, gorm.ErrRecordNotFound) {- return nil, r.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, ErrCodeNotFound, fmt.Sprintf("send schedule [%s] not found", scheduleID)))+ return nil, r.tracer.WrapErrorSpan(+ span,+ stacktrace.PropagateWithCode(+ err,+ ErrCodeNotFound,+ "send schedule [%s] not found",+ scheduleID,+ ),+ )}if err != nil {- return nil, r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot load send schedule [%s]", scheduleID)))+ return nil, r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot load send schedule [%s]", scheduleID),+ )}+return item, nil}-func (r *gormSendScheduleRepository) Index(ctx context.Context, userID entities.UserID) ([]entities.SendSchedule, error) {+// Index lists all message send schedules owned by the given user.+func (r *gormSendScheduleRepository) Index(+ ctx context.Context,+ userID entities.UserID,+) ([]entities.MessageSendSchedule, error) {ctx, span := r.tracer.Start(ctx)defer span.End()- items := make([]entities.SendSchedule, 0)- if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Order("created_at ASC").Find(&items).Error; err != nil {- return nil, r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot index send schedules for user [%s]", userID)))++ items := make([]entities.MessageSendSchedule, 0)+ if err := r.db.WithContext(ctx).+ Where("user_id = ?", userID).+ Order("created_at ASC").+ Find(&items).Error; err != nil {+ return nil, r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot index send schedules for user [%s]", userID),+ )}+return items, nil}-func (r *gormSendScheduleRepository) Delete(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) error {+// Delete removes a message send schedule owned by the given user.+func (r *gormSendScheduleRepository) Delete(+ ctx context.Context,+ userID entities.UserID,+ scheduleID uuid.UUID,+) error {ctx, span := r.tracer.Start(ctx)defer span.End()- if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Where("id = ?", scheduleID).Delete(&entities.SendSchedule{}).Error; err != nil {- return r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot delete send schedule [%s]", scheduleID)))++ if err := r.db.WithContext(ctx).+ Where("user_id = ?", userID).+ Where("id = ?", scheduleID).+ Delete(&entities.MessageSendSchedule{}).Error; err != nil {+ return r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot delete send schedule [%s]", scheduleID),+ )}+return nil}-func (r *gormSendScheduleRepository) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {+// DeleteAllForUser removes all message send schedules owned by the given user.+func (r *gormSendScheduleRepository) DeleteAllForUser(+ ctx context.Context,+ userID entities.UserID,+) error {ctx, span := r.tracer.Start(ctx)defer span.End()- if err := r.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&entities.SendSchedule{}).Error; err != nil {- return r.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot delete send schedules for user [%s]", userID)))++ if err := r.db.WithContext(ctx).+ Where("user_id = ?", userID).+ Delete(&entities.MessageSendSchedule{}).Error; err != nil {+ return r.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(err, "cannot delete send schedules for user [%s]", userID),+ )}+return nil}diff --git a/api/pkg/repositories/phone_notification_repository.go b/api/pkg/repositories/phone_notification_repository.goindex c547379e..9d93f0b3 100644--- a/api/pkg/repositories/phone_notification_repository.go+++ b/api/pkg/repositories/phone_notification_repository.go@@ -11,7 +11,7 @@ import (// PhoneNotificationRepository loads and persists an entities.PhoneNotificationtype PhoneNotificationRepository interface {// Schedule a new entities.PhoneNotification- Schedule(ctx context.Context, messagesPerMinute uint, schedule *entities.SendSchedule, notification *entities.PhoneNotification) error+ Schedule(ctx context.Context, messagesPerMinute uint, schedule *entities.MessageSendSchedule, notification *entities.PhoneNotification) error// UpdateStatus of a notificationUpdateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) errordiff --git a/api/pkg/repositories/send_schedule_repository.go b/api/pkg/repositories/send_schedule_repository.goindex 7b232d13..57e07ca6 100644--- a/api/pkg/repositories/send_schedule_repository.go+++ b/api/pkg/repositories/send_schedule_repository.go@@ -7,12 +7,23 @@ import ("github.com/google/uuid")-// SendScheduleRepository loads and persists entities.SendSchedule.+// SendScheduleRepository loads and persists entities.MessageSendSchedule.type SendScheduleRepository interface {- Store(ctx context.Context, schedule *entities.SendSchedule) error- Update(ctx context.Context, schedule *entities.SendSchedule) error- Load(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) (*entities.SendSchedule, error)- Index(ctx context.Context, userID entities.UserID) ([]entities.SendSchedule, error)+ // Store persists a new message send schedule.+ Store(ctx context.Context, schedule *entities.MessageSendSchedule) error++ // Update persists changes to an existing message send schedule.+ Update(ctx context.Context, schedule *entities.MessageSendSchedule) error++ // Load returns a message send schedule by user ID and schedule ID.+ Load(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) (*entities.MessageSendSchedule, error)++ // Index returns all message send schedules owned by a user.+ Index(ctx context.Context, userID entities.UserID) ([]entities.MessageSendSchedule, error)++ // Delete removes a message send schedule owned by a user.Delete(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) error++ // DeleteAllForUser removes all message send schedules owned by a user.DeleteAllForUser(ctx context.Context, userID entities.UserID) error}diff --git a/api/pkg/requests/send_schedule_store_request.go b/api/pkg/requests/send_schedule_store_request.goindex 5d9f06b0..8a6a2c3d 100644--- a/api/pkg/requests/send_schedule_store_request.go+++ b/api/pkg/requests/send_schedule_store_request.go@@ -40,9 +40,9 @@ func (input *SendScheduleStore) Sanitize() SendScheduleStore {}func (input *SendScheduleStore) ToParams(user entities.AuthContext) *services.SendScheduleUpsertParams {- windows := make([]entities.SendScheduleWindow, 0, len(input.Windows))+ windows := make([]entities.MessageSendScheduleWindow, 0, len(input.Windows))for _, item := range input.Windows {- windows = append(windows, entities.SendScheduleWindow{DayOfWeek: item.DayOfWeek, StartMinute: item.StartMinute, EndMinute: item.EndMinute})+ windows = append(windows, entities.MessageSendScheduleWindow{DayOfWeek: item.DayOfWeek, StartMinute: item.StartMinute, EndMinute: item.EndMinute})}return &services.SendScheduleUpsertParams{UserID: user.ID, Name: input.Name, Timezone: input.Timezone, IsActive: input.IsActive, Windows: windows}}diff --git a/api/pkg/responses/send_schedule_responses.go b/api/pkg/responses/send_schedule_responses.goindex 405b4617..9834de86 100644--- a/api/pkg/responses/send_schedule_responses.go+++ b/api/pkg/responses/send_schedule_responses.go@@ -4,10 +4,10 @@ import "github.com/NdoleStudio/httpsms/pkg/entities"type SendSchedulesResponse struct {response- Data []entities.SendSchedule `json:"data"`+ Data []entities.MessageSendSchedule `json:"data"`}type SendScheduleResponse struct {response- Data entities.SendSchedule `json:"data"`+ Data entities.MessageSendSchedule `json:"data"`}diff --git a/api/pkg/services/phone_notification_service.go b/api/pkg/services/phone_notification_service.goindex 38c577b5..ffafa555 100644--- a/api/pkg/services/phone_notification_service.go+++ b/api/pkg/services/phone_notification_service.go@@ -195,7 +195,7 @@ func (service *PhoneNotificationService) Schedule(ctx context.Context, params *PUpdatedAt: time.Now().UTC(),}- var schedule *entities.SendSchedule+ var schedule *entities.MessageSendScheduleif phone.ScheduleID != nil {schedule, err = service.sendScheduleRepository.Load(ctx, params.UserID, *phone.ScheduleID)if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {diff --git a/api/pkg/services/send_schedule_service.go b/api/pkg/services/send_schedule_service.goindex 96a72151..d942d285 100644--- a/api/pkg/services/send_schedule_service.go+++ b/api/pkg/services/send_schedule_service.go@@ -13,6 +13,7 @@ import ("github.com/palantir/stacktrace")+// SendScheduleService manages message send schedules for a user.type SendScheduleService struct {servicelogger telemetry.Logger@@ -20,117 +21,249 @@ type SendScheduleService struct {repository repositories.SendScheduleRepository}-func NewSendScheduleService(logger telemetry.Logger, tracer telemetry.Tracer, repository repositories.SendScheduleRepository) *SendScheduleService {- return &SendScheduleService{logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleService{})), tracer: tracer, repository: repository}+// NewSendScheduleService creates a new SendScheduleService.+func NewSendScheduleService(+ logger telemetry.Logger,+ tracer telemetry.Tracer,+ repository repositories.SendScheduleRepository,+) *SendScheduleService {+ return &SendScheduleService{+ logger: logger.WithService(fmt.Sprintf("%T", &SendScheduleService{})),+ tracer: tracer,+ repository: repository,+ }}+// SendScheduleUpsertParams contains the fields required to create or update a message send schedule.type SendScheduleUpsertParams struct {UserID entities.UserIDName stringTimezone stringIsActive bool- Windows []entities.SendScheduleWindow+ Windows []entities.MessageSendScheduleWindow}-func (service *SendScheduleService) Index(ctx context.Context, userID entities.UserID) ([]entities.SendSchedule, error) {+// Index returns all message send schedules for a user.+func (service *SendScheduleService) Index(+ ctx context.Context,+ userID entities.UserID,+) ([]entities.MessageSendSchedule, error) {return service.repository.Index(ctx, userID)}-func (service *SendScheduleService) Load(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) (*entities.SendSchedule, error) {+// Load returns a single message send schedule for a user.+func (service *SendScheduleService) Load(+ ctx context.Context,+ userID entities.UserID,+ scheduleID uuid.UUID,+) (*entities.MessageSendSchedule, error) {return service.repository.Load(ctx, userID, scheduleID)}-func (service *SendScheduleService) Store(ctx context.Context, params *SendScheduleUpsertParams) (*entities.SendSchedule, error) {+// Store creates a new message send schedule.+func (service *SendScheduleService) Store(+ ctx context.Context,+ params *SendScheduleUpsertParams,+) (*entities.MessageSendSchedule, error) {ctx, span := service.tracer.Start(ctx)defer span.End()- schedule := &entities.SendSchedule{ID: uuid.New(), UserID: params.UserID, Name: params.Name, Timezone: params.Timezone, IsActive: params.IsActive, Windows: sanitizeWindows(params.Windows), CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC()}++ schedule := &entities.MessageSendSchedule{+ ID: uuid.New(),+ UserID: params.UserID,+ Name: params.Name,+ Timezone: params.Timezone,+ IsActive: params.IsActive,+ Windows: sanitizeWindows(params.Windows),+ CreatedAt: time.Now().UTC(),+ UpdatedAt: time.Now().UTC(),+ }+if err := service.repository.Store(ctx, schedule); err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot store send schedule [%s]", schedule.ID)))+ return nil, service.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ fmt.Sprintf("cannot store message send schedule [%s]", schedule.ID),+ ),+ )}+return schedule, nil}-func (service *SendScheduleService) Update(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID, params *SendScheduleUpsertParams) (*entities.SendSchedule, error) {+// Update updates an existing message send schedule.+func (service *SendScheduleService) Update(+ ctx context.Context,+ userID entities.UserID,+ scheduleID uuid.UUID,+ params *SendScheduleUpsertParams,+) (*entities.MessageSendSchedule, error) {ctx, span := service.tracer.Start(ctx)defer span.End()+schedule, err := service.repository.Load(ctx, userID, scheduleID)if err != nil {return nil, err}+schedule.Name = params.Nameschedule.Timezone = params.Timezoneschedule.IsActive = params.IsActiveschedule.Windows = sanitizeWindows(params.Windows)schedule.UpdatedAt = time.Now().UTC()+if err = service.repository.Update(ctx, schedule); err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot update send schedule [%s]", schedule.ID)))+ return nil, service.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ fmt.Sprintf("cannot update message send schedule [%s]", schedule.ID),+ ),+ )}+return schedule, nil}-func (service *SendScheduleService) Delete(ctx context.Context, userID entities.UserID, scheduleID uuid.UUID) error {+// Delete removes a message send schedule for a user.+func (service *SendScheduleService) Delete(+ ctx context.Context,+ userID entities.UserID,+ scheduleID uuid.UUID,+) error {return service.repository.Delete(ctx, userID, scheduleID)}-func (service *SendScheduleService) ResolveScheduledSendTime(ctx context.Context, schedule *entities.SendSchedule, current time.Time) (time.Time, error) {+// ResolveScheduledSendTime returns the next allowed send time based on the schedule windows and timezone.+func (service *SendScheduleService) ResolveScheduledSendTime(+ ctx context.Context,+ schedule *entities.MessageSendSchedule,+ current time.Time,+) (time.Time, error) {ctx, span := service.tracer.Start(ctx)defer span.End()+if schedule == nil || !schedule.IsActive || len(schedule.Windows) == 0 {return current.UTC(), nil}+location, err := time.LoadLocation(schedule.Timezone)if err != nil {- return current.UTC(), service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, fmt.Sprintf("cannot load location [%s]", schedule.Timezone)))+ return current.UTC(), service.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ fmt.Sprintf("cannot load location [%s]", schedule.Timezone),+ ),+ )}base := current.In(location)- type candidate struct{ t time.Time }best := time.Time{}+for dayOffset := 0; dayOffset <= 7; dayOffset++ {day := base.AddDate(0, 0, dayOffset)weekday := int(day.Weekday())+for _, window := range schedule.Windows {if window.DayOfWeek != weekday {continue}- start := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, location).Add(time.Duration(window.StartMinute) * time.Minute)- end := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, location).Add(time.Duration(window.EndMinute) * time.Minute)++ start := time.Date(+ day.Year(),+ day.Month(),+ day.Day(),+ 0,+ 0,+ 0,+ 0,+ location,+ ).Add(time.Duration(window.StartMinute) * time.Minute)++ end := time.Date(+ day.Year(),+ day.Month(),+ day.Day(),+ 0,+ 0,+ 0,+ 0,+ location,+ ).Add(time.Duration(window.EndMinute) * time.Minute)+var candidateTime time.Time+switch {case dayOffset == 0 && base.Before(start):candidateTime = start- case (dayOffset == 0 && (base.Equal(start) || (base.After(start) && base.Before(end)))) || (dayOffset > 0):+ case dayOffset == 0 && (base.Equal(start) || (base.After(start) && base.Before(end))):candidateTime = base- if dayOffset > 0 {- candidateTime = start- }+ case dayOffset > 0:+ candidateTime = startdefault:continue}+if best.IsZero() || candidateTime.Before(best) {best = candidateTime}}+if !best.IsZero() {break}}+if best.IsZero() {return current.UTC(), nil}+return best.UTC(), nil}-func sanitizeWindows(windows []entities.SendScheduleWindow) []entities.SendScheduleWindow {- result := make([]entities.SendScheduleWindow, 0, len(windows))+// sanitizeWindows normalizes and sorts schedule windows by day and start minute.+func sanitizeWindows(+ windows []entities.MessageSendScheduleWindow,+) []entities.MessageSendScheduleWindow {+ result := make([]entities.MessageSendScheduleWindow, 0, len(windows))+for _, item := range windows {- result = append(result, entities.SendScheduleWindow{DayOfWeek: item.DayOfWeek, StartMinute: item.StartMinute, EndMinute: item.EndMinute})+ result = append(result, entities.MessageSendScheduleWindow{+ DayOfWeek: item.DayOfWeek,+ StartMinute: item.StartMinute,+ EndMinute: item.EndMinute,+ })}+sort.SliceStable(result, func(i, j int) bool {if result[i].DayOfWeek == result[j].DayOfWeek {return result[i].StartMinute < result[j].StartMinute}return result[i].DayOfWeek < result[j].DayOfWeek})+return result}++// DeleteAllForUser removes all message send schedules owned by a user.+func (service *SendScheduleService) DeleteAllForUser(+ ctx context.Context,+ userID entities.UserID,+) error {+ ctx, span := service.tracer.Start(ctx)+ defer span.End()++ if err := service.repository.DeleteAllForUser(ctx, userID); err != nil {+ return service.tracer.WrapErrorSpan(+ span,+ stacktrace.Propagate(+ err,+ fmt.Sprintf("cannot delete message send schedules for user [%s]", userID),+ ),+ )+ }++ return nil+}diff --git a/api/pkg/validators/send_schedule_handler_validator.go b/api/pkg/validators/send_schedule_handler_validator.goindex 313eba9d..d402fa5c 100644--- a/api/pkg/validators/send_schedule_handler_validator.go+++ b/api/pkg/validators/send_schedule_handler_validator.go@@ -4,6 +4,7 @@ import ("context""fmt""net/url"+ "sort""time""github.com/NdoleStudio/httpsms/pkg/requests"@@ -13,12 +14,14 @@ import (const maxWindowsPerDay = 6+// SendScheduleHandlerValidator validates send schedule HTTP requests.type SendScheduleHandlerValidator struct {validatorlogger telemetry.Loggertracer telemetry.Tracer}+// NewSendScheduleHandlerValidator creates a new SendScheduleHandlerValidator.func NewSendScheduleHandlerValidator(logger telemetry.Logger,tracer telemetry.Tracer,@@ -29,6 +32,7 @@ func NewSendScheduleHandlerValidator(}}+// ValidateStore validates a send schedule create or update request.func (validator *SendScheduleHandlerValidator) ValidateStore(_ context.Context,request requests.SendScheduleStore,@@ -44,8 +48,10 @@ func (validator *SendScheduleHandlerValidator) ValidateStore(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")+ if request.Timezone != "" {+ if _, err := time.LoadLocation(request.Timezone); err != nil {+ result.Add("timezone", "timezone must be a valid IANA timezone")+ }}return result@@ -63,6 +69,8 @@ func (validator *SendScheduleHandlerValidator) validateWindows(validator.validateEndMinute(result, index, item)validator.validateWindowRange(result, index, item)}++ validator.validateOverlappingWindows(result, windows)}func (validator *SendScheduleHandlerValidator) validateDayOfWeek(@@ -114,3 +122,39 @@ func (validator *SendScheduleHandlerValidator) validateWindowRange(result.Add("windows", fmt.Sprintf("windows[%d].end_minute must be greater than start_minute", index))}}++func (validator *SendScheduleHandlerValidator) validateOverlappingWindows(+ result url.Values,+ windows []requests.SendScheduleWindow,+) {+ grouped := make(map[int][]requests.SendScheduleWindow)++ for _, item := range windows {+ if item.DayOfWeek < 0 || item.DayOfWeek > 6 {+ continue+ }+ if item.EndMinute <= item.StartMinute {+ continue+ }+ grouped[item.DayOfWeek] = append(grouped[item.DayOfWeek], item)+ }++ for dayOfWeek, dayWindows := range grouped {+ sort.Slice(dayWindows, func(i, j int) bool {+ return dayWindows[i].StartMinute < dayWindows[j].StartMinute+ })++ for i := 1; i < len(dayWindows); i++ {+ previous := dayWindows[i-1]+ current := dayWindows[i]++ if current.StartMinute < previous.EndMinute {+ result.Add(+ "windows",+ fmt.Sprintf("day_of_week %d contains overlapping windows", dayOfWeek),+ )+ break+ }+ }+ }+}