diff --git a/backend/app/api/outfits.py b/backend/app/api/outfits.py index 7583cbee6..109c1de62 100644 --- a/backend/app/api/outfits.py +++ b/backend/app/api/outfits.py @@ -1,7 +1,7 @@ import logging from datetime import date, datetime from typing import Annotated -from uuid import UUID +from uuid import UUID, uuid4 from fastapi import APIRouter, Depends, HTTPException, Query, status from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, computed_field, field_validator @@ -12,7 +12,7 @@ from app.api.pagination import PaginationParams from app.config import get_settings from app.database import DbSession -from app.models.item import ClothingItem +from app.models.item import ClothingItem, ItemStatus from app.models.outfit import ( FamilyOutfitRating, Outfit, @@ -38,6 +38,7 @@ AIRecommendationError, InsufficientWardrobeError, RecommendationService, + warmer_layer_can_come_off, ) from app.services.studio_service import ( ItemOwnershipError, @@ -48,6 +49,7 @@ from app.services.suggestion_cache import clear_suggestions from app.services.weather_service import WeatherData from app.utils.auth import get_current_user +from app.utils.clothing import covered_regions from app.utils.rate_limit import rate_limit_by_user from app.utils.scales import RATING_MAX, RATING_MIN from app.utils.signed_urls import sign_optional @@ -122,6 +124,27 @@ def thumbnail_url(self) -> str | None: return sign_optional(self.thumbnail_path) +class OutfitExtraItemResponse(BaseModel): + id: UUID + type: str + subtype: str | None = None + name: str | None = None + primary_color: str | None = None + colors: list[str] = [] + image_path: str | None = None + thumbnail_path: str | None = None + + @computed_field + @property + def image_url(self) -> str | None: + return sign_optional(self.image_path) + + @computed_field + @property + def thumbnail_url(self) -> str | None: + return sign_optional(self.thumbnail_path) + + class WoreInsteadItem(BaseModel): id: UUID type: str @@ -175,6 +198,8 @@ class OutfitResponse(BaseModel): highlights: list[str] | None = None weather: dict | None = None items: list[OutfitItemResponse] + if_cooler: OutfitExtraItemResponse | None = None + if_warmer: OutfitExtraItemResponse | None = None feedback: FeedbackSummary | None = None family_ratings: list[FamilyRatingResponse] | None = None family_rating_average: float | None = None @@ -341,6 +366,42 @@ async def fetch_wore_instead_items_map( return wore_instead_map +def _extra_item_response(item: ClothingItem | None) -> OutfitExtraItemResponse | None: + if item is None: + return None + return OutfitExtraItemResponse( + id=item.id, + type=item.type, + subtype=item.subtype, + name=item.name, + primary_color=item.primary_color, + colors=item.colors or [], + image_path=item.image_path, + thumbnail_path=item.thumbnail_path, + ) + + +def _extra_is_available(item: ClothingItem) -> bool: + return item.status == ItemStatus.ready and not item.is_archived + + +# Stand-ins for the wardrobe's pieces: the response has no candidate pool to ask which regions +# the wardrobe can dress, so an outfit is held to covering the upper and lower body, and the +# feet when it has shoes now. +_REGION_STAND_INS = {"upper": "t-shirt", "lower": "jeans", "feet": "sneakers"} + + +def _completeness_type_map(outfit: Outfit) -> dict[UUID, str]: + type_map = { + outfit_item.item_id: (outfit_item.item.type or "").lower() for outfit_item in outfit.items + } + worn = covered_regions(list(type_map), type_map) + for region, item_type in _REGION_STAND_INS.items(): + if region != "feet" or "feet" in worn: + type_map[uuid4()] = item_type + return type_map + + def outfit_to_response( outfit: Outfit, wore_instead_items_map: dict[str, list[WoreInsteadItem]] | None = None, @@ -364,6 +425,23 @@ def outfit_to_response( ) ) + # The outfit's items can change after the AI named its extras (studio edits), so an extra + # that no longer fits is hidden rather than shown wrongly. + # Likewise an extra archived or not ready since, and a warmer layer the outfit now needs. + outfit_item_ids = [outfit_item.item_id for outfit_item in outfit.items] + if_cooler = outfit.if_cooler_item + if if_cooler is not None and ( + if_cooler.id in outfit_item_ids or not _extra_is_available(if_cooler) + ): + if_cooler = None + if_warmer = outfit.if_warmer_item + if if_warmer is not None: + type_map = _completeness_type_map(outfit) + if not _extra_is_available(if_warmer) or not warmer_layer_can_come_off( + if_warmer.id, outfit_item_ids, type_map + ): + if_warmer = None + feedback_summary = None if outfit.feedback: wore_instead = None @@ -423,6 +501,8 @@ def outfit_to_response( highlights=highlights, weather=outfit.weather_data, items=items, + if_cooler=_extra_item_response(if_cooler), + if_warmer=_extra_item_response(if_warmer), feedback=feedback_summary, family_ratings=family_ratings_list, family_rating_average=family_rating_average, diff --git a/backend/app/models/outfit.py b/backend/app/models/outfit.py index 6d2b50890..6affd6b12 100644 --- a/backend/app/models/outfit.py +++ b/backend/app/models/outfit.py @@ -93,6 +93,21 @@ class Outfit(Base): name: Mapped[str | None] = mapped_column(String(100), nullable=True) + # Weather-aware extras the AI may name: a wardrobe layer to add if it gets cooler, and one + # of the outfit's own layers to take off if it warms up. Both are validated before saving. + if_cooler_item_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), + ForeignKey("clothing_items.id", ondelete="SET NULL"), + nullable=True, + index=True, + ) + if_warmer_item_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), + ForeignKey("clothing_items.id", ondelete="SET NULL"), + nullable=True, + index=True, + ) + replaces_outfit_id: Mapped[uuid.UUID | None] = mapped_column( UUID(as_uuid=True), ForeignKey("outfits.id", ondelete="SET NULL"), @@ -129,6 +144,13 @@ class Outfit(Base): source_item: Mapped[Optional["ClothingItem"]] = relationship( "ClothingItem", foreign_keys=[source_item_id] ) + # Loaded with the outfit, so every query that serializes one includes the extras. + if_cooler_item: Mapped[Optional["ClothingItem"]] = relationship( + "ClothingItem", foreign_keys=[if_cooler_item_id], lazy="selectin" + ) + if_warmer_item: Mapped[Optional["ClothingItem"]] = relationship( + "ClothingItem", foreign_keys=[if_warmer_item_id], lazy="selectin" + ) replaces: Mapped[Optional["Outfit"]] = relationship( "Outfit", foreign_keys=[replaces_outfit_id], diff --git a/backend/app/prompts/recommendation.txt b/backend/app/prompts/recommendation.txt index 9e7124620..bad37e939 100644 --- a/backend/app/prompts/recommendation.txt +++ b/backend/app/prompts/recommendation.txt @@ -5,6 +5,7 @@ CONTEXT: - Time of day: {time_of_day} - Weather: {temperature}°C (feels like {feels_like}°C), {condition}, {precipitation_chance}% chance of rain {temp_range_text} +{weather_details_text} - Items are pre-ranked by suitability. Higher-numbered items are less compatible — prefer items near the top of the list. {preferences_text} @@ -21,6 +22,7 @@ Texture and fabric: - Do not double the same texture (two shiny pieces, two heavy knits, two identical weaves) - Heavier and rougher fabrics read more casual; lighter and refined fabrics read more polished - Match fabric weight to weather — linen and cotton for warmth, wool and knit for cold +- Match footwear weight to the weather: light, breathable shoes when warm; heavier, closed shoes when cold or wet. Each footwear item lists its weight (light, medium or heavy) Proportion and silhouette: - Balance volume: if the top is relaxed or oversized, the bottom should be more fitted, and vice versa @@ -52,13 +54,21 @@ RULES: - Suit: ONE top + ONE suit (<>) + ONE footwear; the suit replaces the bottom - OPTIONAL: legwear (<>) under a skirt, dress or shorts in cool or cold weather; leave it out when it is warm, and put only thermal legwear under trousers or a jumpsuit, only when it is very cold. Legwear does not replace the bottom, the one-piece garment or footwear - OPTIONAL: ONE bag if appropriate for the occasion -- OPTIONAL: accessories (belt, scarf, hat, watch, jewelry) that genuinely complement the outfit +- OPTIONAL: accessories (belt, scarf, watch, jewelry) that genuinely complement the outfit +- Add a hat only if it suits the outfit's style and the weather calls for it: a cap or sun hat when the UV index is 6 or higher, a warm hat (beanie, wool cap) when it is cold (about 8°C or below) or windy. Never add a hat just to complete the look - For cold or rainy weather, add outerwear (jacket/coat) if available - Every piece must earn its place — do not add items just to fill slots - Do NOT pick the same item number twice - Return item NUMBERS only +WEATHER EXTRAS (optional, per outfit): +- "if_cooler": the number of ONE extra layer (<>, <>) from AVAILABLE ITEMS that is NOT in this outfit, to add if it gets cooler. It must match the outfit's style and colours and must not be an item already in the outfit +- "if_warmer": the number of ONE layer that IS in this outfit (a jacket, coat, blazer, cardigan, hoodie or vest) that can come off if it warms up. The outfit must still be complete and look good without it +- Suggest "if_cooler" for every outfit whenever a fitting layer exists, so the person always knows how to cover up if the weather turns; use null only on a clearly hot day (feels like about 26°C or more all day) or when no layer fits the style +- Suggest "if_warmer" whenever the outfit has a removable layer and it could get warmer during the day; use null otherwise +- Never invent an item to fill them + Respond with valid JSON containing exactly 3 distinct outfit options. Each must be a complete look. -{{"outfits": [{{"items": [item numbers], "headline": "Short catchy outfit title (max 5 words)", "highlights": ["One short sentence each — vary your reasoning across color, texture, proportion, occasion, weather, or time of day"], "styling_tip": "One specific, actionable styling detail — do not suggest rolling up sleeves every time, vary your advice"}}, ...]}} +{{"outfits": [{{"items": [item numbers], "headline": "Short catchy outfit title (max 5 words)", "highlights": ["One short sentence each — vary your reasoning across color, texture, proportion, occasion, weather, or time of day"], "styling_tip": "One specific, actionable styling detail — do not suggest rolling up sleeves every time, vary your advice", "if_cooler": item number or null, "if_warmer": item number or null}}, ...]}} Each outfit MUST use different key pieces (different tops, bottoms, one-piece garments or suits). Vary color palettes and energy levels. First outfit = strongest recommendation. \ No newline at end of file diff --git a/backend/app/services/item_scorer.py b/backend/app/services/item_scorer.py index 7267ffee9..bae6131db 100644 --- a/backend/app/services/item_scorer.py +++ b/backend/app/services/item_scorer.py @@ -1,3 +1,4 @@ +import re from dataclasses import dataclass from datetime import date from math import prod @@ -71,6 +72,10 @@ def get_season(month: int, latitude: float | None = None) -> str: # when a whole category scores below the TOP_N cut and would otherwise be sliced away. ESSENTIAL_ROLES = ("footwear", "bottom") MIN_CANDIDATES_PER_ESSENTIAL_ROLE = 4 +# Layers are not essential, but the stylist can only offer a layer for a cold spell (if_cooler) +# from the numbered prompt list, so a few must survive the cut. +LAYER_FLOOR_ROLES = ("mid_layer", "outer_layer") +MIN_CANDIDATES_PER_LAYER_ROLE = 2 TEMP_RANGE_MIN_SWING = 8.0 REMOVABLE_LAYER_HOT_FLOOR = 0.6 @@ -95,6 +100,139 @@ def get_season(month: int, latitude: float | None = None) -> str: } +# Footwear weight: how warm and bulky a shoe is, so an "all-season" chunky leather sneaker +# is not treated like a knit one. See footwear_weight for the precedence of the rules. +FOOTWEAR_LIGHT = "light" +FOOTWEAR_MEDIUM = "medium" +FOOTWEAR_HEAVY = "heavy" + +# Matched against the lowercased subtype, name and ai_description as whole words or phrases. +HEAVY_FOOTWEAR_KEYWORDS = ( + "high-top", + "high top", + "hi-top", + "hi top", + "lined", + "shearling", + "sherpa", + "fur", + "fleece", + "wool", + "insulated", +) +LIGHT_FOOTWEAR_KEYWORDS = ( + "sandal", + "espadrille", + "slide", + "slides", + "flip-flop", + "flip flop", + "canvas", + "knit", + "knitted", + "mesh", + "linen", + "breathable", +) +# Bulk alone is only "heavy" together with leather or suede; next to a light upper it just +# keeps the shoe from counting as light. +BULKY_FOOTWEAR_KEYWORDS = ("chunky", "platform", "thick sole", "lug sole") +HEAVY_FOOTWEAR_MATERIALS = {"wool", "fleece", "shearling"} +LIGHT_FOOTWEAR_MATERIALS = {"canvas", "linen", "knit"} +BULKY_HEAVY_MATERIALS = {"leather", "suede"} +LIGHT_FOOTWEAR_TYPES = {"sandals"} + +# Footwear is judged a few degrees below the clothing hot threshold, because feet overheat in +# heavy shoes before the day counts as hot (a 22.6C day feeling like 24C is already warm). +WARM_FOOTWEAR_MARGIN = 3 +HEAVY_FOOTWEAR_WARM_FACTOR = 0.4 +MEDIUM_FOOTWEAR_WARM_FACTOR = 0.85 +LIGHT_FOOTWEAR_COLD_FACTOR = 0.8 + + +def _has_keyword(text: str, keywords: tuple[str, ...]) -> bool: + return any(re.search(rf"(? str | None: + """Classify a shoe as light, medium or heavy; None for anything that is not footwear. + + Precedence: boots are always heavy; then heavy signals (high-top, lined, fur, wool, + fleece, seasons tagged winter only, chunky leather or suede); then light signals (sandals, + espadrilles, slides, canvas, knit, mesh, linen, seasons tagged summer and/or spring only). A light shoe that + is also chunky is medium. Everything else is medium. + """ + item_type = (item.type or "").lower() + if ITEM_ROLE.get(item_type) != "footwear": + return None + + material = (item.material or "").lower() + seasons = set(item.season or []) + text = " ".join(part.lower() for part in (item.subtype, item.name, item.ai_description) if part) + # "unlined" is the opposite of lined, so it must not match as a heavy signal. + text = re.sub(r"\bun-?lined\b", "", text) + bulky = _has_keyword(text, BULKY_FOOTWEAR_KEYWORDS) + leathery = material in BULKY_HEAVY_MATERIALS or _has_keyword(text, ("leather", "suede")) + winter_only = seasons == {"winter"} + summer_only = bool(seasons) and seasons <= {"summer", "spring"} and "summer" in seasons + + if ( + item_type == "boots" + or material in HEAVY_FOOTWEAR_MATERIALS + or winter_only + or _has_keyword(text, HEAVY_FOOTWEAR_KEYWORDS) + or (bulky and leathery) + ): + return FOOTWEAR_HEAVY + + light = ( + item_type in LIGHT_FOOTWEAR_TYPES + or material in LIGHT_FOOTWEAR_MATERIALS + or summer_only + or _has_keyword(text, LIGHT_FOOTWEAR_KEYWORDS) + ) + if light and not bulky: + return FOOTWEAR_LIGHT + return FOOTWEAR_MEDIUM + + +def has_light_footwear(items: list[ClothingItem]) -> bool: + return any(footwear_weight(i) == FOOTWEAR_LIGHT for i in items) + + +def _footwear_reference_temps(weather: WeatherData) -> tuple[float, float]: + # Warmest and coolest reading to judge shoes against: the feels-like and the ends of a + # wide temperature range, because shoes are worn all day and a midpoint hides either end. + temp_range = scoring_temp_range(weather) + if temp_range is not None: + return max(weather.feels_like, temp_range[1]), min(weather.feels_like, temp_range[0]) + return ( + max(weather.temperature, weather.feels_like), + min(weather.temperature, weather.feels_like), + ) + + +def _footwear_weight_score( + item: ClothingItem, + weather: WeatherData, + preferences: UserPreference | None, + light_available: bool, +) -> float: + weight = footwear_weight(item) + if weight is None: + return 1.0 + cold_threshold, hot_threshold = _resolve_temp_thresholds(preferences) + warmest, coolest = _footwear_reference_temps(weather) + if warmest >= hot_threshold - WARM_FOOTWEAR_MARGIN: + if weight == FOOTWEAR_HEAVY: + return HEAVY_FOOTWEAR_WARM_FACTOR + if weight == FOOTWEAR_MEDIUM and light_available: + return MEDIUM_FOOTWEAR_WARM_FACTOR + elif coolest < cold_threshold and weight == FOOTWEAR_LIGHT: + return LIGHT_FOOTWEAR_COLD_FACTOR + return 1.0 + + @dataclass class ScoredItem: item: ClothingItem @@ -274,9 +412,11 @@ def _fit_factors( current_season: str, preferences: UserPreference | None, learned_prefs: dict | None, + light_footwear_available: bool = False, ) -> tuple[float, float, float, float]: return ( - _weather_score(item, weather, preferences), + _weather_score(item, weather, preferences) + * _footwear_weight_score(item, weather, preferences, light_footwear_available), _formality_score(item, occasion), _season_score(item, current_season, weather, preferences), _preference_score(item, preferences, learned_prefs), @@ -294,9 +434,19 @@ def rank_by_fit( # score_items leaves small wardrobes unscored, so filling a missing piece needs its own # ranking or it would fall back to database order. Most items tie on fit in mild # weather, so the least recently worn goes first to avoid adding the same piece every time. + light_available = has_light_footwear(items) + def key(item: ClothingItem) -> tuple[float, date]: fit = prod( - _fit_factors(item, weather, occasion, current_season, preferences, learned_prefs) + _fit_factors( + item, + weather, + occasion, + current_season, + preferences, + learned_prefs, + light_available, + ) ) return -fit, item.last_worn_at or date.min @@ -408,6 +558,25 @@ def _sort_mandatory_first( return sorted(scored, key=lambda s: s.item.id not in mandatory_item_ids) +def _reorder_footwear_by_weight( + scored: list[ScoredItem], weather: WeatherData, preferences: UserPreference | None +) -> list[ScoredItem]: + """Small wardrobes are not scored, but shoes still go lightest-first on a warm day. + + Only the footwear positions are rearranged (stable sort), every other item keeps its place. + """ + light_available = has_light_footwear([s.item for s in scored]) + slots = [i for i, s in enumerate(scored) if footwear_weight(s.item) is not None] + shoes = sorted( + (scored[i] for i in slots), + key=lambda s: -_footwear_weight_score(s.item, weather, preferences, light_available), + ) + result = list(scored) + for i, shoe in zip(slots, shoes, strict=True): + result[i] = shoe + return result + + def _role_of(scored_item: ScoredItem) -> str | None: return ITEM_ROLE.get((scored_item.item.type or "").lower()) @@ -426,8 +595,11 @@ def _ensure_role_diversity( tail = scored[top_n:] promoted: list[ScoredItem] = [] - for role in ESSENTIAL_ROLES: - missing = min_per_role - sum(1 for s in head if _role_of(s) == role) + floors = [(role, min_per_role) for role in ESSENTIAL_ROLES] + [ + (role, MIN_CANDIDATES_PER_LAYER_ROLE) for role in LAYER_FLOOR_ROLES + ] + for role, floor in floors: + missing = floor - sum(1 for s in head if _role_of(s) == role) if missing > 0: promoted.extend([s for s in tail if _role_of(s) == role][:missing]) @@ -477,7 +649,9 @@ def score_items( mandatory_item_ids: set[UUID] | None = None, ) -> list[ScoredItem]: if len(items) < MIN_ITEMS_FOR_SCORING: - scored = [ScoredItem(item=item) for item in items] + scored = _reorder_footwear_by_weight( + [ScoredItem(item=item) for item in items], weather, preferences + ) return _sort_mandatory_first(scored, mandatory_item_ids) avoid_days = DEFAULT_AVOID_REPEAT_DAYS @@ -495,10 +669,11 @@ def score_items( ) median_wear = median([i.wear_count or 0 for i in items]) if use_underused and items else 0 + light_available = has_light_footwear(items) scored = [] for item in items: ws, fs, ss, ps = _fit_factors( - item, weather, occasion, current_season, preferences, learned_prefs + item, weather, occasion, current_season, preferences, learned_prefs, light_available ) rs = _recency_score(item, user_today, avoid_days, recently_worn_dates) us = _usage_score(item, median_wear) if use_underused else 1.0 diff --git a/backend/app/services/recommendation_service.py b/backend/app/services/recommendation_service.py index b0b4c5d5d..1901f8ab7 100644 --- a/backend/app/services/recommendation_service.py +++ b/backend/app/services/recommendation_service.py @@ -25,6 +25,8 @@ from app.models.user import User from app.services.ai_service import AIResponseTruncatedError, AIService, require_internal_ai from app.services.item_scorer import ( + REMOVABLE_LAYER_TYPES, + footwear_weight, get_season, rain_likely, rank_by_fit, @@ -41,6 +43,7 @@ WeatherServiceError, ) from app.utils.clothing import ( + LAYER_ROLES, can_complete_outfit, canonical_item_order, deduplicate_by_body_slot, @@ -49,7 +52,7 @@ missing_regions, remove_legwear, ) -from app.utils.garment_vocabulary import render_outfit_prompt +from app.utils.garment_vocabulary import ITEM_ROLE, render_outfit_prompt from app.utils.preference_defaults import ( DEFAULT_LAYERING_PREFERENCE, DEFAULT_TEMPERATURE_SENSITIVITY, @@ -70,9 +73,12 @@ '"highlights": ["One short sentence each — vary your reasoning across color, texture, ' 'proportion, occasion, weather, or time of day"], ' '"styling_tip": "One specific, actionable styling detail — do not suggest rolling up ' - 'sleeves every time, vary your advice"}}' + 'sleeves every time, vary your advice", ' + '"if_cooler": item number or null, "if_warmer": item number or null}}' ) +WINDY_KMH = 25 + def get_time_of_day(user: User) -> TimeOfDay: hour = get_user_now(user).hour @@ -97,6 +103,130 @@ def format_temp_range_text(weather: WeatherData) -> str: ) +def format_weather_details_text(weather: WeatherData) -> str: + """UV index (now and the day's peak) and wind, so the prompt can judge hats and layers.""" + uv_now = weather.uv_index + parts = [f"UV index {uv_now:g}"] + if weather.uv_index_max is not None and weather.uv_index_max != uv_now: + parts[0] += f" now, up to {weather.uv_index_max:g} today" + if weather.wind_speed >= WINDY_KMH: + parts.append(f"windy ({weather.wind_speed:g} km/h)") + return "- " + ", ".join(parts) + + +def warmer_layer_can_come_off( + layer_id: UUID, item_ids: list[UUID], item_type_map: dict[UUID, str] +) -> bool: + """True when `layer_id` is a removable layer of the outfit and the rest is still complete. + + `item_type_map` must cover the whole candidate pool, because it decides which body regions + the wardrobe can fill (see `missing_regions`). + """ + item_type = item_type_map.get(layer_id, "") + remaining = [iid for iid in item_ids if iid != layer_id] + return ( + layer_id in item_ids + and (item_type in REMOVABLE_LAYER_TYPES or ITEM_ROLE.get(item_type) in LAYER_ROLES) + and has_wearable_piece(remaining, item_type_map) + and not missing_regions(remaining, item_type_map) + ) + + +def _describe_pick(value: object) -> str: + # Ids and types only: the raw AI value is arbitrary text and stays out of the logs. + if isinstance(value, int) and not isinstance(value, bool): + return f"number {value}" + return f"a {type(value).__name__} value" + + +def resolve_layer_extras( + outfit_data: dict, + number_map: dict[int, UUID], + item_type_map: dict[UUID, str], + item_ids: list[UUID], +) -> tuple[UUID | None, UUID | None]: + """Validate the AI's if_cooler / if_warmer picks; an invalid one is dropped (and logged). + + `item_type_map` holds only the candidates (ready, not archived, not excluded), so an item + outside it is never accepted. if_cooler must be a mid or outer layer that is not already in + the outfit; if_warmer must be a removable layer in the outfit, and the outfit must still be + complete without it. + """ + + def pick(key: str) -> UUID | None: + value = outfit_data.get(key) + if value is None: + return None + picked = picked_item_ids([value], number_map) + if len(picked) != 1 or picked[0] not in item_type_map: + logger.info(f"Dropping {key}: {_describe_pick(value)} is not an available item") + return None + return picked[0] + + in_outfit = set(item_ids) + if_cooler = pick("if_cooler") + if if_cooler is not None and ( + if_cooler in in_outfit or ITEM_ROLE.get(item_type_map[if_cooler]) not in LAYER_ROLES + ): + logger.info( + f"Dropping if_cooler {if_cooler} ({item_type_map[if_cooler]}): " + "in the outfit or not a mid/outer layer" + ) + if_cooler = None + + if_warmer = pick("if_warmer") + if if_warmer is not None and not warmer_layer_can_come_off(if_warmer, item_ids, item_type_map): + logger.info( + f"Dropping if_warmer {if_warmer} ({item_type_map[if_warmer]}): " + "not in the outfit, not removable or outfit incomplete without it" + ) + if_warmer = None + + return if_cooler, if_warmer + + +async def drop_unavailable_extras( + db: AsyncSession, user_id: UUID, extras: tuple[UUID | None, UUID | None] +) -> tuple[UUID | None, UUID | None]: + """Re-check the extras against the database: an item archived, deleted, still processing + or excluded since the candidates were loaded must not be saved.""" + wanted = {e for e in extras if e is not None} + if not wanted: + return extras + rows = await db.execute( + select(ClothingItem.id).where( + ClothingItem.id.in_(wanted), + ClothingItem.user_id == user_id, + ClothingItem.status == ItemStatus.ready, + ClothingItem.is_archived.is_(False), + ) + ) + available = set(rows.scalars().all()) + excluded = await db.scalar( + select(UserPreference.excluded_item_ids).where(UserPreference.user_id == user_id) + ) + available -= set(excluded or []) + + def keep(name: str, item_id: UUID | None) -> UUID | None: + if item_id is not None and item_id not in available: + logger.info(f"Dropping {name} {item_id}: no longer available when saving") + return None + return item_id + + return keep("if_cooler", extras[0]), keep("if_warmer", extras[1]) + + +def uv_bucket(uv: float | None) -> int | None: + if uv is None: + return None + return 0 if uv < 3 else 1 if uv < 6 else 2 if uv < 8 else 3 + + +def wind_bucket(wind_speed: float) -> int: + """Calm, breezy, or at or above the WINDY_KMH point where the prompt mentions wind.""" + return 0 if wind_speed < WINDY_KMH * 0.6 else 1 if wind_speed < WINDY_KMH else 2 + + def suggestion_context( weather: WeatherData, time_of_day: TimeOfDay, @@ -107,6 +237,9 @@ def suggestion_context( "temps": [weather.temperature, weather.feels_like, *(scoring_temp_range(weather) or ())], "condition": weather.condition, "rain_likely": rain_likely(weather), + # Hat and layer advice depends on sun and wind, so a change of bucket regenerates it. + "uv": [uv_bucket(weather.uv_index), uv_bucket(weather.uv_index_max)], + "wind": wind_bucket(weather.wind_speed), "time_of_day": str(time_of_day), "preferences": str(preferences.updated_at) if preferences else None, # A digest, so that personal measurements are not copied into Redis. @@ -368,6 +501,10 @@ def _format_items_for_prompt( if item.material: parts.append(item.material) + weight = footwear_weight(item) + if weight: + parts.append(f"footwear weight: {weight}") + if item.formality: parts.append(item.formality) @@ -706,8 +843,15 @@ async def _save_outfit( occasion: str, source: OutfitSource, scheduled_date: date | None = None, + number_map: dict[int, UUID] | None = None, ) -> Outfit: valid_ids = canonical_item_order(item_ids, item_type_map) + if_cooler, if_warmer = resolve_layer_extras( + outfit_data, number_map or {}, item_type_map, valid_ids + ) + if_cooler, if_warmer = await drop_unavailable_extras( + self.db, user.id, (if_cooler, if_warmer) + ) reasoning = outfit_data.get("headline") or outfit_data.get("reasoning") style_notes = outfit_data.get("styling_tip") or outfit_data.get("style_notes") @@ -719,6 +863,8 @@ async def _save_outfit( reasoning=reasoning, style_notes=style_notes, ai_raw_response=outfit_data, + if_cooler_item_id=if_cooler, + if_warmer_item_id=if_warmer, source=source, status=OutfitStatus.pending, ) @@ -912,7 +1058,15 @@ async def generate_recommendations( continue logger.info(f"Using cached suggestion for user {user.id}, occasion: {occasion}") outfit = await self._save_outfit( - cached, item_ids, item_type_map, user, weather, occasion, source, scheduled_date + cached, + item_ids, + item_type_map, + user, + weather, + occasion, + source, + scheduled_date, + number_map, ) return [outfit] @@ -969,6 +1123,7 @@ async def generate_recommendations( condition=weather.condition, precipitation_chance=weather.precipitation_chance, temp_range_text=format_temp_range_text(weather), + weather_details_text=format_weather_details_text(weather), preferences_text=preferences_text, items_text=items_text, mandatory_items_section=mandatory_items_section, @@ -1027,6 +1182,7 @@ async def generate_recommendations( occasion, source, scheduled_date, + number_map, ) return [outfit] @@ -1066,7 +1222,15 @@ async def generate_recommendations( outfits = [ await self._save_outfit( - od, item_ids, item_type_map, user, weather, occasion, source, scheduled_date + od, + item_ids, + item_type_map, + user, + weather, + occasion, + source, + scheduled_date, + number_map, ) for od, item_ids in chosen ] diff --git a/backend/app/services/weather_service.py b/backend/app/services/weather_service.py index 0178d10fb..f08ed3013 100644 --- a/backend/app/services/weather_service.py +++ b/backend/app/services/weather_service.py @@ -36,6 +36,8 @@ class WeatherData: # so that late-evening requests score against the current reading only. window_min: float | None = None window_max: float | None = None + # Today's (or the forecast day's) peak UV index; uv_index above is the reading right now. + uv_index_max: float | None = None def to_dict(self) -> dict: return { @@ -54,6 +56,7 @@ def to_dict(self) -> dict: "temp_max": self.temp_max, "window_min": self.window_min, "window_max": self.window_max, + "uv_index_max": self.uv_index_max, } @@ -300,7 +303,7 @@ async def get_current_weather( "uv_index", ], "hourly": ["precipitation_probability", "temperature_2m"], - "daily": ["temperature_2m_max", "temperature_2m_min"], + "daily": ["temperature_2m_max", "temperature_2m_min", "uv_index_max"], "forecast_hours": 24, "forecast_days": 1, "timezone": "auto", @@ -328,6 +331,8 @@ async def get_current_weather( temp_mins = daily.get("temperature_2m_min") or [] temp_max = temp_maxs[0] if temp_maxs and temp_maxs[0] is not None else None temp_min = temp_mins[0] if temp_mins and temp_mins[0] is not None else None + uv_maxs = daily.get("uv_index_max") or [] + uv_index_max = uv_maxs[0] if uv_maxs and uv_maxs[0] is not None else None window = self._wearing_window(current, hourly) weather = WeatherData( @@ -346,6 +351,7 @@ async def get_current_weather( temp_max=temp_max, window_min=window[0] if window else None, window_max=window[1] if window else None, + uv_index_max=uv_index_max, ) await self._cache_set(latitude, longitude, weather) @@ -506,6 +512,7 @@ async def get_tomorrow_weather(self, latitude: float, longitude: float) -> Weath temp_max=tomorrow.temp_max, window_min=tomorrow.temp_min, window_max=tomorrow.temp_max, + uv_index_max=tomorrow.uv_index, ) async def check_health(self) -> dict: diff --git a/backend/migrations/versions/b3d9f1a2c4e6_add_outfit_weather_extras.py b/backend/migrations/versions/b3d9f1a2c4e6_add_outfit_weather_extras.py new file mode 100644 index 000000000..f8725fdb0 --- /dev/null +++ b/backend/migrations/versions/b3d9f1a2c4e6_add_outfit_weather_extras.py @@ -0,0 +1,46 @@ +"""Add if-cooler and if-warmer items to outfits. + +Two nullable foreign keys to clothing_items. The AI may name one wardrobe layer to add if it +gets cooler and one of the outfit's own layers to take off if it warms up. Deleting the item +clears the pointer instead of the outfit (both columns are indexed for that lookup). +Existing rows stay NULL. + +Revision ID: b3d9f1a2c4e6 +Revises: a7d3c9e1f5b2 +Create Date: 2026-11-12 12:00:00.000000 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects.postgresql import UUID + +# revision identifiers, used by Alembic. +revision: str = "b3d9f1a2c4e6" +down_revision: str | None = "a7d3c9e1f5b2" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + for column in ("if_cooler_item_id", "if_warmer_item_id"): + op.add_column("outfits", sa.Column(column, UUID(as_uuid=True), nullable=True)) + op.create_foreign_key( + f"fk_outfits_{column}", + "outfits", + "clothing_items", + [column], + ["id"], + ondelete="SET NULL", + ) + # Deleting an item looks up the outfits pointing at it (ON DELETE SET NULL). + op.create_index(f"ix_outfits_{column}", "outfits", [column]) + + +def downgrade() -> None: + for column in ("if_warmer_item_id", "if_cooler_item_id"): + op.drop_index(f"ix_outfits_{column}", table_name="outfits") + op.drop_constraint(f"fk_outfits_{column}", "outfits", type_="foreignkey") + op.drop_column("outfits", column) diff --git a/backend/tests/test_footwear_weight.py b/backend/tests/test_footwear_weight.py new file mode 100644 index 000000000..e5096ebe8 --- /dev/null +++ b/backend/tests/test_footwear_weight.py @@ -0,0 +1,244 @@ +from datetime import date + +import pytest + +from app.models.item import ClothingItem +from app.services.item_scorer import ( + HEAVY_FOOTWEAR_WARM_FACTOR, + LIGHT_FOOTWEAR_COLD_FACTOR, + MEDIUM_FOOTWEAR_WARM_FACTOR, + ScoredItem, + _fit_factors, + _footwear_weight_score, + footwear_weight, + has_light_footwear, + score_items, +) +from app.services.recommendation_service import ( + RECOMMENDATION_PROMPT, + RecommendationService, +) +from tests.test_item_scorer import _item, _prefs, _weather + + +def _shoe(**kwargs) -> ClothingItem: + kwargs.setdefault("type", "sneakers") + return _item(**kwargs) + + +class TestFootwearWeight: + @pytest.mark.parametrize( + ("kwargs", "expected"), + [ + # Chunky sole but a mesh upper in nylon: neither leather bulk nor truly airy. + ( + { + "ai_description": ( + "Black lace-up sneakers with a chunky sole and textured mesh upper" + ), + "material": "nylon", + "season": ["all-season"], + }, + "medium", + ), + ({"subtype": "knit sneaker", "material": "knit", "season": ["all-season"]}, "light"), + ({"ai_description": "Slip-on knit trainers"}, "light"), + ({"type": "boots", "subtype": "combat boots", "material": "leather"}, "heavy"), + ({"type": "boots", "subtype": "suede chukka boots", "material": "suede"}, "heavy"), + ({"type": "sandals"}, "light"), + ({"type": "shoes", "subtype": "espadrilles"}, "light"), + ({"type": "shoes", "subtype": "slides"}, "light"), + ({"material": "canvas"}, "light"), + ({"material": "linen"}, "light"), + ({"ai_description": "High-top sneakers in white leather"}, "heavy"), + ({"ai_description": "Sneakers lined with soft fleece"}, "heavy"), + ({"ai_description": "Unlined leather sneakers"}, "medium"), + ({"material": "shearling"}, "heavy"), + ({"ai_description": "Chunky leather platform sneakers"}, "heavy"), + ({"material": "suede", "ai_description": "Chunky suede sneakers"}, "heavy"), + ({"season": ["winter"]}, "heavy"), + ({"season": ["fall", "winter"]}, "medium"), + ({"season": ["summer"]}, "light"), + ({"season": ["summer", "spring"]}, "light"), + ({"season": ["all-season"], "material": "leather"}, "medium"), + ({"type": "flats", "material": "leather"}, "medium"), + ({"type": "heels", "material": "leather"}, "medium"), + ], + ) + def test_classification(self, kwargs, expected): + assert footwear_weight(_shoe(**kwargs)) == expected + + def test_not_footwear_is_none(self): + assert footwear_weight(_item(type="shirt")) is None + assert footwear_weight(_item(type="hat")) is None + + def test_winter_boots_with_all_season_tag_are_still_heavy(self): + assert footwear_weight(_shoe(type="boots", season=["all-season"])) == "heavy" + + +def _factor(item, weather, light_available=True, prefs=None): + return _fit_factors(item, weather, "casual", "spring", prefs, None, light_available)[0] + + +def _feels(temp, feels_like, **kwargs): + weather = _weather(temp=temp, **kwargs) + weather.feels_like = feels_like + return weather + + +class TestFootwearScoring: + def test_warm_day_prefers_light_over_heavy(self): + weather = _feels(22.6, 24) + light = _factor(_shoe(material="knit"), weather) + medium = _factor(_shoe(material="leather"), weather) + heavy = _factor(_shoe(ai_description="Chunky leather sneakers"), weather) + assert light > medium > heavy + assert heavy == pytest.approx( + HEAVY_FOOTWEAR_WARM_FACTOR * _factor(_item(type="hat"), weather) + ) + + def test_medium_penalty_only_when_a_light_alternative_exists(self): + weather = _feels(22.6, 24) + medium = _shoe(material="leather") + with_light = _factor(medium, weather, light_available=True) + without = _factor(medium, weather, light_available=False) + assert with_light == pytest.approx(without * MEDIUM_FOOTWEAR_WARM_FACTOR) + + def test_feels_like_alone_makes_it_warm(self): + heavy = _shoe(type="boots") + cool_air = _factor(heavy, _feels(18, 18)) + hot_feel = _factor(heavy, _feels(18, 23)) + assert hot_feel < cool_air + + def test_range_high_makes_it_warm_even_when_the_midpoint_is_not(self): + heavy = _shoe(ai_description="High-top sneakers") + # Midpoint 19, below the warm point, but the afternoon reaches 28. + swing = _weather(temp=15, window_min=10, window_max=28) + assert swing.feels_like < 20 + assert _footwear_weight_score(heavy, swing, None, True) < 1.0 + cool_swing = _weather(temp=15, window_min=8, window_max=18) + assert _footwear_weight_score(heavy, cool_swing, None, True) == 1.0 + + def test_range_low_makes_it_cold_even_when_the_midpoint_is_not(self): + light = _shoe(material="knit") + # Midpoint 10.5 is not cold, but the morning drops to 2. + swing = _weather(temp=11, window_min=2, window_max=19) + assert _footwear_weight_score(light, swing, None, True) == LIGHT_FOOTWEAR_COLD_FACTOR + + def test_feels_like_counts_alongside_a_range(self): + heavy = _shoe(ai_description="High-top sneakers") + light = _shoe(material="knit") + hot_feel = _weather(temp=15, window_min=12, window_max=20) + hot_feel.feels_like = 26 + assert _footwear_weight_score(heavy, hot_feel, None, True) < 1.0 + cold_feel = _weather(temp=12, window_min=8, window_max=18) + cold_feel.feels_like = 3 + assert _footwear_weight_score(light, cold_feel, None, True) == LIGHT_FOOTWEAR_COLD_FACTOR + + def test_threshold_follows_user_preference(self): + heavy = _shoe(ai_description="High-top sneakers") + weather = _feels(20, 20) + assert _factor(heavy, weather, prefs=_prefs(hot_threshold=25)) > _factor( + heavy, weather, prefs=_prefs(hot_threshold=20) + ) + + def test_cold_day_mildly_penalises_light_shoes(self): + weather = _weather(temp=4) + light = _shoe(material="knit") + heavy = _shoe(type="boots") + assert _footwear_weight_score(heavy, weather, None, True) == 1.0 + assert _footwear_weight_score(light, weather, None, True) == LIGHT_FOOTWEAR_COLD_FACTOR + assert LIGHT_FOOTWEAR_COLD_FACTOR > 0.5 + + def test_mild_day_does_not_change_footwear(self): + weather = _weather(temp=15) + assert ( + _factor(_shoe(type="boots"), weather) + == _factor(_shoe(material="knit"), weather) + == _factor(_item(type="hat"), weather) + ) + + def test_nothing_is_excluded(self): + assert _factor(_shoe(type="boots"), _feels(22.6, 24)) > 0 + + def test_has_light_footwear(self): + assert has_light_footwear([_shoe(material="knit")]) + assert not has_light_footwear([_shoe(type="boots"), _item(type="shirt")]) + + def test_score_items_ranks_light_shoe_above_heavy_on_a_warm_day(self): + heavy = _shoe(ai_description="Chunky leather sneakers") + light = _shoe(material="knit") + items = [heavy, light, *[_item() for _ in range(60)]] + result = score_items( + items=items, + weather=_feels(22.6, 24), + occasion="casual", + preferences=None, + user_today=date(2026, 3, 8), + current_season="spring", + learned_prefs=None, + good_pairs={}, + recently_worn_dates={}, + ) + order = [s.item.id for s in result] + assert order.index(light.id) < order.index(heavy.id) + + def test_small_wardrobe_reorders_only_the_shoes(self): + shirt, jeans, hat = _item(type="shirt"), _item(type="jeans"), _item(type="hat") + heavy = _shoe(ai_description="Chunky leather sneakers") + light = _shoe(material="knit") + items = [heavy, shirt, light, jeans, hat] + result = score_items( + items=items, + weather=_feels(22.6, 24), + occasion="casual", + preferences=None, + user_today=date(2026, 3, 8), + current_season="spring", + learned_prefs=None, + good_pairs={}, + recently_worn_dates={}, + ) + assert [s.item.id for s in result] == [i.id for i in (light, shirt, heavy, jeans, hat)] + + def test_small_wardrobe_keeps_order_on_a_mild_day_and_mandatory_stays_first(self): + heavy = _shoe(ai_description="Chunky leather sneakers") + light = _shoe(material="knit") + shirt = _item(type="shirt") + kwargs = { + "occasion": "casual", + "preferences": None, + "user_today": date(2026, 3, 8), + "current_season": "spring", + "learned_prefs": None, + "good_pairs": {}, + "recently_worn_dates": {}, + } + mild = score_items(items=[heavy, shirt, light], weather=_weather(temp=15), **kwargs) + assert [s.item.id for s in mild] == [heavy.id, shirt.id, light.id] + warm = score_items( + items=[heavy, shirt, light], + weather=_feels(22.6, 24), + mandatory_item_ids={heavy.id}, + **kwargs, + ) + assert warm[0].item.id == heavy.id + + +class TestFootwearPrompt: + def test_rule_in_prompt(self): + assert "Match footwear weight to the weather" in RECOMMENDATION_PROMPT + assert "light, breathable shoes when warm" in RECOMMENDATION_PROMPT + + def test_items_text_lists_footwear_weight_only_for_shoes(self): + service = RecommendationService.__new__(RecommendationService) + boots = _shoe(type="boots") + knit = _shoe(material="knit") + shirt = _item(type="shirt") + text, _ = service._format_items_for_prompt( + [ScoredItem(item=i) for i in (boots, knit, shirt)], {}, date(2026, 3, 8) + ) + lines = text.splitlines() + assert "footwear weight: heavy" in lines[0] + assert "footwear weight: light" in lines[1] + assert "footwear weight" not in lines[2] diff --git a/backend/tests/test_item_scorer.py b/backend/tests/test_item_scorer.py index c32940370..e726a37b1 100644 --- a/backend/tests/test_item_scorer.py +++ b/backend/tests/test_item_scorer.py @@ -688,6 +688,24 @@ def test_promotion_never_evicts_a_mandatory_item(self): assert mandatory.id in result_ids assert {s.id for s in shoes} <= result_ids + def test_keeps_layers_for_if_cooler_in_a_big_wardrobe(self): + shirts, bottoms, shoes = self._wardrobe() + cardigans = [_item(type="cardigan") for _ in range(3)] + coats = [_item(type="coat") for _ in range(3)] + result = self._score(shirts + bottoms + shoes + cardigans + coats) + kept = [s.item for s in result] + assert len(kept) == 70 + assert sum(1 for i in kept if i.type == "cardigan") >= 2 + assert sum(1 for i in kept if i.type == "coat") >= 2 + + def test_layer_floor_leaves_a_wardrobe_with_enough_layers_alone(self): + shirts, bottoms, shoes = self._wardrobe() + coats = [_item(type="coat") for _ in range(2)] + cardigans = [_item(type="cardigan") for _ in range(2)] + # The layers are first in the input, so they are already in the cut. + result = self._score(coats + cardigans + shirts + bottoms + shoes) + assert {i.id for i in coats + cardigans} <= {s.item.id for s in result} + @pytest.mark.parametrize( ("weather", "prefs", "expected"), diff --git a/backend/tests/test_migration_wore_instead_names.py b/backend/tests/test_migration_wore_instead_names.py index ba9d5d84f..8b6a3b0cf 100644 --- a/backend/tests/test_migration_wore_instead_names.py +++ b/backend/tests/test_migration_wore_instead_names.py @@ -1,11 +1,13 @@ import os import subprocess +from uuid import UUID, uuid4 import pytest +from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from app.models import User -from app.models.outfit import Outfit, OutfitSource +from app.models.outfit import Outfit PREVIOUS = "921b8d3bc2b8" @@ -21,36 +23,34 @@ async def test_clears_only_generated_wore_instead_names(db_session: AsyncSession await db_session.commit() _alembic("downgrade", PREVIOUS) try: - original = Outfit(user_id=user_id, occasion="casual", source=OutfitSource.manual) - db_session.add(original) - await db_session.flush() - - def wore_instead(occasion: str, name: str) -> Outfit: - return Outfit( - user_id=user_id, - occasion=occasion, - source=OutfitSource.manual, - replaces_outfit_id=original.id, - name=name, + # Raw SQL: the ORM model also names columns that a later migration adds, and the + # schema is deliberately downgraded below them here. + async def insert(occasion: str, name: str | None, replaces: UUID | None = None) -> UUID: + outfit_id = uuid4() + await db_session.execute( + text( + "INSERT INTO outfits (id, user_id, occasion, status, source, name," + " replaces_outfit_id) VALUES (:id, :user_id, :occasion, 'pending', 'manual'," + " :name, :replaces)" + ), + { + "id": outfit_id, + "user_id": user_id, + "occasion": occasion, + "name": name, + "replaces": replaces, + }, ) + return outfit_id - generated = wore_instead("casual", "Casual (wore instead)") - multiword = wore_instead("date_night", "Date_Night (wore instead)") - renamed = wore_instead("casual", "My favourite look") - kept = Outfit( - user_id=user_id, - occasion="casual", - source=OutfitSource.manual, - name="Casual (wore instead)", - ) - db_session.add_all([generated, multiword, renamed, kept]) + original = await insert("casual", None) await db_session.commit() - ids = { - "generated": generated.id, - "multiword": multiword.id, - "renamed": renamed.id, - "kept": kept.id, - } + generated = await insert("casual", "Casual (wore instead)", original) + multiword = await insert("date_night", "Date_Night (wore instead)", original) + renamed = await insert("casual", "My favourite look", original) + kept = await insert("casual", "Casual (wore instead)") + await db_session.commit() + ids = {"generated": generated, "multiword": multiword, "renamed": renamed, "kept": kept} finally: _alembic("upgrade", "head") diff --git a/backend/tests/test_recommendation_service.py b/backend/tests/test_recommendation_service.py index 4ad3f8611..6d9a87dab 100644 --- a/backend/tests/test_recommendation_service.py +++ b/backend/tests/test_recommendation_service.py @@ -121,6 +121,7 @@ def test_prompt_format_accepts_time_of_day(self): condition="clear", precipitation_chance=10, temp_range_text="", + weather_details_text="", preferences_text="", items_text="[1] shirt | blue | cotton", mandatory_items_section="", @@ -141,6 +142,7 @@ def test_prompt_format_all_time_of_day_values(self): condition="cloudy", precipitation_chance=30, temp_range_text="", + weather_details_text="", preferences_text="", items_text="[1] shirt", mandatory_items_section="", @@ -191,6 +193,7 @@ def test_empty_formats_cleanly(self): condition="clear", precipitation_chance=10, temp_range_text="", + weather_details_text="", preferences_text="", items_text="[1] shirt", mandatory_items_section="", @@ -206,6 +209,7 @@ def test_non_empty_appears_in_output(self): condition="clear", precipitation_chance=10, temp_range_text="- Temperature ahead ranges from 5.0°C to 30.0°C, a large swing.", + weather_details_text="", preferences_text="", items_text="[1] shirt", mandatory_items_section="", @@ -843,6 +847,8 @@ async def test_suggest_options_endpoint_returns_multiple(self, client, auth_head o.notes = None o.weather_data = None o.items = [] + o.if_cooler_item = None + o.if_warmer_item = None o.feedback = [] o.family_ratings = [] o.created_at = datetime.utcnow() diff --git a/backend/tests/test_sun_and_cold_hat.py b/backend/tests/test_sun_and_cold_hat.py new file mode 100644 index 000000000..7b7e59779 --- /dev/null +++ b/backend/tests/test_sun_and_cold_hat.py @@ -0,0 +1,110 @@ +from datetime import datetime + +from app.services.item_scorer import _fit_factors +from app.services.recommendation_service import ( + RECOMMENDATION_PROMPT, + cached_suggestion_fits, + format_weather_details_text, + suggestion_context, + uv_bucket, + wind_bucket, +) +from app.services.weather_service import WeatherData +from tests.test_item_scorer import _item, _weather + + +def _factor(item, weather): + return _fit_factors(item, weather, "casual", "spring", None, None)[0] + + +def _weather_with(**kwargs) -> WeatherData: + weather = _weather(temp=20) + for key, value in kwargs.items(): + setattr(weather, key, value) + return weather + + +class TestSunAndColdHat: + def _format(self, weather): + return RECOMMENDATION_PROMPT.format( + occasion="casual", + time_of_day="morning", + temperature=weather.temperature, + feels_like=weather.feels_like, + condition=weather.condition, + precipitation_chance=weather.precipitation_chance, + temp_range_text="", + weather_details_text=format_weather_details_text(weather), + preferences_text="", + items_text="[1] sneakers", + mandatory_items_section="", + ) + + def test_uv_index_reaches_the_prompt(self): + prompt = self._format(_weather_with(uv_index=7.0, uv_index_max=8.5)) + assert "UV index 7 now, up to 8.5 today" in prompt + + def test_uv_without_daily_max(self): + assert format_weather_details_text(_weather_with(uv_index=3.0)) == "- UV index 3" + + def test_wind_is_mentioned_when_strong(self): + text = format_weather_details_text(_weather_with(wind_speed=32)) + assert "windy (32 km/h)" in text + assert "windy" not in format_weather_details_text(_weather_with(wind_speed=10)) + + def test_hat_rule(self): + assert "Never add a hat just to complete the look" in RECOMMENDATION_PROMPT + assert "UV index is 6 or higher" in RECOMMENDATION_PROMPT + assert "(belt, scarf, hat" not in RECOMMENDATION_PROMPT + + def test_hats_are_not_boosted_by_any_weather(self): + hat = _item(type="hat") + shirt = _item(type="shirt") + for weather in (_weather(temp=2), _weather(temp=15), _weather(temp=32)): + assert _factor(hat, weather) <= 1.0 + assert _factor(hat, weather) <= _factor(shirt, weather) + 1e-9 + + +def test_weather_data_round_trips_uv_max(): + weather = _weather_with(uv_index_max=7.5) + assert ( + WeatherData(**{**weather.to_dict(), "timestamp": datetime(2026, 3, 8)}).uv_index_max == 7.5 + ) + + +class TestCacheContextSunAndWind: + def _context(self, **weather): + from app.models.outfit import TimeOfDay + + return suggestion_context(_weather_with(**weather), TimeOfDay.morning, None, None) + + def _fits(self, cached, now): + return cached_suggestion_fits(cached, now, None) + + def test_uv_bucket_change_invalidates_the_cache(self): + assert not self._fits(self._context(uv_index=2), self._context(uv_index=7)) + assert not self._fits( + self._context(uv_index=2, uv_index_max=3), self._context(uv_index=2, uv_index_max=9) + ) + + def test_uv_within_a_bucket_is_reused(self): + assert self._fits(self._context(uv_index=3.5), self._context(uv_index=5.5)) + + def test_wind_crossing_the_threshold_invalidates_the_cache(self): + assert not self._fits(self._context(wind_speed=10), self._context(wind_speed=30)) + assert not self._fits(self._context(wind_speed=20), self._context(wind_speed=26)) + + def test_wind_within_a_bucket_is_reused(self): + assert self._fits(self._context(wind_speed=5), self._context(wind_speed=12)) + assert self._fits(self._context(wind_speed=30), self._context(wind_speed=45)) + + def test_old_cache_entries_without_sun_and_wind_are_not_reused(self): + old = self._context() + del old["uv"], old["wind"] + assert not self._fits(old, self._context()) + + def test_buckets(self): + assert [uv_bucket(v) for v in (None, 0, 2.9, 3, 5.9, 6, 7.9, 8, 11)] == [ + None, 0, 0, 1, 1, 2, 2, 3, 3, + ] # fmt: skip + assert [wind_bucket(v) for v in (0, 14.9, 15, 24.9, 25, 60)] == [0, 0, 1, 1, 2, 2] diff --git a/backend/tests/test_weather_extras.py b/backend/tests/test_weather_extras.py new file mode 100644 index 000000000..328f1dd01 --- /dev/null +++ b/backend/tests/test_weather_extras.py @@ -0,0 +1,319 @@ +import json +import logging +from uuid import uuid4 + +import pytest +from sqlalchemy import delete, text + +from app.models.item import ClothingItem, ItemStatus +from app.models.outfit import Outfit, OutfitItem, OutfitSource +from app.services.recommendation_service import ( + RECOMMENDATION_PROMPT, + RecommendationService, + resolve_layer_extras, +) +from tests.migration_helpers import migration_downgrade +from tests.test_item_scorer import _weather + +PREVIOUS = "a7d3c9e1f5b2" + + +class TestExtrasPrompt: + def test_extras_in_prompt_and_json_shape(self): + assert '"if_cooler"' in RECOMMENDATION_PROMPT + assert '"if_warmer"' in RECOMMENDATION_PROMPT + assert "cardigan" in RECOMMENDATION_PROMPT.split("WEATHER EXTRAS")[1] + + +class TestResolveLayerExtras: + def setup_method(self): + kinds = { + "top": "t-shirt", + "bottom": "jeans", + "shoes": "sneakers", + "cardigan": "cardigan", + "jacket": "jacket", + "coat": "coat", + "hat": "hat", + "shirt2": "shirt", + } + self.ids = {name: uuid4() for name in kinds} + self.types = {self.ids[name]: kind for name, kind in kinds.items()} + self.numbers = {i: self.ids[name] for i, name in enumerate(kinds, start=1)} + self.n = {name: i for i, name in enumerate(kinds, start=1)} + self.outfit = [self.ids[n] for n in ("top", "bottom", "shoes", "jacket")] + + def _resolve(self, cooler=None, warmer=None, outfit=None, types=None): + data = {"items": [], "if_cooler": cooler, "if_warmer": warmer} + return resolve_layer_extras(data, self.numbers, types or self.types, outfit or self.outfit) + + def test_valid_pair(self): + cooler, warmer = self._resolve(self.n["cardigan"], self.n["jacket"]) + assert cooler == self.ids["cardigan"] + assert warmer == self.ids["jacket"] + + def test_null_and_missing(self): + assert self._resolve(None, None) == (None, None) + assert resolve_layer_extras({"items": []}, self.numbers, self.types, self.outfit) == ( + None, + None, + ) + + def test_numbers_as_strings_are_accepted(self): + cooler, _ = self._resolve(str(self.n["coat"])) + assert cooler == self.ids["coat"] + + @pytest.mark.parametrize("bad", [99, 0, -1, "abc", True, [1, 2], {"a": 1}, 4.5e20]) + def test_out_of_range_or_malformed_is_dropped(self, bad): + assert self._resolve(bad, bad) == (None, None) + + def test_cooler_must_be_a_layer(self): + assert self._resolve(self.n["hat"]) == (None, None) + assert self._resolve(self.n["shirt2"]) == (None, None) + assert self._resolve(self.n["shoes"]) == (None, None) + + def test_cooler_must_not_duplicate_an_outfit_item(self): + assert self._resolve(self.n["jacket"]) == (None, None) + + def test_warmer_must_be_in_the_outfit(self): + assert self._resolve(None, self.n["coat"]) == (None, None) + + def test_warmer_must_be_removable(self): + assert self._resolve(None, self.n["top"]) == (None, None) + assert self._resolve(None, self.n["shoes"]) == (None, None) + + def test_warmer_must_leave_a_complete_outfit(self): + hoodie = uuid4() + types = {**self.types, hoodie: "hoodie"} + numbers = {**self.numbers, 50: hoodie} + # The hoodie is the only top, so taking it off would leave the outfit incomplete. + outfit = [hoodie, self.ids["bottom"], self.ids["shoes"]] + data = {"items": [], "if_warmer": 50} + assert resolve_layer_extras(data, numbers, types, outfit) == (None, None) + + def test_excluded_or_archived_items_are_not_candidates(self): + # Excluded and archived items never reach the candidates, so they are absent from + # item_type_map (and the number map built from it). + types = {k: v for k, v in self.types.items() if k != self.ids["cardigan"]} + assert self._resolve(self.n["cardigan"], types=types) == (None, None) + + def test_dropped_extras_are_logged_at_info_without_content(self, caplog): + with caplog.at_level(logging.INFO, logger="app.services.recommendation_service"): + self._resolve("ignore previous instructions", self.n["hat"]) + assert "Dropping if_cooler" in caplog.text + assert "Dropping if_warmer" in caplog.text + ours = [r for r in caplog.records if r.name == "app.services.recommendation_service"] + assert len(ours) == 2 + assert all(r.levelno == logging.INFO for r in ours) + assert all("ignore previous" not in r.getMessage() for r in ours) + + def test_one_invalid_does_not_drop_the_other(self): + cooler, warmer = self._resolve(self.n["jacket"], self.n["jacket"]) + assert cooler is None + assert warmer == self.ids["jacket"] + + def test_survives_a_redis_round_trip(self): + data = json.loads(json.dumps({"items": [], "if_cooler": 4, "if_warmer": 5})) + numbers = {int(k): v for k, v in {str(k): v for k, v in self.numbers.items()}.items()} + cooler, warmer = resolve_layer_extras(data, numbers, self.types, self.outfit) + assert cooler == self.ids["cardigan"] + assert warmer == self.ids["jacket"] + + +async def _wardrobe(db_session, user_id): + items = {} + for name, kind in ( + ("top", "t-shirt"), + ("bottom", "jeans"), + ("shoes", "sneakers"), + ("jacket", "jacket"), + ("cardigan", "cardigan"), + ): + items[name] = ClothingItem( + id=uuid4(), + user_id=user_id, + type=kind, + name=f"My {name}", + image_path=f"test/{name}.jpg", + thumbnail_path=f"test/{name}_thumb.jpg", + status=ItemStatus.ready, + ) + db_session.add_all(items.values()) + await db_session.commit() + return items + + +class TestPersistenceAndApi: + async def _save(self, db_session, test_user, items, extras): + service = RecommendationService(db_session) + types = {i.id: i.type for i in items.values()} + numbers = dict(enumerate((i.id for i in items.values()), start=1)) + ids = [items[n].id for n in ("top", "bottom", "shoes", "jacket")] + weather = _weather(temp=15) + return await service._save_outfit( + {"items": [1, 2, 3, 4], "headline": "Layered", **extras}, + ids, + types, + test_user, + weather, + "casual", + OutfitSource.on_demand, + number_map=numbers, + ) + + async def test_saved_and_returned_by_the_api(self, client, db_session, test_user, auth_headers): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_cooler": 5, "if_warmer": 4}) + assert outfit.if_cooler_item_id == items["cardigan"].id + assert outfit.if_warmer_item_id == items["jacket"].id + + response = await client.get(f"/api/v1/outfits/{outfit.id}", headers=auth_headers) + assert response.status_code == 200 + body = response.json() + assert body["if_cooler"]["id"] == str(items["cardigan"].id) + assert body["if_cooler"]["type"] == "cardigan" + assert body["if_cooler"]["thumbnail_url"] + assert body["if_warmer"]["id"] == str(items["jacket"].id) + + async def test_invalid_extras_are_not_saved(self, client, db_session, test_user, auth_headers): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_cooler": 4, "if_warmer": 1}) + assert outfit.if_cooler_item_id is None + assert outfit.if_warmer_item_id is None + body = (await client.get(f"/api/v1/outfits/{outfit.id}", headers=auth_headers)).json() + assert body["if_cooler"] is None + assert body["if_warmer"] is None + + @pytest.mark.parametrize("change", ["archived", "processing", "excluded", "deleted"]) + async def test_extra_unavailable_at_save_time_is_dropped( + self, db_session, test_user, change, caplog + ): + from app.models.preference import UserPreference + + items = await _wardrobe(db_session, test_user.id) + cardigan = items["cardigan"] + cardigan_id = cardigan.id + if change == "archived": + cardigan.is_archived = True + elif change == "processing": + cardigan.status = ItemStatus.processing + elif change == "excluded": + db_session.add(UserPreference(user_id=test_user.id, excluded_item_ids=[cardigan_id])) + else: + await db_session.delete(cardigan) + await db_session.commit() + with caplog.at_level(logging.INFO, logger="app.services.recommendation_service"): + outfit = await self._save( + db_session, test_user, items, {"if_cooler": 5, "if_warmer": 4} + ) + assert outfit.if_cooler_item_id is None + assert outfit.if_warmer_item_id == items["jacket"].id + assert f"Dropping if_cooler {cardigan_id}" in caplog.text + + async def test_archived_extra_is_hidden_in_the_response( + self, client, db_session, test_user, auth_headers + ): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_cooler": 5, "if_warmer": 4}) + outfit_id = outfit.id + items["cardigan"].is_archived = True + items["jacket"].status = ItemStatus.processing + await db_session.commit() + db_session.expire_all() + body = (await client.get(f"/api/v1/outfits/{outfit_id}", headers=auth_headers)).json() + assert body["if_cooler"] is None + assert body["if_warmer"] is None + + async def test_warmer_the_outfit_now_needs_is_hidden( + self, client, db_session, test_user, auth_headers + ): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_warmer": 4}) + outfit_id, top_id = outfit.id, items["top"].id + # An edit removes the t-shirt, so the jacket is now the only upper-body piece. + await db_session.execute( + delete(OutfitItem).where( + OutfitItem.outfit_id == outfit_id, OutfitItem.item_id == top_id + ) + ) + await db_session.commit() + db_session.expire_all() + body = (await client.get(f"/api/v1/outfits/{outfit_id}", headers=auth_headers)).json() + assert body["if_warmer"] is None + + async def test_list_endpoint_includes_extras(self, client, db_session, test_user, auth_headers): + items = await _wardrobe(db_session, test_user.id) + await self._save(db_session, test_user, items, {"if_cooler": 5}) + response = await client.get("/api/v1/outfits", headers=auth_headers) + assert response.status_code == 200 + [entry] = response.json()["outfits"] + assert entry["if_cooler"]["type"] == "cardigan" + assert entry["if_warmer"] is None + + async def test_deleting_the_item_clears_the_extra( + self, client, db_session, test_user, auth_headers + ): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_cooler": 5}) + outfit_id = outfit.id + await db_session.execute( + delete(ClothingItem).where(ClothingItem.id == items["cardigan"].id) + ) + await db_session.commit() + db_session.expire_all() + body = (await client.get(f"/api/v1/outfits/{outfit_id}", headers=auth_headers)).json() + assert body["if_cooler"] is None + assert (await db_session.get(Outfit, outfit_id)) is not None + + async def test_extra_that_no_longer_fits_the_outfit_is_hidden( + self, client, db_session, test_user, auth_headers + ): + items = await _wardrobe(db_session, test_user.id) + outfit = await self._save(db_session, test_user, items, {"if_cooler": 5, "if_warmer": 4}) + jacket_id, cardigan_id, outfit_id = items["jacket"].id, items["cardigan"].id, outfit.id + # An edit removes the jacket and puts the cardigan in the outfit. + await db_session.execute( + delete(OutfitItem).where( + OutfitItem.outfit_id == outfit_id, OutfitItem.item_id == jacket_id + ) + ) + db_session.add(OutfitItem(outfit_id=outfit_id, item_id=cardigan_id, position=9)) + await db_session.commit() + db_session.expire_all() + body = (await client.get(f"/api/v1/outfits/{outfit_id}", headers=auth_headers)).json() + assert body["if_cooler"] is None + assert body["if_warmer"] is None + + +class TestMigration: + async def _columns(self, db_session): + rows = await db_session.execute( + text( + "SELECT column_name FROM information_schema.columns " + "WHERE table_name = 'outfits' AND column_name LIKE 'if\\_%'" + ) + ) + return {row[0] for row in rows} + + async def test_up_and_down(self, db_session): + assert await self._columns(db_session) == {"if_cooler_item_id", "if_warmer_item_id"} + async with migration_downgrade(db_session, PREVIOUS): + assert await self._columns(db_session) == set() + await db_session.rollback() + assert await self._columns(db_session) == {"if_cooler_item_id", "if_warmer_item_id"} + + async def test_foreign_keys_are_indexed(self, db_session): + rows = await db_session.execute( + text("SELECT indexname FROM pg_indexes WHERE tablename = 'outfits'") + ) + names = {row[0] for row in rows} + assert {"ix_outfits_if_cooler_item_id", "ix_outfits_if_warmer_item_id"} <= names + async with migration_downgrade(db_session, PREVIOUS): + rows = await db_session.execute( + text("SELECT indexname FROM pg_indexes WHERE tablename = 'outfits'") + ) + assert not {row[0] for row in rows} & { + "ix_outfits_if_cooler_item_id", + "ix_outfits_if_warmer_item_id", + } + await db_session.rollback() diff --git a/frontend/app/dashboard/outfits/[id]/page.tsx b/frontend/app/dashboard/outfits/[id]/page.tsx index 15d41beee..5a7679faf 100644 --- a/frontend/app/dashboard/outfits/[id]/page.tsx +++ b/frontend/app/dashboard/outfits/[id]/page.tsx @@ -23,6 +23,7 @@ import { Card, CardContent } from '@/components/ui/card'; import { Skeleton } from '@/components/ui/skeleton'; import { SourceBadge } from '@/components/shared/source-badge'; import { LineageCard } from '@/components/shared/lineage-card'; +import { OutfitWeatherExtras } from '@/components/shared/outfit-weather-extras'; import { CloneToLookbookDialog } from '@/components/shared/clone-to-lookbook-dialog'; import { useDeleteOutfit, useOutfit, useOutfits } from '@/lib/hooks/use-outfits'; import { useWearToday } from '@/lib/hooks/use-studio'; @@ -151,6 +152,8 @@ export default function OutfitDetailPage() { + +

diff --git a/frontend/app/dashboard/suggest/page.tsx b/frontend/app/dashboard/suggest/page.tsx index 52d7f2b41..07aa5b789 100644 --- a/frontend/app/dashboard/suggest/page.tsx +++ b/frontend/app/dashboard/suggest/page.tsx @@ -50,6 +50,7 @@ import { } from '@/components/ui/collapsible'; import { ItemPicker } from '@/components/shared/item-picker'; import { OccasionChips } from '@/components/shared/occasion-chips'; +import { OutfitWeatherExtras } from '@/components/shared/outfit-weather-extras'; import { useOccasionLabel, useWeatherConditionLabel, useTypeLabel } from '@/lib/hooks/use-translated-constants'; import { useItem } from '@/lib/hooks/use-items'; import { api, ApiError } from '@/lib/api'; @@ -367,6 +368,8 @@ function OutfitCard({ })} + + {outfit.style_notes && (
{t('tip')} {outfit.style_notes} diff --git a/frontend/components/shared/outfit-weather-extras.tsx b/frontend/components/shared/outfit-weather-extras.tsx new file mode 100644 index 000000000..f35ac617a --- /dev/null +++ b/frontend/components/shared/outfit-weather-extras.tsx @@ -0,0 +1,55 @@ +'use client'; + +import Image from 'next/image'; +import Link from 'next/link'; +import { Shirt } from 'lucide-react'; +import { useTranslations } from 'next-intl'; + +import { useTypeLabel } from '@/lib/hooks/use-translated-constants'; +import type { OutfitExtraItem } from '@/lib/types'; + +interface OutfitWeatherExtrasProps { + ifCooler?: OutfitExtraItem | null; + ifWarmer?: OutfitExtraItem | null; +} + +function ExtraRow({ + item, + messageKey, +}: { + item: OutfitExtraItem; + messageKey: 'ifCooler' | 'ifWarmer'; +}) { + const t = useTranslations('outfits.weatherExtras'); + const typeLabel = useTypeLabel(); + const label = item.name || typeLabel(item.type); + return ( +
  • + + + {item.thumbnail_url ? ( + {label} + ) : ( + + + + )} + + {t(messageKey, { item: label })} + +
  • + ); +} + +export function OutfitWeatherExtras({ ifCooler, ifWarmer }: OutfitWeatherExtrasProps) { + if (!ifCooler && !ifWarmer) return null; + return ( +
      + {ifCooler && } + {ifWarmer && } +
    + ); +} diff --git a/frontend/lib/types.ts b/frontend/lib/types.ts index 94d21a48d..09da7b389 100644 --- a/frontend/lib/types.ts +++ b/frontend/lib/types.ts @@ -344,6 +344,19 @@ export type OutfitStatus = (typeof OUTFIT_STATUSES)[number]; export type OutfitSource = 'scheduled' | 'on_demand' | 'manual' | 'pairing' | 'external'; +export interface OutfitExtraItem { + id: string; + type: string; + subtype: string | null; + name: string | null; + primary_color: string | null; + colors: string[]; + image_path: string | null; + thumbnail_path: string | null; + image_url: string | null; + thumbnail_url: string | null; +} + export interface Outfit { id: string; occasion: string; @@ -362,6 +375,8 @@ export interface Outfit { highlights: string[] | null; weather: WeatherData | null; items: OutfitItem[]; + if_cooler?: OutfitExtraItem | null; + if_warmer?: OutfitExtraItem | null; feedback: FeedbackSummary | null; family_ratings: FamilyRating[] | null; family_rating_average: number | null; diff --git a/frontend/messages/de/outfits.json b/frontend/messages/de/outfits.json index 141046fea..b467a8b99 100644 --- a/frontend/messages/de/outfits.json +++ b/frontend/messages/de/outfits.json @@ -170,5 +170,9 @@ "totalCount": "{count} insgesamt", "viewCalendar": "Kalender", "viewList": "Liste", - "viewToggle": "Ansicht wechseln" + "viewToggle": "Ansicht wechseln", + "weatherExtras": { + "ifCooler": "Wenn es kühler wird: {item} dazunehmen", + "ifWarmer": "Wenn es wärmer wird: {item} ausziehen" + } } diff --git a/frontend/messages/en/outfits.json b/frontend/messages/en/outfits.json index cfff1b078..6eba8a53a 100644 --- a/frontend/messages/en/outfits.json +++ b/frontend/messages/en/outfits.json @@ -170,5 +170,9 @@ "totalCount": "{count} total", "viewCalendar": "Calendar", "viewList": "List", - "viewToggle": "View toggle" + "viewToggle": "View toggle", + "weatherExtras": { + "ifCooler": "If it gets cooler: add {item}", + "ifWarmer": "If it warms up: take off {item}" + } } diff --git a/frontend/messages/fr/outfits.json b/frontend/messages/fr/outfits.json index f4c9191e7..d22367064 100644 --- a/frontend/messages/fr/outfits.json +++ b/frontend/messages/fr/outfits.json @@ -170,5 +170,9 @@ "totalCount": "{count} au total", "viewCalendar": "Calendrier", "viewList": "Liste", - "viewToggle": "Changer de vue" + "viewToggle": "Changer de vue", + "weatherExtras": { + "ifCooler": "S'il fait plus frais : ajoutez {item}", + "ifWarmer": "S'il fait plus chaud : retirez {item}" + } } diff --git a/frontend/messages/it/outfits.json b/frontend/messages/it/outfits.json index e04dcb3bc..216f2cab6 100644 --- a/frontend/messages/it/outfits.json +++ b/frontend/messages/it/outfits.json @@ -170,5 +170,9 @@ "totalCount": "{count} totali", "viewCalendar": "Calendario", "viewList": "Elenco", - "viewToggle": "Cambia vista" + "viewToggle": "Cambia vista", + "weatherExtras": { + "ifCooler": "Se si rinfresca: aggiungi {item}", + "ifWarmer": "Se fa più caldo: togli {item}" + } } diff --git a/frontend/messages/ja/outfits.json b/frontend/messages/ja/outfits.json index 70b4c4fe0..45cd86e18 100644 --- a/frontend/messages/ja/outfits.json +++ b/frontend/messages/ja/outfits.json @@ -170,5 +170,9 @@ "totalCount": "合計 {count}", "viewCalendar": "カレンダー", "viewList": "リスト", - "viewToggle": "表示切替" + "viewToggle": "表示切替", + "weatherExtras": { + "ifCooler": "涼しくなったら:{item}を追加", + "ifWarmer": "暖かくなったら:{item}を脱ぐ" + } } diff --git a/frontend/messages/ko/outfits.json b/frontend/messages/ko/outfits.json index 8d46ffeaf..f1258420e 100644 --- a/frontend/messages/ko/outfits.json +++ b/frontend/messages/ko/outfits.json @@ -170,5 +170,9 @@ "totalCount": "총 {count}개", "viewCalendar": "캘린더", "viewList": "목록", - "viewToggle": "보기 전환" + "viewToggle": "보기 전환", + "weatherExtras": { + "ifCooler": "쌀쌀해지면: {item} 추가", + "ifWarmer": "따뜻해지면: {item} 벗기" + } } diff --git a/frontend/messages/zh-CN/outfits.json b/frontend/messages/zh-CN/outfits.json index 88e7d2638..ab33c4bf6 100644 --- a/frontend/messages/zh-CN/outfits.json +++ b/frontend/messages/zh-CN/outfits.json @@ -170,5 +170,9 @@ "totalCount": "共{count}组", "viewCalendar": "日历", "viewList": "列表", - "viewToggle": "切换视图" + "viewToggle": "切换视图", + "weatherExtras": { + "ifCooler": "变凉时:加上{item}", + "ifWarmer": "变暖时:脱掉{item}" + } } diff --git a/frontend/messages/zh-TW/outfits.json b/frontend/messages/zh-TW/outfits.json index a325f7246..36a750af7 100644 --- a/frontend/messages/zh-TW/outfits.json +++ b/frontend/messages/zh-TW/outfits.json @@ -170,5 +170,9 @@ "totalCount": "共 {count} 個", "viewCalendar": "日曆", "viewList": "列表", - "viewToggle": "切換檢視" + "viewToggle": "切換檢視", + "weatherExtras": { + "ifCooler": "變涼時:加上{item}", + "ifWarmer": "變暖時:脫掉{item}" + } } diff --git a/frontend/tests/outfit-weather-extras.test.tsx b/frontend/tests/outfit-weather-extras.test.tsx new file mode 100644 index 000000000..9e421c84e --- /dev/null +++ b/frontend/tests/outfit-weather-extras.test.tsx @@ -0,0 +1,88 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { render, screen } from '@testing-library/react' +import { NextIntlClientProvider } from 'next-intl' +import type { ReactNode } from 'react' +import { describe, expect, it, vi } from 'vitest' +import { OutfitWeatherExtras } from '@/components/shared/outfit-weather-extras' +import type { OutfitExtraItem } from '@/lib/types' + +vi.unmock('next-intl') + +function messages(locale: string, namespace: string) { + return JSON.parse( + readFileSync(resolve(__dirname, '..', 'messages', locale, `${namespace}.json`), 'utf8'), + ) +} + +function wrapperFor(locale: string) { + const all = Object.fromEntries( + ['outfits', 'constants', 'common'].map((ns) => [ns, messages(locale, ns)]), + ) + return function Wrapper({ children }: { children: ReactNode }) { + return ( + {}}> + {children} + + ) + } +} + +const extra = (overrides: Partial): OutfitExtraItem => ({ + id: 'x1', + type: 'cardigan', + subtype: null, + name: 'Grey cardigan', + primary_color: 'grey', + colors: ['grey'], + image_path: null, + thumbnail_path: null, + image_url: null, + thumbnail_url: 'https://example.test/thumb.jpg', + ...overrides, +}) + +describe('OutfitWeatherExtras', () => { + it('renders nothing when both extras are missing', () => { + const { container } = render(, { + wrapper: wrapperFor('en'), + }) + expect(container).toBeEmptyDOMElement() + }) + + it('shows only the cooler row when only if_cooler is set', () => { + render(, { + wrapper: wrapperFor('en'), + }) + expect(screen.getByText('If it gets cooler: add Grey cardigan')).toBeInTheDocument() + expect(screen.queryByText(/warms up/)).not.toBeInTheDocument() + }) + + it('shows only the warmer row when only if_warmer is set', () => { + render(, { + wrapper: wrapperFor('en'), + }) + expect(screen.getByText('If it warms up: take off Denim jacket')).toBeInTheDocument() + expect(screen.queryByText(/gets cooler/)).not.toBeInTheDocument() + }) + + it('shows both rows with a link to each item and falls back to the type label', () => { + render( + , + { wrapper: wrapperFor('en') }, + ) + expect(screen.getByText(/If it gets cooler: add \S+/)).toBeInTheDocument() + expect(screen.getAllByRole('link').map((a) => a.getAttribute('href'))).toEqual([ + '/dashboard/wardrobe?item=x1', + '/dashboard/wardrobe?item=x2', + ]) + }) + + it('translates the rows', () => { + render(, { + wrapper: wrapperFor('it'), + }) + expect(screen.getByText('Se si rinfresca: aggiungi Grey cardigan')).toBeInTheDocument() + expect(screen.getByText('Se fa più caldo: togli Giacca')).toBeInTheDocument() + }) +})