77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package transformer
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"repository.promas.id/prana/omnix-sopiga/domain"
|
|
"repository.promas.id/prana/omnix-sopiga/entity"
|
|
)
|
|
|
|
type Transformer struct{}
|
|
|
|
func New() *Transformer {
|
|
return &Transformer{}
|
|
}
|
|
|
|
func (t *Transformer) EntityToDomain(e *entity.BroadcastStaging) (*domain.Broadcast, error) {
|
|
var payload map[string]any
|
|
if err := json.Unmarshal(e.MessagePayload, &payload); err != nil {
|
|
return nil, fmt.Errorf("unmarshal message_payload: %w", err)
|
|
}
|
|
|
|
return &domain.Broadcast{
|
|
ID: e.ID,
|
|
SopigaCollarID: e.SopigaCollarID,
|
|
SopigaTemplateID: e.SopigaTemplateID,
|
|
MessagePayload: payload,
|
|
Status: domain.BroadcastStatus(e.Status),
|
|
ErrorMessage: e.ErrorMessage,
|
|
ErrorCount: e.ErrorCount,
|
|
SopigaRecipientDetailID: e.SopigaRecipientDetailID,
|
|
CreatedAt: e.CreatedAt,
|
|
UpdatedAt: e.UpdatedAt,
|
|
}, nil
|
|
}
|
|
|
|
func (t *Transformer) EntityToDomainVariable(e *entity.TemplateVariableMapping) *domain.TemplateVariable {
|
|
return &domain.TemplateVariable{
|
|
VariableOrder: e.VariableOrder,
|
|
VariableName: e.SopigaVariableName,
|
|
VariableType: e.VariableType,
|
|
FieldSource: e.DBFieldSource,
|
|
IsRequired: e.IsRequired,
|
|
}
|
|
}
|
|
|
|
// BuildDynamicMessage interpolates the message payload against the ordered
|
|
// template variables, joining formatted values with "#" — the delimiter
|
|
// Sopiga expects between positional template placeholders.
|
|
func (t *Transformer) BuildDynamicMessage(variables []*domain.TemplateVariable, payload map[string]any) (string, error) {
|
|
parts := make([]string, 0, len(variables))
|
|
|
|
for _, v := range variables {
|
|
value, exists := payload[v.FieldSource]
|
|
if !exists {
|
|
if v.IsRequired {
|
|
return "", fmt.Errorf("missing required field: %s", v.FieldSource)
|
|
}
|
|
value = ""
|
|
}
|
|
|
|
parts = append(parts, formatValue(v.VariableType, value))
|
|
}
|
|
|
|
return strings.Join(parts, "#"), nil
|
|
}
|
|
|
|
func formatValue(variableType string, value any) string {
|
|
switch variableType {
|
|
case "integer", "decimal":
|
|
return fmt.Sprintf("%.0f", value)
|
|
default:
|
|
return fmt.Sprintf("%v", value)
|
|
}
|
|
}
|