i18n: backend-localized lookups, suggestions, and static data (10 languages)
Backend CI / Test (push) Has been cancelled
Backend CI / Contract Tests (push) Has been cancelled
Backend CI / Lint (push) Has been cancelled
Backend CI / Secret Scanning (push) Has been cancelled
Backend CI / Build (push) Has been cancelled

- suggestion_service: fix scorer (stringList unmarshal accepts scalar|array;
  anchor scoring on base universal score so bool matches no longer tie); add
  localizeReasons for human-readable, Accept-Language-localized match reasons
- lookup_i18n: localize lookup display names, home-profile options, document
  types/categories via internal/i18n
- static_data_handler: per-locale seeded-data response (display_name, home
  profile options, document types/categories) with per-locale cache + ETag
- settings_handler: invalidate per-locale seeded-data cache on lookup change
  instead of pre-warming a single non-localized blob
- cache_service: per-locale seeded-data keys + ETag
- DTOs: add DisplayName fields (task/residence/contractor)
- translations: add suggestion.reason.* and lookup.* keys across all 10 langs
- cmd/api: extract startup helpers + tests

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Trey T
2026-06-04 20:54:54 -05:00
parent 25897e913e
commit 12de5a230a
23 changed files with 1671 additions and 703 deletions
+132 -70
View File
@@ -3,11 +3,14 @@ package services
import (
"encoding/json"
"sort"
"strings"
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
"gorm.io/gorm"
"github.com/treytartt/honeydue-api/internal/apperrors"
"github.com/treytartt/honeydue-api/internal/dto/responses"
"github.com/treytartt/honeydue-api/internal/i18n"
"github.com/treytartt/honeydue-api/internal/models"
"github.com/treytartt/honeydue-api/internal/repositories"
)
@@ -26,25 +29,59 @@ func NewSuggestionService(db *gorm.DB, residenceRepo *repositories.ResidenceRepo
}
}
// stringList is a condition value that may be encoded as either a single JSON
// string ("gas_furnace") or an array of allowed strings (["gas_furnace",
// "boiler"]). The seeded template catalog uses arrays of allowed values; older
// hand-written conditions used a scalar. Accepting both keeps every existing
// condition working — and a scalar `*string` (the previous type) silently
// failed to unmarshal the array form, collapsing every conditioned template to
// "universal".
type stringList []string
// UnmarshalJSON accepts a string or an array of strings.
func (s *stringList) UnmarshalJSON(data []byte) error {
var arr []string
if err := json.Unmarshal(data, &arr); err == nil {
*s = arr
return nil
}
var one string
if err := json.Unmarshal(data, &one); err != nil {
return err
}
*s = stringList{one}
return nil
}
// contains reports whether v is one of the allowed values.
func (s stringList) contains(v string) bool {
for _, x := range s {
if x == v {
return true
}
}
return false
}
// templateConditions represents the parsed conditions JSON from a task template.
// Every field is optional; a template with no conditions is "universal" and
// receives a small base score. See scoreTemplate for how each field is used.
type templateConditions struct {
HeatingType *string `json:"heating_type,omitempty"`
CoolingType *string `json:"cooling_type,omitempty"`
WaterHeaterType *string `json:"water_heater_type,omitempty"`
RoofType *string `json:"roof_type,omitempty"`
ExteriorType *string `json:"exterior_type,omitempty"`
FlooringPrimary *string `json:"flooring_primary,omitempty"`
LandscapingType *string `json:"landscaping_type,omitempty"`
HasPool *bool `json:"has_pool,omitempty"`
HasSprinkler *bool `json:"has_sprinkler_system,omitempty"`
HasSeptic *bool `json:"has_septic,omitempty"`
HasFireplace *bool `json:"has_fireplace,omitempty"`
HasGarage *bool `json:"has_garage,omitempty"`
HasBasement *bool `json:"has_basement,omitempty"`
HasAttic *bool `json:"has_attic,omitempty"`
PropertyType *string `json:"property_type,omitempty"`
HeatingType stringList `json:"heating_type,omitempty"`
CoolingType stringList `json:"cooling_type,omitempty"`
WaterHeaterType stringList `json:"water_heater_type,omitempty"`
RoofType stringList `json:"roof_type,omitempty"`
ExteriorType stringList `json:"exterior_type,omitempty"`
FlooringPrimary stringList `json:"flooring_primary,omitempty"`
LandscapingType stringList `json:"landscaping_type,omitempty"`
HasPool *bool `json:"has_pool,omitempty"`
HasSprinkler *bool `json:"has_sprinkler_system,omitempty"`
HasSeptic *bool `json:"has_septic,omitempty"`
HasFireplace *bool `json:"has_fireplace,omitempty"`
HasGarage *bool `json:"has_garage,omitempty"`
HasBasement *bool `json:"has_basement,omitempty"`
HasAttic *bool `json:"has_attic,omitempty"`
PropertyType stringList `json:"property_type,omitempty"`
// ClimateRegionID replaces the old task_tasktemplate_regions join table.
// Tag a template with the IECC zone ID it's relevant to (e.g. "Winterize
// Sprinkler" → zone 5/6). Residence.PostalCode is mapped to a region at
@@ -54,12 +91,12 @@ type templateConditions struct {
// isEmpty returns true if no conditions are set
func (c *templateConditions) isEmpty() bool {
return c.HeatingType == nil && c.CoolingType == nil && c.WaterHeaterType == nil &&
c.RoofType == nil && c.ExteriorType == nil && c.FlooringPrimary == nil &&
c.LandscapingType == nil && c.HasPool == nil && c.HasSprinkler == nil &&
return len(c.HeatingType) == 0 && len(c.CoolingType) == 0 && len(c.WaterHeaterType) == 0 &&
len(c.RoofType) == 0 && len(c.ExteriorType) == 0 && len(c.FlooringPrimary) == 0 &&
len(c.LandscapingType) == 0 && c.HasPool == nil && c.HasSprinkler == nil &&
c.HasSeptic == nil && c.HasFireplace == nil && c.HasGarage == nil &&
c.HasBasement == nil && c.HasAttic == nil &&
c.PropertyType == nil && c.ClimateRegionID == nil
len(c.PropertyType) == 0 && c.ClimateRegionID == nil
}
const (
@@ -75,8 +112,10 @@ const (
totalProfileFields = 15 // 14 home-profile fields + ZIP/region
)
// GetSuggestions returns task template suggestions scored against a residence's profile
func (s *SuggestionService) GetSuggestions(residenceID uint, userID uint) (*responses.TaskSuggestionsResponse, error) {
// GetSuggestions returns task template suggestions scored against a residence's
// profile. Match reasons are localized for display via the supplied localizer
// (nil falls back to English).
func (s *SuggestionService) GetSuggestions(residenceID uint, userID uint, localizer *goi18n.Localizer) (*responses.TaskSuggestionsResponse, error) {
// Check access
hasAccess, err := s.residenceRepo.HasAccess(residenceID, userID)
if err != nil {
@@ -112,7 +151,7 @@ func (s *SuggestionService) GetSuggestions(residenceID uint, userID uint) (*resp
suggestions = append(suggestions, responses.TaskSuggestionResponse{
Template: responses.NewTaskTemplateResponse(&templates[i]),
RelevanceScore: score,
MatchReasons: reasons,
MatchReasons: localizeReasons(localizer, reasons),
})
}
@@ -135,6 +174,38 @@ func (s *SuggestionService) GetSuggestions(residenceID uint, userID uint) (*resp
}, nil
}
// localizeReasons converts the internal reason codes emitted by scoreTemplate
// into human-readable, localized strings for the API response.
//
// Codes come in two shapes: a bare feature code ("has_fireplace") and a
// "field:value" pair ("heating_type:gas_furnace"); for the latter we key off
// the field only (the percentage already conveys strength, and a per-enum-value
// catalog would be a much larger surface). The "universal" and "partial_profile"
// signals are internal scoring artifacts, not user-facing reasons, so they're
// dropped. Any code without a translation falls back to English so a raw key
// can never leak to the UI.
func localizeReasons(localizer *goi18n.Localizer, codes []string) []string {
out := make([]string, 0, len(codes))
for _, code := range codes {
if code == "universal" || code == "partial_profile" {
continue
}
field := code
if i := strings.IndexByte(code, ':'); i >= 0 {
field = code[:i]
}
key := "suggestion.reason." + field
msg := i18n.T(localizer, key, nil)
if msg == key {
// Locale lacked the key — fall back to English so the user never
// sees a raw message id.
msg = i18n.T(i18n.NewLocalizer(i18n.DefaultLanguage), key, nil)
}
out = append(out, msg)
}
return out
}
// scoreTemplate scores a template against a residence profile.
// Returns (score, matchReasons, shouldInclude).
func (s *SuggestionService) scoreTemplate(tmpl *models.TaskTemplate, residence *models.Residence) (float64, []string, bool) {
@@ -157,76 +228,62 @@ func (s *SuggestionService) scoreTemplate(tmpl *models.TaskTemplate, residence *
reasons := make([]string, 0)
conditionCount := 0
// String field matches
if cond.HeatingType != nil {
// String field matches. Each condition is a set of allowed values; the
// residence matches when its value is one of them. A nil residence field is
// ignored (no penalty, no exclusion); a mismatch simply earns no bonus.
if len(cond.HeatingType) > 0 {
conditionCount++
if residence.HeatingType == nil {
// Field not set - ignore
} else if *residence.HeatingType == *cond.HeatingType {
if residence.HeatingType != nil && cond.HeatingType.contains(*residence.HeatingType) {
score += stringMatchBonus
reasons = append(reasons, "heating_type:"+*cond.HeatingType)
} else {
// Mismatch - don't exclude, just don't reward
reasons = append(reasons, "heating_type:"+*residence.HeatingType)
}
}
if cond.CoolingType != nil {
if len(cond.CoolingType) > 0 {
conditionCount++
if residence.CoolingType == nil {
// ignore
} else if *residence.CoolingType == *cond.CoolingType {
if residence.CoolingType != nil && cond.CoolingType.contains(*residence.CoolingType) {
score += stringMatchBonus
reasons = append(reasons, "cooling_type:"+*cond.CoolingType)
reasons = append(reasons, "cooling_type:"+*residence.CoolingType)
}
}
if cond.WaterHeaterType != nil {
if len(cond.WaterHeaterType) > 0 {
conditionCount++
if residence.WaterHeaterType == nil {
// ignore
} else if *residence.WaterHeaterType == *cond.WaterHeaterType {
if residence.WaterHeaterType != nil && cond.WaterHeaterType.contains(*residence.WaterHeaterType) {
score += stringMatchBonus
reasons = append(reasons, "water_heater_type:"+*cond.WaterHeaterType)
reasons = append(reasons, "water_heater_type:"+*residence.WaterHeaterType)
}
}
if cond.RoofType != nil {
if len(cond.RoofType) > 0 {
conditionCount++
if residence.RoofType == nil {
// ignore
} else if *residence.RoofType == *cond.RoofType {
if residence.RoofType != nil && cond.RoofType.contains(*residence.RoofType) {
score += stringMatchBonus
reasons = append(reasons, "roof_type:"+*cond.RoofType)
reasons = append(reasons, "roof_type:"+*residence.RoofType)
}
}
if cond.ExteriorType != nil {
if len(cond.ExteriorType) > 0 {
conditionCount++
if residence.ExteriorType == nil {
// ignore
} else if *residence.ExteriorType == *cond.ExteriorType {
if residence.ExteriorType != nil && cond.ExteriorType.contains(*residence.ExteriorType) {
score += stringMatchBonus
reasons = append(reasons, "exterior_type:"+*cond.ExteriorType)
reasons = append(reasons, "exterior_type:"+*residence.ExteriorType)
}
}
if cond.FlooringPrimary != nil {
if len(cond.FlooringPrimary) > 0 {
conditionCount++
if residence.FlooringPrimary == nil {
// ignore
} else if *residence.FlooringPrimary == *cond.FlooringPrimary {
if residence.FlooringPrimary != nil && cond.FlooringPrimary.contains(*residence.FlooringPrimary) {
score += stringMatchBonus
reasons = append(reasons, "flooring_primary:"+*cond.FlooringPrimary)
reasons = append(reasons, "flooring_primary:"+*residence.FlooringPrimary)
}
}
if cond.LandscapingType != nil {
if len(cond.LandscapingType) > 0 {
conditionCount++
if residence.LandscapingType == nil {
// ignore
} else if *residence.LandscapingType == *cond.LandscapingType {
if residence.LandscapingType != nil && cond.LandscapingType.contains(*residence.LandscapingType) {
score += stringMatchBonus
reasons = append(reasons, "landscaping_type:"+*cond.LandscapingType)
reasons = append(reasons, "landscaping_type:"+*residence.LandscapingType)
}
}
@@ -309,11 +366,11 @@ func (s *SuggestionService) scoreTemplate(tmpl *models.TaskTemplate, residence *
}
// Property type match
if cond.PropertyType != nil {
if len(cond.PropertyType) > 0 {
conditionCount++
if residence.PropertyType != nil && residence.PropertyType.Name == *cond.PropertyType {
if residence.PropertyType != nil && cond.PropertyType.contains(residence.PropertyType.Name) {
score += propertyTypeBonus
reasons = append(reasons, "property_type:"+*cond.PropertyType)
reasons = append(reasons, "property_type:"+residence.PropertyType.Name)
}
}
@@ -328,17 +385,22 @@ func (s *SuggestionService) scoreTemplate(tmpl *models.TaskTemplate, residence *
}
}
// Cap at 1.0
if score > 1.0 {
score = 1.0
}
// If template has conditions but no matches and no reasons, still include with low score
// If template has conditions but none matched (residence fields unset or
// different), rank it just below universal — it's a conditioned template we
// couldn't confirm applies.
if conditionCount > 0 && len(reasons) == 0 {
return baseUniversalScore * 0.5, []string{"partial_profile"}, true
}
return score, reasons, true
// A matched conditioned template must rank ABOVE a universal one. Anchor it
// at the universal baseline and add the accumulated match bonuses on top,
// so e.g. a single heating match (0.3 + 0.25) clearly beats universal (0.3).
final := baseUniversalScore + score
if final > 1.0 {
final = 1.0
}
return final, reasons, true
}
// CalculateProfileCompleteness returns how many of the 14 home profile fields are filled