i18n: backend-localized lookups, suggestions, and static data (10 languages)
- 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:
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/treytartt/honeydue-api/internal/config"
|
||||
"github.com/treytartt/honeydue-api/internal/i18n"
|
||||
)
|
||||
|
||||
// CacheService provides Redis caching functionality
|
||||
@@ -21,7 +22,7 @@ type CacheService struct {
|
||||
|
||||
var (
|
||||
cacheInstance *CacheService
|
||||
cacheOnce sync.Once
|
||||
cacheOnce sync.Once
|
||||
)
|
||||
|
||||
// NewCacheService creates a new cache service (thread-safe via sync.Once)
|
||||
@@ -133,7 +134,6 @@ func (c *CacheService) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// Static data cache helpers
|
||||
const (
|
||||
StaticDataKey = "static_data"
|
||||
@@ -191,9 +191,11 @@ func (c *CacheService) InvalidateAllLookups(ctx context.Context) error {
|
||||
LookupResidenceTypesKey,
|
||||
LookupSpecialtiesKey,
|
||||
LookupTaskTemplatesKey,
|
||||
StaticDataKey, // Also invalidate the combined static data
|
||||
SeededDataKey, // Invalidate unified seeded data
|
||||
SeededDataETagKey, // Invalidate seeded data ETag
|
||||
StaticDataKey, // Also invalidate the combined static data
|
||||
}
|
||||
// Per-locale seeded-data + ETag keys.
|
||||
for _, lang := range i18n.SupportedLanguages {
|
||||
keys = append(keys, seededDataKey(lang), seededDataETagKey(lang))
|
||||
}
|
||||
return c.Delete(ctx, keys...)
|
||||
}
|
||||
@@ -289,50 +291,64 @@ func (c *CacheService) InvalidateTaskTemplates(ctx context.Context) error {
|
||||
return c.Delete(ctx, LookupTaskTemplatesKey, StaticDataKey)
|
||||
}
|
||||
|
||||
// Unified seeded data cache helpers
|
||||
// Unified seeded data cache helpers.
|
||||
//
|
||||
// The seeded-data payload is localized (lookup display_name + home-profile
|
||||
// option labels), so the cache and ETag are namespaced per locale. Mixing
|
||||
// locales under one key would let the first request poison every other
|
||||
// language and make the ETag meaningless across locales.
|
||||
const (
|
||||
SeededDataKey = "seeded_data"
|
||||
SeededDataETagKey = "seeded_data:etag"
|
||||
SeededDataTTL = 24 * time.Hour
|
||||
seededDataPrefix = "seeded_data:"
|
||||
SeededDataTTL = 24 * time.Hour
|
||||
)
|
||||
|
||||
// CacheSeededData caches the unified seeded data and generates an ETag
|
||||
func (c *CacheService) CacheSeededData(ctx context.Context, data interface{}) (string, error) {
|
||||
func seededDataKey(locale string) string { return seededDataPrefix + locale }
|
||||
func seededDataETagKey(locale string) string { return seededDataPrefix + locale + ":etag" }
|
||||
|
||||
// CacheSeededData caches the unified seeded data for a locale and generates an
|
||||
// ETag. The locale is folded into the ETag so a client switching languages
|
||||
// always re-fetches rather than getting a stale 304.
|
||||
func (c *CacheService) CacheSeededData(ctx context.Context, locale string, data interface{}) (string, error) {
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to marshal seeded data: %w", err)
|
||||
}
|
||||
|
||||
// Generate FNV-64a ETag from the JSON data (faster than MD5, non-cryptographic)
|
||||
// FNV-64a ETag over locale + JSON (faster than MD5, non-cryptographic).
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(locale))
|
||||
h.Write([]byte{0})
|
||||
h.Write(jsonData)
|
||||
etag := fmt.Sprintf("\"%x\"", h.Sum64())
|
||||
|
||||
// Store both the data and the ETag
|
||||
if err := c.client.Set(ctx, SeededDataKey, jsonData, SeededDataTTL).Err(); err != nil {
|
||||
if err := c.client.Set(ctx, seededDataKey(locale), jsonData, SeededDataTTL).Err(); err != nil {
|
||||
return "", fmt.Errorf("failed to cache seeded data: %w", err)
|
||||
}
|
||||
|
||||
if err := c.client.Set(ctx, SeededDataETagKey, etag, SeededDataTTL).Err(); err != nil {
|
||||
if err := c.client.Set(ctx, seededDataETagKey(locale), etag, SeededDataTTL).Err(); err != nil {
|
||||
return "", fmt.Errorf("failed to cache seeded data etag: %w", err)
|
||||
}
|
||||
|
||||
return etag, nil
|
||||
}
|
||||
|
||||
// GetCachedSeededData retrieves cached unified seeded data
|
||||
func (c *CacheService) GetCachedSeededData(ctx context.Context, dest interface{}) error {
|
||||
return c.Get(ctx, SeededDataKey, dest)
|
||||
// GetCachedSeededData retrieves cached unified seeded data for a locale.
|
||||
func (c *CacheService) GetCachedSeededData(ctx context.Context, locale string, dest interface{}) error {
|
||||
return c.Get(ctx, seededDataKey(locale), dest)
|
||||
}
|
||||
|
||||
// GetSeededDataETag retrieves the cached ETag for seeded data
|
||||
func (c *CacheService) GetSeededDataETag(ctx context.Context) (string, error) {
|
||||
return c.GetString(ctx, SeededDataETagKey)
|
||||
// GetSeededDataETag retrieves the cached ETag for a locale's seeded data.
|
||||
func (c *CacheService) GetSeededDataETag(ctx context.Context, locale string) (string, error) {
|
||||
return c.GetString(ctx, seededDataETagKey(locale))
|
||||
}
|
||||
|
||||
// InvalidateSeededData removes cached seeded data and its ETag
|
||||
// InvalidateSeededData removes cached seeded data and ETags for every
|
||||
// supported locale (lookup data is locale-independent at the source, so a
|
||||
// change must clear all language variants).
|
||||
func (c *CacheService) InvalidateSeededData(ctx context.Context) error {
|
||||
return c.Delete(ctx, SeededDataKey, SeededDataETagKey)
|
||||
keys := make([]string, 0, len(i18n.SupportedLanguages)*2)
|
||||
for _, lang := range i18n.SupportedLanguages {
|
||||
keys = append(keys, seededDataKey(lang), seededDataETagKey(lang))
|
||||
}
|
||||
return c.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
// === User → Residence-IDs cache ===
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
|
||||
"github.com/treytartt/honeydue-api/internal/dto/responses"
|
||||
"github.com/treytartt/honeydue-api/internal/i18n"
|
||||
)
|
||||
|
||||
// lookup kinds — the message-key namespace for each localizable lookup type.
|
||||
const (
|
||||
lookupKindResidenceType = "residence_type"
|
||||
lookupKindTaskCategory = "task_category"
|
||||
lookupKindTaskPriority = "task_priority"
|
||||
lookupKindTaskFrequency = "task_frequency"
|
||||
lookupKindSpecialty = "contractor_specialty"
|
||||
lookupKindHomeProfile = "home_profile"
|
||||
lookupKindDocumentType = "document_type"
|
||||
lookupKindDocumentCat = "document_category"
|
||||
)
|
||||
|
||||
// documentTypeValues / documentCategoryValues are the stable client enum codes
|
||||
// (see iOS DocumentType/DocumentCategory). Display labels are localized at
|
||||
// request time. Order is presentation order.
|
||||
var documentTypeValues = []string{
|
||||
"warranty", "manual", "receipt", "inspection", "permit", "deed", "insurance", "contract", "photo", "other",
|
||||
}
|
||||
|
||||
var documentCategoryValues = []string{
|
||||
"appliance", "hvac", "plumbing", "electrical", "roofing", "structural", "landscaping", "general", "other",
|
||||
}
|
||||
|
||||
// localizedList maps a list of stable values to {value, localized display}.
|
||||
func localizedList(localizer *goi18n.Localizer, kind string, values []string) []HomeProfileOption {
|
||||
out := make([]HomeProfileOption, 0, len(values))
|
||||
for _, v := range values {
|
||||
out = append(out, HomeProfileOption{
|
||||
Value: v,
|
||||
DisplayName: localizeLookup(localizer, kind, v),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// BuildDocumentTypes returns localized document-type options.
|
||||
func BuildDocumentTypes(localizer *goi18n.Localizer) []HomeProfileOption {
|
||||
return localizedList(localizer, lookupKindDocumentType, documentTypeValues)
|
||||
}
|
||||
|
||||
// BuildDocumentCategories returns localized document-category options.
|
||||
func BuildDocumentCategories(localizer *goi18n.Localizer) []HomeProfileOption {
|
||||
return localizedList(localizer, lookupKindDocumentCat, documentCategoryValues)
|
||||
}
|
||||
|
||||
// lookupSlug normalizes a stable English lookup name (or option value) into a
|
||||
// message-key slug: lowercased, non-alphanumeric runs collapsed to "_".
|
||||
// "Pest Control" -> "pest_control", "Bi-Weekly" -> "bi_weekly", "tank_gas" ->
|
||||
// "tank_gas".
|
||||
func lookupSlug(name string) string {
|
||||
var b strings.Builder
|
||||
prevUnderscore := false
|
||||
for _, r := range strings.ToLower(strings.TrimSpace(name)) {
|
||||
switch {
|
||||
case (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9'):
|
||||
b.WriteRune(r)
|
||||
prevUnderscore = false
|
||||
default:
|
||||
if !prevUnderscore && b.Len() > 0 {
|
||||
b.WriteByte('_')
|
||||
prevUnderscore = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "_")
|
||||
}
|
||||
|
||||
// localizeLookup returns the localized display label for a lookup value.
|
||||
// Keys follow "lookup.<kind>.<slug>". If the locale lacks the key it falls back
|
||||
// to English, and ultimately to the original name so a raw key never surfaces.
|
||||
func localizeLookup(localizer *goi18n.Localizer, kind, name string) string {
|
||||
key := "lookup." + kind + "." + lookupSlug(name)
|
||||
msg := i18n.T(localizer, key, nil)
|
||||
if msg == key {
|
||||
msg = i18n.T(i18n.NewLocalizer(i18n.DefaultLanguage), key, nil)
|
||||
}
|
||||
if msg == key {
|
||||
// No translation anywhere — fall back to the stable English name.
|
||||
return name
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
// HomeProfileOption is a single selectable value for a home-profile field.
|
||||
type HomeProfileOption struct {
|
||||
Value string `json:"value"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
// homeProfileCatalog is the canonical set of home-profile field options,
|
||||
// mirroring the (previously hardcoded) iOS dropdowns. Order is presentation
|
||||
// order. Display labels are localized at request time via localizeLookup.
|
||||
var homeProfileCatalog = []struct {
|
||||
Field string
|
||||
Values []string
|
||||
}{
|
||||
{"heating_type", []string{"gas_furnace", "electric_furnace", "heat_pump", "boiler", "radiant", "other"}},
|
||||
{"cooling_type", []string{"central_ac", "window_ac", "heat_pump", "evaporative", "none", "other"}},
|
||||
{"water_heater_type", []string{"tank_gas", "tank_electric", "tankless_gas", "tankless_electric", "heat_pump", "solar", "other"}},
|
||||
{"roof_type", []string{"asphalt_shingle", "metal", "tile", "slate", "wood_shake", "flat", "other"}},
|
||||
{"exterior_type", []string{"brick", "vinyl_siding", "wood_siding", "stucco", "stone", "fiber_cement", "other"}},
|
||||
{"flooring_primary", []string{"hardwood", "laminate", "tile", "carpet", "vinyl", "concrete", "other"}},
|
||||
{"landscaping_type", []string{"lawn", "desert", "xeriscape", "garden", "mixed", "none", "other"}},
|
||||
}
|
||||
|
||||
// BuildHomeProfileOptions returns the home-profile field options with display
|
||||
// labels localized for the supplied localizer (nil falls back to English).
|
||||
func BuildHomeProfileOptions(localizer *goi18n.Localizer) map[string][]HomeProfileOption {
|
||||
out := make(map[string][]HomeProfileOption, len(homeProfileCatalog))
|
||||
for _, f := range homeProfileCatalog {
|
||||
opts := make([]HomeProfileOption, 0, len(f.Values))
|
||||
for _, v := range f.Values {
|
||||
opts = append(opts, HomeProfileOption{
|
||||
Value: v,
|
||||
DisplayName: localizeLookup(localizer, lookupKindHomeProfile, v),
|
||||
})
|
||||
}
|
||||
out[f.Field] = opts
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalizeLookups fills the DisplayName of each lookup slice in place, using the
|
||||
// supplied localizer. Mutates the passed slices.
|
||||
func LocalizeLookups(
|
||||
localizer *goi18n.Localizer,
|
||||
residenceTypes []responses.ResidenceTypeResponse,
|
||||
categories []responses.TaskCategoryResponse,
|
||||
priorities []responses.TaskPriorityResponse,
|
||||
frequencies []responses.TaskFrequencyResponse,
|
||||
specialties []responses.ContractorSpecialtyResponse,
|
||||
) {
|
||||
for i := range residenceTypes {
|
||||
residenceTypes[i].DisplayName = localizeLookup(localizer, lookupKindResidenceType, residenceTypes[i].Name)
|
||||
}
|
||||
for i := range categories {
|
||||
categories[i].DisplayName = localizeLookup(localizer, lookupKindTaskCategory, categories[i].Name)
|
||||
}
|
||||
for i := range priorities {
|
||||
priorities[i].DisplayName = localizeLookup(localizer, lookupKindTaskPriority, priorities[i].Name)
|
||||
}
|
||||
for i := range frequencies {
|
||||
frequencies[i].DisplayName = localizeLookup(localizer, lookupKindTaskFrequency, frequencies[i].Name)
|
||||
}
|
||||
for i := range specialties {
|
||||
specialties[i].DisplayName = localizeLookup(localizer, lookupKindSpecialty, specialties[i].Name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/treytartt/honeydue-api/internal/dto/responses"
|
||||
"github.com/treytartt/honeydue-api/internal/i18n"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Load the embedded translation bundle for the localization tests.
|
||||
_ = i18n.Init()
|
||||
}
|
||||
|
||||
func TestLookupSlug(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"Pest Control": "pest_control",
|
||||
"Bi-Weekly": "bi_weekly",
|
||||
"Semi-Annually": "semi_annually",
|
||||
"Mobile Home": "mobile_home",
|
||||
"HVAC": "hvac",
|
||||
"tank_gas": "tank_gas",
|
||||
"Tankless (Gas)": "tankless_gas",
|
||||
" Trailing/Punct ": "trailing_punct",
|
||||
}
|
||||
for in, want := range cases {
|
||||
assert.Equalf(t, want, lookupSlug(in), "slug(%q)", in)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalizeLookup_EnglishAndSpanish(t *testing.T) {
|
||||
en := i18n.NewLocalizer("en")
|
||||
es := i18n.NewLocalizer("es")
|
||||
|
||||
// Known value: localizes per locale.
|
||||
assert.Equal(t, "Plumbing", localizeLookup(en, lookupKindTaskCategory, "Plumbing"))
|
||||
assert.Equal(t, "Fontanería", localizeLookup(es, lookupKindTaskCategory, "Plumbing"))
|
||||
|
||||
// Frequency with separators (regression on the bi_weekly/semi_annually slug).
|
||||
assert.Equal(t, "Bi-Weekly", localizeLookup(en, lookupKindTaskFrequency, "Bi-Weekly"))
|
||||
assert.Equal(t, "Quincenal", localizeLookup(es, lookupKindTaskFrequency, "Bi-Weekly"))
|
||||
}
|
||||
|
||||
func TestLocalizeLookup_NilLocalizerFallsBackToEnglish(t *testing.T) {
|
||||
assert.Equal(t, "House", localizeLookup(nil, lookupKindResidenceType, "House"))
|
||||
}
|
||||
|
||||
func TestLocalizeLookup_UnknownValueFallsBackToName(t *testing.T) {
|
||||
// No translation key exists -> return the stable English name, never a key.
|
||||
got := localizeLookup(i18n.NewLocalizer("es"), lookupKindTaskCategory, "Totally Unknown Value")
|
||||
assert.Equal(t, "Totally Unknown Value", got)
|
||||
}
|
||||
|
||||
func TestBuildHomeProfileOptions(t *testing.T) {
|
||||
opts := BuildHomeProfileOptions(i18n.NewLocalizer("es"))
|
||||
|
||||
// All 7 fields present.
|
||||
for _, field := range []string{"heating_type", "cooling_type", "water_heater_type", "roof_type", "exterior_type", "flooring_primary", "landscaping_type"} {
|
||||
require.Containsf(t, opts, field, "missing field %s", field)
|
||||
require.NotEmpty(t, opts[field])
|
||||
}
|
||||
|
||||
// Values are stable; display_name is localized.
|
||||
heating := opts["heating_type"]
|
||||
assert.Equal(t, "gas_furnace", heating[0].Value)
|
||||
assert.Equal(t, "Calefactor de gas", heating[0].DisplayName)
|
||||
}
|
||||
|
||||
func TestLocalizeLookups_FillsDisplayName(t *testing.T) {
|
||||
cats := []responses.TaskCategoryResponse{{Name: "Plumbing"}, {Name: "HVAC"}}
|
||||
prios := []responses.TaskPriorityResponse{{Name: "High"}}
|
||||
freqs := []responses.TaskFrequencyResponse{{Name: "Monthly"}}
|
||||
specs := []responses.ContractorSpecialtyResponse{{Name: "Plumber"}}
|
||||
types := []responses.ResidenceTypeResponse{{Name: "House"}}
|
||||
|
||||
LocalizeLookups(i18n.NewLocalizer("es"), types, cats, prios, freqs, specs)
|
||||
|
||||
assert.Equal(t, "Fontanería", cats[0].DisplayName)
|
||||
assert.Equal(t, "Plumbing", cats[0].Name) // name stays stable
|
||||
assert.Equal(t, "Climatización", cats[1].DisplayName)
|
||||
assert.Equal(t, "Alta", prios[0].DisplayName)
|
||||
assert.Equal(t, "Mensual", freqs[0].DisplayName)
|
||||
assert.Equal(t, "Fontanero", specs[0].DisplayName)
|
||||
assert.Equal(t, "Casa", types[0].DisplayName)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -47,12 +47,12 @@ func TestSuggestionService_UniversalTemplate(t *testing.T) {
|
||||
// Create universal template (empty conditions)
|
||||
createTemplateWithConditions(t, service, "Change Air Filters", nil)
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Equal(t, "Change Air Filters", resp.Suggestions[0].Template.Title)
|
||||
assert.Equal(t, baseUniversalScore, resp.Suggestions[0].RelevanceScore)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "universal")
|
||||
assert.Empty(t, resp.Suggestions[0].MatchReasons) // universal templates carry no display reason
|
||||
}
|
||||
|
||||
func TestSuggestionService_HeatingTypeMatch(t *testing.T) {
|
||||
@@ -75,11 +75,47 @@ func TestSuggestionService_HeatingTypeMatch(t *testing.T) {
|
||||
"heating_type": "gas_furnace",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Equal(t, stringMatchBonus, resp.Suggestions[0].RelevanceScore)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "heating_type:gas_furnace")
|
||||
// Matched conditioned templates are anchored at the universal baseline and
|
||||
// earn bonuses on top, so a match always ranks above a universal template.
|
||||
assert.Equal(t, baseUniversalScore+stringMatchBonus, resp.Suggestions[0].RelevanceScore)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your heating system")
|
||||
}
|
||||
|
||||
// TestSuggestionService_StringConditionArrayForm is the regression test for the
|
||||
// scorer bug where conditions encoded as an array of allowed values
|
||||
// (`{"heating_type":["gas_furnace","boiler"]}`, the format used by the seeded
|
||||
// template catalog) failed to unmarshal into a scalar *string field and the
|
||||
// template silently collapsed to "universal". The residence's value must match
|
||||
// when it is any member of the array.
|
||||
func TestSuggestionService_StringConditionArrayForm(t *testing.T) {
|
||||
service := setupSuggestionService(t)
|
||||
user := testutil.CreateTestUser(t, service.db, "owner", "owner@test.com", "password")
|
||||
|
||||
heatingType := "boiler" // second value in the allowed list
|
||||
residence := &models.Residence{
|
||||
OwnerID: user.ID,
|
||||
Name: "Boiler House",
|
||||
IsActive: true,
|
||||
IsPrimary: true,
|
||||
HeatingType: &heatingType,
|
||||
}
|
||||
require.NoError(t, service.db.Create(residence).Error)
|
||||
|
||||
// Array-of-allowed-values form, exactly as the seed catalog stores it.
|
||||
createTemplateWithConditions(t, service, "Test Gas Shutoffs", map[string]interface{}{
|
||||
"heating_type": []string{"gas_furnace", "boiler"},
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Must MATCH (not fall back to universal) and rank above the universal baseline.
|
||||
assert.Equal(t, baseUniversalScore+stringMatchBonus, resp.Suggestions[0].RelevanceScore)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your heating system")
|
||||
assert.Len(t, resp.Suggestions[0].MatchReasons, 1)
|
||||
}
|
||||
|
||||
func TestSuggestionService_ExcludedWhenPoolRequiredButFalse(t *testing.T) {
|
||||
@@ -94,7 +130,7 @@ func TestSuggestionService_ExcludedWhenPoolRequiredButFalse(t *testing.T) {
|
||||
"has_pool": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0) // Should be excluded
|
||||
}
|
||||
@@ -111,11 +147,11 @@ func TestSuggestionService_NilFieldIgnored(t *testing.T) {
|
||||
"heating_type": "gas_furnace",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Should be included (not excluded) but with low partial score
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "partial_profile")
|
||||
assert.Empty(t, resp.Suggestions[0].MatchReasons) // conditioned-but-unmatched carries no display reason
|
||||
}
|
||||
|
||||
func TestSuggestionService_ProfileCompleteness(t *testing.T) {
|
||||
@@ -140,7 +176,7 @@ func TestSuggestionService_ProfileCompleteness(t *testing.T) {
|
||||
// Create at least one template so we get a response
|
||||
createTemplateWithConditions(t, service, "Universal Task", nil)
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
// 4 fields filled out of 15 (home-profile fields + ZIP/region)
|
||||
expectedCompleteness := 4.0 / float64(totalProfileFields)
|
||||
@@ -176,7 +212,7 @@ func TestSuggestionService_SortedByScoreDescending(t *testing.T) {
|
||||
"has_pool": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 3)
|
||||
|
||||
@@ -193,7 +229,7 @@ func TestSuggestionService_AccessDenied(t *testing.T) {
|
||||
|
||||
residence := testutil.CreateTestResidence(t, service.db, owner.ID, "Private House")
|
||||
|
||||
_, err := service.GetSuggestions(residence.ID, stranger.ID)
|
||||
_, err := service.GetSuggestions(residence.ID, stranger.ID, nil)
|
||||
require.Error(t, err)
|
||||
testutil.AssertAppErrorCode(t, err, 403)
|
||||
}
|
||||
@@ -222,12 +258,13 @@ func TestSuggestionService_MultipleConditionsAllMustMatch(t *testing.T) {
|
||||
"heating_type": "gas_furnace",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
|
||||
// All three conditions matched
|
||||
expectedScore := boolMatchBonus + boolMatchBonus + stringMatchBonus // 0.3 + 0.3 + 0.25 = 0.85
|
||||
// All three conditions matched. Anchored baseline (0.3) + 0.3 + 0.3 + 0.25
|
||||
// = 1.15, capped at 1.0.
|
||||
expectedScore := 1.0
|
||||
assert.InDelta(t, expectedScore, resp.Suggestions[0].RelevanceScore, 0.01)
|
||||
assert.Len(t, resp.Suggestions[0].MatchReasons, 3)
|
||||
}
|
||||
@@ -248,7 +285,7 @@ func TestSuggestionService_MalformedConditions(t *testing.T) {
|
||||
err := service.db.Create(tmpl).Error
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Should be treated as universal
|
||||
@@ -270,7 +307,7 @@ func TestSuggestionService_NullConditions(t *testing.T) {
|
||||
err := service.db.Create(tmpl).Error
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Equal(t, baseUniversalScore, resp.Suggestions[0].RelevanceScore)
|
||||
@@ -304,10 +341,10 @@ func TestSuggestionService_PropertyTypeMatch(t *testing.T) {
|
||||
"property_type": "House",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "property_type:House")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Recommended for your property type")
|
||||
}
|
||||
|
||||
// === CalculateProfileCompleteness with fully filled profile ===
|
||||
@@ -392,7 +429,7 @@ func TestSuggestionService_ScoreCappedAtOne(t *testing.T) {
|
||||
"has_garage": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.LessOrEqual(t, resp.Suggestions[0].RelevanceScore, 1.0)
|
||||
@@ -409,7 +446,7 @@ func TestSuggestionService_InactiveTemplateExcluded(t *testing.T) {
|
||||
err := service.db.Exec("INSERT INTO task_tasktemplate (title, is_active, conditions, created_at, updated_at) VALUES ('Inactive Task', false, '{}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)").Error
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -425,7 +462,7 @@ func TestSuggestionService_ExcludedWhenSprinklerRequired(t *testing.T) {
|
||||
"has_sprinkler_system": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -441,7 +478,7 @@ func TestSuggestionService_ExcludedWhenSepticRequired(t *testing.T) {
|
||||
"has_septic": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -455,7 +492,7 @@ func TestSuggestionService_ExcludedWhenFireplaceRequired(t *testing.T) {
|
||||
"has_fireplace": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -469,7 +506,7 @@ func TestSuggestionService_ExcludedWhenGarageRequired(t *testing.T) {
|
||||
"has_garage": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -483,7 +520,7 @@ func TestSuggestionService_ExcludedWhenBasementRequired(t *testing.T) {
|
||||
"has_basement": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -497,7 +534,7 @@ func TestSuggestionService_ExcludedWhenAtticRequired(t *testing.T) {
|
||||
"has_attic": true,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resp.Suggestions, 0)
|
||||
}
|
||||
@@ -523,10 +560,10 @@ func TestSuggestionService_CoolingTypeMatch(t *testing.T) {
|
||||
"cooling_type": "central_ac",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "cooling_type:central_ac")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your cooling system")
|
||||
}
|
||||
|
||||
func TestSuggestionService_WaterHeaterTypeMatch(t *testing.T) {
|
||||
@@ -548,10 +585,10 @@ func TestSuggestionService_WaterHeaterTypeMatch(t *testing.T) {
|
||||
"water_heater_type": "tank_gas",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "water_heater_type:tank_gas")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your water heater")
|
||||
}
|
||||
|
||||
func TestSuggestionService_ExteriorTypeMatch(t *testing.T) {
|
||||
@@ -573,10 +610,10 @@ func TestSuggestionService_ExteriorTypeMatch(t *testing.T) {
|
||||
"exterior_type": "brick",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "exterior_type:brick")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your exterior")
|
||||
}
|
||||
|
||||
func TestSuggestionService_FlooringPrimaryMatch(t *testing.T) {
|
||||
@@ -598,10 +635,10 @@ func TestSuggestionService_FlooringPrimaryMatch(t *testing.T) {
|
||||
"flooring_primary": "hardwood",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "flooring_primary:hardwood")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your flooring")
|
||||
}
|
||||
|
||||
func TestSuggestionService_LandscapingTypeMatch(t *testing.T) {
|
||||
@@ -623,10 +660,10 @@ func TestSuggestionService_LandscapingTypeMatch(t *testing.T) {
|
||||
"landscaping_type": "lawn",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "landscaping_type:lawn")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your landscaping")
|
||||
}
|
||||
|
||||
func TestSuggestionService_RoofTypeMatch(t *testing.T) {
|
||||
@@ -648,10 +685,10 @@ func TestSuggestionService_RoofTypeMatch(t *testing.T) {
|
||||
"roof_type": "asphalt_shingle",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "roof_type:asphalt_shingle")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your roof")
|
||||
}
|
||||
|
||||
// === Mismatch on string field — no score for that field ===
|
||||
@@ -676,11 +713,11 @@ func TestSuggestionService_HeatingTypeMismatch(t *testing.T) {
|
||||
"heating_type": "gas_furnace",
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Should still be included but with partial_profile (no match, no exclude)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "partial_profile")
|
||||
assert.Empty(t, resp.Suggestions[0].MatchReasons) // conditioned-but-unmatched carries no display reason
|
||||
}
|
||||
|
||||
// === templateConditions.isEmpty ===
|
||||
@@ -689,16 +726,14 @@ func TestTemplateConditions_IsEmpty(t *testing.T) {
|
||||
cond := &templateConditions{}
|
||||
assert.True(t, cond.isEmpty())
|
||||
|
||||
ht := "gas"
|
||||
cond2 := &templateConditions{HeatingType: &ht}
|
||||
cond2 := &templateConditions{HeatingType: stringList{"gas"}}
|
||||
assert.False(t, cond2.isEmpty())
|
||||
|
||||
pool := true
|
||||
cond3 := &templateConditions{HasPool: &pool}
|
||||
assert.False(t, cond3.isEmpty())
|
||||
|
||||
pt := "House"
|
||||
cond4 := &templateConditions{PropertyType: &pt}
|
||||
cond4 := &templateConditions{PropertyType: stringList{"House"}}
|
||||
assert.False(t, cond4.isEmpty())
|
||||
|
||||
var regionID uint = 5
|
||||
@@ -727,11 +762,11 @@ func TestSuggestionService_ClimateRegionMatch(t *testing.T) {
|
||||
"climate_region_id": 5,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
assert.InDelta(t, climateRegionBonus, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "climate_region")
|
||||
assert.InDelta(t, baseUniversalScore+climateRegionBonus, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Recommended for your climate")
|
||||
}
|
||||
|
||||
func TestSuggestionService_ClimateRegionMismatch(t *testing.T) {
|
||||
@@ -753,11 +788,11 @@ func TestSuggestionService_ClimateRegionMismatch(t *testing.T) {
|
||||
"climate_region_id": 6,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1) // Still included — mismatch doesn't exclude
|
||||
assert.InDelta(t, baseUniversalScore*0.5, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "partial_profile")
|
||||
assert.Empty(t, resp.Suggestions[0].MatchReasons) // conditioned-but-unmatched carries no display reason
|
||||
}
|
||||
|
||||
func TestSuggestionService_ClimateRegionIgnoredWhenNoZip(t *testing.T) {
|
||||
@@ -779,7 +814,7 @@ func TestSuggestionService_ClimateRegionIgnoredWhenNoZip(t *testing.T) {
|
||||
"climate_region_id": 5,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1) // Still included, just no bonus
|
||||
assert.InDelta(t, baseUniversalScore*0.5, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
@@ -802,11 +837,11 @@ func TestSuggestionService_ClimateRegionUnknownZip(t *testing.T) {
|
||||
"climate_region_id": 5,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Unknown ZIP → 0 region → no match, but no crash
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "partial_profile")
|
||||
assert.Empty(t, resp.Suggestions[0].MatchReasons) // conditioned-but-unmatched carries no display reason
|
||||
}
|
||||
|
||||
func TestSuggestionService_ClimateRegionStacksWithOtherConditions(t *testing.T) {
|
||||
@@ -829,11 +864,11 @@ func TestSuggestionService_ClimateRegionStacksWithOtherConditions(t *testing.T)
|
||||
"climate_region_id": 5,
|
||||
})
|
||||
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID)
|
||||
resp, err := service.GetSuggestions(residence.ID, user.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Suggestions, 1)
|
||||
// Both bonuses should apply: stringMatchBonus + climateRegionBonus
|
||||
assert.InDelta(t, stringMatchBonus+climateRegionBonus, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "heating_type:gas_furnace")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "climate_region")
|
||||
assert.InDelta(t, baseUniversalScore+stringMatchBonus+climateRegionBonus, resp.Suggestions[0].RelevanceScore, 0.001)
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Matches your heating system")
|
||||
assert.Contains(t, resp.Suggestions[0].MatchReasons, "Recommended for your climate")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user