diff --git a/app/assets/stylesheets/_climate.scss b/app/assets/stylesheets/_climate.scss index dd5efe4a93..b991b6a853 100644 --- a/app/assets/stylesheets/_climate.scss +++ b/app/assets/stylesheets/_climate.scss @@ -263,10 +263,25 @@ $climate-soil-year: #6b4423; .weather-invitation-body { display: flex; flex-direction: column; - gap: 1rem; + gap: 1.5rem; padding: 1.25rem 1.5rem; } + .weather-invitation-history { + display: flex; + flex-direction: column; + gap: 1rem; + min-width: 0; + } + + .weather-invitation-forecast { + background: rgba($green, 0.035); + border: $figure-line; + border-radius: $card-radius; + min-width: 0; + padding: 1.1rem; + } + .weather-invitation-intro { align-items: flex-start; display: flex; @@ -279,7 +294,7 @@ $climate-soil-year: #6b4423; .weather-invitation-cards { display: grid; gap: 0.75rem; - grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); } .weather-invitation-card { @@ -342,5 +357,29 @@ $climate-soil-year: #6b4423; display: flex; flex-wrap: wrap; gap: 0.75rem 1.25rem; + margin-top: auto; + } + + @include media-breakpoint-up(xl) { + .weather-invitation-body--combined { + display: grid; + grid-template-columns: minmax(0, 1.8fr) minmax(18rem, 1fr); + + .weather-invitation-cards { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + + .weather-invitation-card { + flex-direction: column; + } + + .weather-invitation-title { + font-size: 1rem; + } + + .weather-invitation-note { + font-size: 0.85rem; + } + } } } diff --git a/app/assets/stylesheets/_weather_forecast.scss b/app/assets/stylesheets/_weather_forecast.scss new file mode 100644 index 0000000000..fe8cd9f4e7 --- /dev/null +++ b/app/assets/stylesheets/_weather_forecast.scss @@ -0,0 +1,174 @@ +// The home page's outlook. Jobs use the smaller inline summaries below. +.weather-forecast { + background: $white; + border: 1px solid #dfe8d4; + border-radius: $card-radius; + color: $body-color; + padding: 1.1rem; + + .weather-forecast-title { + background: none; + box-shadow: none; + color: $green; + font-size: 1.15rem; + font-weight: 600; + margin: 0 0 0.35rem; + padding: 0; + } + + .weather-forecast-period, + .weather-forecast-label, + .weather-forecast-note, + .weather-forecast-credit { + color: $ink-muted; + font-size: 0.85rem; + } + + .weather-forecast-figures { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 2rem; + margin-bottom: 0.75rem; + + span, + strong { + display: block; + } + + strong { + font-size: 1.2rem; + } + } + + .weather-forecast-outlook { + margin-bottom: 0.75rem; + } + + .weather-forecast-hazards { + background: #fff3cd; + border-left: 3px solid #9b6700; + border-radius: 2px; + color: #624500; + display: flex; + flex-wrap: wrap; + gap: 0.4rem 1rem; + list-style: none; + padding: 0.65rem 0.75rem; + } + + .weather-forecast-days { + list-style: none; + margin: 0 0 1rem; + padding: 0; + } + + .weather-forecast-day { + align-items: baseline; + border-top: 1px solid #e5e9e0; + display: grid; + font-size: 0.85rem; + gap: 0.2rem 0.75rem; + grid-template-columns: minmax(0, 1fr) auto; + padding: 0.6rem 0; + + time { + font-weight: 600; + } + } + + .weather-forecast-condition { + grid-column: 1; + grid-row: 2; + + i { + color: $green; + margin-right: 0.25rem; + } + } + + .weather-forecast-rain { + grid-column: 2; + grid-row: 2; + } + + .weather-forecast-temperature { + grid-column: 2; + grid-row: 1; + } + + .weather-forecast-credit { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-bottom: 0; + } +} + +.weather-invitation .weather-forecast--summary { + background: transparent; + border: 0; + padding: 0; + + .weather-forecast-figures { + gap: 0.75rem; + + > div { + background: $white; + border: 1px solid #dfe8d4; + border-radius: $card-radius; + flex: 1; + padding: 0.6rem 0.75rem; + } + } + + .weather-forecast-note { + font-size: 0.8rem; + line-height: 1.5; + margin-bottom: 0.6rem; + } + + .weather-forecast-credit { + font-size: 0.75rem; + } +} + +.notepad .notepad-heading { + flex-wrap: wrap; + + .notepad-weather { + align-items: baseline; + color: $ink-muted; + display: inline-flex; + flex-wrap: wrap; + font-size: 0.8rem; + gap: 0.3rem 0.75rem; + justify-content: flex-end; + margin-left: auto; + text-align: right; + } + + .notepad-weather-condition { + i { + margin-right: 0.2rem; + } + } + + .notepad-weather-caution { + color: inherit; + } + + @include media-breakpoint-down(sm) { + .notepad-weather { + flex-basis: 100%; + } + } +} + +.notepad-forecast-credit { + color: $ink-muted; + display: flex; + flex-wrap: wrap; + font-size: 0.75rem; + gap: 0.5rem; + margin: 0.75rem 1.1rem; +} diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index a409380921..a2ab44aed4 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -49,6 +49,7 @@ @import "figures"; @import "frost"; @import "climate"; +@import "weather_forecast"; @import "crop_picker"; @import "garden_cards"; @import "gardens_page"; diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb index 24107da2f6..597d10f4b0 100644 --- a/app/controllers/jobs_controller.rb +++ b/app/controllers/jobs_controller.rb @@ -93,13 +93,21 @@ def render_notepad(status) def render_groups(status) response.set_header('X-Jobs-Done-This-Week', @done_this_week.to_s) - render partial: 'jobs/notepad_groups', locals: { groups: @job_groups, in_garden: garden.present? }, status: + render partial: 'jobs/notepad_groups', + locals: { groups: @job_groups, in_garden: garden.present?, forecast: @weather_forecast }, status: end def load_notepad notepad = JobsNotepad.new(@owner, garden:, pinned: pinned_ids) @job_groups = notepad.groups @done_this_week = notepad.done_this_week + return if garden || !current_member || !WeatherInvitation.enabled?(current_member) + + @weather_forecast = if request.xhr? + WeatherForecast.cached_for(current_member) + else + WeatherForecast.for(current_member) + end end # The garden a notepad on a garden's page is for, if it is. diff --git a/app/helpers/weather_forecast_helper.rb b/app/helpers/weather_forecast_helper.rb new file mode 100644 index 0000000000..d062e381e1 --- /dev/null +++ b/app/helpers/weather_forecast_helper.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +module WeatherForecastHelper + ICONS = { + heat: 'temperature-high', frost: 'snowflake', heavy_rain: 'cloud-showers-heavy', strong_wind: 'wind', + freezing_rain: 'icicles', snow: 'snowflake', thunderstorm: 'cloud-bolt', hail: 'cloud-bolt' + }.freeze + + def forecast_condition_icon(condition) + icon('fas', ICONS.fetch(condition), 'aria-hidden': true) + end + + def forecast_temperature(range) + return t('weather_forecast.missing') unless range + + t('weather_forecast.temperature_range', low: range.first.round, high: range.last.round) + end + + def forecast_rainfall(value) + return t('weather_forecast.missing') if value.nil? + + t('weather_forecast.rainfall_amount', amount: number_with_precision(value, precision: 1, strip_insignificant_zeros: true)) + end + + def forecast_outlook(forecast) + forecast.conditions.map { |condition| t("weather_forecast.conditions.#{condition}") }.to_sentence + end + + def forecast_for_job_group(forecast, group) + return unless forecast&.available? && %i(today week weekend next_weekend).include?(group.key) + + last_day = group.to || group.from + days = forecast.days.select { |day| day[:date].between?(group.from, last_day) } + # Do not present part of a weekend (or week) as the whole period's outlook. + return unless days.pluck(:date).uniq.size == (last_day - group.from).to_i + 1 + + WeatherForecast.new(forecast.place_name, days) + end + + def forecast_header_condition(forecast) + priority = %i(hail thunderstorm freezing_rain snow heat heavy_rain strong_wind frost) + priority.find { |condition| forecast.hazards.include?(condition) } + end + + def forecast_header_details(forecast) + cautions = forecast.hazards.map { |hazard| t("weather_forecast.hazards.#{hazard}") }.to_sentence + [t('weather_forecast.title', place: forecast.place_name), forecast_outlook(forecast), cautions, + t('weather_forecast.caution')].compact_blank.join('. ') + end +end diff --git a/app/models/domesticated_animal.rb b/app/models/domesticated_animal.rb new file mode 100644 index 0000000000..96c3bef392 --- /dev/null +++ b/app/models/domesticated_animal.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Temporary compatibility stub for legacy jobs. There is no animal table in +# the current schema. Use an existing table only for Active Record's metadata, +# never return its rows, and prohibit writes until the legacy links are migrated. +class DomesticatedAnimal < ApplicationRecord + self.table_name = 'jobs' + + default_scope { none } + + def readonly? + true + end +end diff --git a/app/models/weather_forecast.rb b/app/models/weather_forecast.rb new file mode 100644 index 0000000000..d4d32c1c57 --- /dev/null +++ b/app/models/weather_forecast.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +# An outlook for the signed-in member's place, shared by the jobs and +# home pages. Cache by coarse weather cell, not by member or precise address. +class WeatherForecast + CACHE_VERSION = 2 + attr_reader :place_name, :days + + def self.for(member, client: OpenMeteoForecastClient.new, cache: Rails.cache) + return unless member&.located? && Feature.enabled?(:planting_weather, member) + + latitude, longitude = WeatherReading.grid_point(member.latitude, member.longitude) + key = ['weather-forecast', CACHE_VERSION, latitude, longitude] + days = cache.fetch(key, expires_in: 1.hour, race_condition_ttl: 15.seconds) { client.daily(latitude:, longitude:) } + new(member.location_place, days) + rescue OpenMeteoForecastClient::Error => e + Rails.logger.warn("WeatherForecast: #{e.message}") + cache.write(key, [], expires_in: 5.minutes) + new(member.location_place, []) + end + + def initialize(place_name, days) + @place_name = place_name + @days = days + end + + # Notepad edits only need the outlook already fetched for the page. Never + # make adding or crossing off a job wait for a fresh external request. + def self.cached_for(member, cache: Rails.cache) + return unless member&.located? && Feature.enabled?(:planting_weather, member) + + latitude, longitude = WeatherReading.grid_point(member.latitude, member.longitude) + days = cache.read(['weather-forecast', CACHE_VERSION, latitude, longitude]) + new(member.location_place, days) if days + end + + def available? + days.any? + end + + def temperature_range + lows = days.filter_map { |day| day[:temp_min_c] } + highs = days.filter_map { |day| day[:temp_max_c] } + [lows.min, highs.max] if lows.any? && highs.any? + end + + def rainfall_mm + values = days.pluck(:rainfall_mm) + values.sum if values.any? && values.none?(nil) + end + + def conditions + days.filter_map { |day| condition(day) }.uniq + end + + # Only model significant weather events. Routine conditions, fog and missing + # codes deliberately have no label rather than dominating a whole section. + def condition(day) + case day[:weather_code] + when 56, 57, 66, 67 then :freezing_rain + when 71, 73, 75, 77, 85, 86 then :snow + when 95, 97 then :thunderstorm + when 96, 99 then :hail + end + end + + # General gardening cautions, not official weather warnings. Keep these as + # individual conditions: a storm must not hide frost, heat or strong wind. + def hazards + risks = [] + risks << :frost if days.any? { |day| day[:temp_min_c] && day[:temp_min_c] <= 0 } + risks << :heat if days.any? { |day| day[:temp_max_c] && day[:temp_max_c] >= 32 } + risks << :heavy_rain if days.any? { |day| day[:rainfall_mm] && day[:rainfall_mm] >= 20 } + risks << :strong_wind if days.any? { |day| day[:wind_gust_kmh] && day[:wind_gust_kmh] >= 50 } + risks.concat(conditions) + risks << :snow if days.any? { |day| day[:snowfall_cm]&.positive? } + risks.uniq + end +end diff --git a/app/models/weather_invitation.rb b/app/models/weather_invitation.rb index 1b44c7dda3..72ed957153 100644 --- a/app/models/weather_invitation.rb +++ b/app/models/weather_invitation.rb @@ -31,6 +31,13 @@ def place_name @member.location_place end + # A live outlook, independent of whether the historical climate is loaded. + def forecast + return @forecast if defined?(@forecast) + + @forecast = WeatherForecast.for(@member) + end + # Whether the front page shows it: the weather feature is switched on. def self.enabled?(member = nil) Feature.enabled?(:planting_weather, member) diff --git a/app/services/open_meteo_forecast_client.rb b/app/services/open_meteo_forecast_client.rb new file mode 100644 index 0000000000..95c6f66d9d --- /dev/null +++ b/app/services/open_meteo_forecast_client.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +# Forecasts are deliberately separate from ERA5 history: never save predicted +# values as WeatherReadings, or use last year's weather as a live forecast. +class OpenMeteoForecastClient + class Error < StandardError; end + + URL = 'https://api.open-meteo.com' + VARIABLES = { + 'temperature_2m_min' => :temp_min_c, + 'temperature_2m_max' => :temp_max_c, + 'rain_sum' => :rainfall_mm, + 'weather_code' => :weather_code, + 'wind_gusts_10m_max' => :wind_gust_kmh, + 'snowfall_sum' => :snowfall_cm + }.freeze + + def initialize(connection: nil) + @connection = connection || Faraday.new(url: URL, headers: { 'User-Agent' => OpenMeteoClient::USER_AGENT }) do |f| + f.options.open_timeout = 2 + f.options.timeout = 3 + end + end + + def daily(latitude:, longitude:) + response = @connection.get('/v1/forecast', latitude:, longitude:, daily: VARIABLES.keys.join(','), + forecast_days: 14, timezone: 'auto', temperature_unit: 'celsius', + wind_speed_unit: 'kmh', precipitation_unit: 'mm') + raise Error, "Open-Meteo answered #{response.status}" unless response.success? + + parse(JSON.parse(response.body)) + rescue Faraday::Error, JSON::ParserError, ArgumentError => e + raise Error, e.message + end + + private + + def parse(body) + daily = body.is_a?(Hash) && body['daily'] + raise Error, 'Missing daily forecast' unless daily.is_a?(Hash) && daily['time'].is_a?(Array) + raise Error, 'Invalid daily forecast' unless VARIABLES.keys.all? { |key| daily[key].nil? || daily[key].is_a?(Array) } + + daily['time'].first(14).each_with_index.map do |date, index| + raise Error, 'Invalid forecast date' unless date.is_a?(String) + + values = VARIABLES.to_h do |key, name| + value = daily.dig(key, index) + [name, value.is_a?(Numeric) && value.finite? ? value : nil] + end + values.merge(date: Date.iso8601(date)) + end + end +end diff --git a/app/views/home/_weather_invitation.html.haml b/app/views/home/_weather_invitation.html.haml index 16304ddb76..76d952207e 100644 --- a/app/views/home/_weather_invitation.html.haml +++ b/app/views/home/_weather_invitation.html.haml @@ -1,29 +1,35 @@ --# The invitation at the top of the front page to see the weather at your own place: frost, rain and temperature headlines --# that lead to the place's page. See WeatherInvitation. +-# History and forecast are distinct, alongside one another when both are ready. - state = invitation.state +- forecast = invitation.forecast .record-page.weather-invitation %section .section-header %h2= t('home.weather_invitation.title') - .weather-invitation-body - %p.weather-invitation-intro - - if state == :loading - = frost_icon(:late_possible) - = weather_invitation_intro(invitation) - .weather-invitation-cards - - weather_invitation_cards(invitation).each do |card| - .weather-invitation-card - .weather-invitation-icon{ class: "weather-invitation-icon--#{state == :ready ? card[:measure] : 'none'}" } - = weather_invitation_icon(card[:measure]) - %div - .weather-invitation-label= card[:label] - .weather-invitation-title= card[:title] - .weather-invitation-note= card[:note] - .weather-invitation-actions - - case state - - when :ready - = link_to t('home.weather_invitation.see'), place_path(current_member.location), class: 'btn btn-success' - - when :no_location - = render 'home/dashboard/location_picker', label: t('home.weather_invitation.add_location'), button_class: 'btn btn-success' - - else - = render 'home/dashboard/location_picker', label: t('home.weather_invitation.change_location'), button_class: 'btn btn-link p-0' + .weather-invitation-body{ class: ('weather-invitation-body--combined' if state == :ready && forecast&.available?) } + .weather-invitation-history + %p.weather-invitation-intro + = frost_icon(:late_possible) if state == :loading + = weather_invitation_intro(invitation) + - if state == :ready || !forecast&.available? + .weather-invitation-cards + - weather_invitation_cards(invitation).each do |card| + .weather-invitation-card + .weather-invitation-icon{ class: "weather-invitation-icon--#{state == :ready ? card[:measure] : 'none'}" } + = weather_invitation_icon(card[:measure]) + %div + .weather-invitation-label= card[:label] + .weather-invitation-title= card[:title] + .weather-invitation-note= card[:note] + .weather-invitation-actions + - case state + - when :ready + = link_to t('home.weather_invitation.see'), place_path(current_member.location), class: 'btn btn-success' + - when :no_location + - label = t('home.weather_invitation.add_location') + = render 'home/dashboard/location_picker', label: label, button_class: 'btn btn-success' + - else + - label = t('home.weather_invitation.change_location') + = render 'home/dashboard/location_picker', label: label, button_class: 'btn btn-link p-0' + - if forecast + .weather-invitation-forecast + = render 'weather/forecast', forecast: forecast, daily: false, heading: :h3 diff --git a/app/views/jobs/_notepad.html.haml b/app/views/jobs/_notepad.html.haml index 5c45b86d9a..b5c2bbc165 100644 --- a/app/views/jobs/_notepad.html.haml +++ b/app/views/jobs/_notepad.html.haml @@ -28,7 +28,12 @@ = render 'jobs/ideas', owner: owner unless garden || !local_assigns.fetch(:ideas_banner, true) %button.btn.btn-sm.btn-outline-secondary.notepad-hide-done{ id: 'notepad-hide-done', type: 'button', hidden: true, data: { url: member_jobs_path(owner) } }= t('jobs.pad.hide_done') - #notepad-groups{ data: { celebrations: job_celebrations.to_json, garden_id: garden&.id } }= render 'jobs/notepad_groups', groups:, in_garden: garden.present? + #notepad-groups{ data: { celebrations: job_celebrations.to_json, garden_id: garden&.id } } + = render 'jobs/notepad_groups', groups:, in_garden: garden.present?, forecast: local_assigns[:forecast] + - if local_assigns[:forecast]&.available? + %p.notepad-forecast-credit + = link_to t('weather_forecast.source'), 'https://open-meteo.com/' + = link_to 'CC BY 4.0', 'https://creativecommons.org/licenses/by/4.0/' -# The snail keeps the jobs pages company; on a garden's page the list is just the list. - unless garden .notepad-snail diff --git a/app/views/jobs/_notepad_groups.html.haml b/app/views/jobs/_notepad_groups.html.haml index 51e38635db..d3eaac43ad 100644 --- a/app/views/jobs/_notepad_groups.html.haml +++ b/app/views/jobs/_notepad_groups.html.haml @@ -14,6 +14,8 @@ %small= "#{l(group.from, format: '%a %-d')} – #{l(group.to, format: '%a %-d %b')}" - elsif group.key == :someday %small= t('jobs.pad.someday_note') + - if (weather = forecast_for_job_group(local_assigns[:forecast], group)) + = render 'jobs/section_weather', forecast: weather - if group.jobs.empty? %p.notepad-drop-hint= t('jobs.pad.drop_here') -# Later is rolled up until asked for: it is not for today's list. diff --git a/app/views/jobs/_section_weather.html.haml b/app/views/jobs/_section_weather.html.haml new file mode 100644 index 0000000000..226c688f74 --- /dev/null +++ b/app/views/jobs/_section_weather.html.haml @@ -0,0 +1,14 @@ +- condition = forecast_header_condition(forecast) +%span.notepad-weather{ title: forecast_header_details(forecast) } + - if condition + %span.notepad-weather-condition + = forecast_condition_icon(condition) + = t("weather_forecast.hazards.#{condition}") + - if forecast.temperature_range + %span= forecast_temperature(forecast.temperature_range) + - unless forecast.rainfall_mm.nil? + %span.notepad-weather-rain= forecast_rainfall(forecast.rainfall_mm) + - if forecast.hazards.any? + %span.notepad-weather-caution + = icon('fas', 'triangle-exclamation', 'aria-hidden': true) + %span.visually-hidden= forecast.hazards.map { |hazard| t("weather_forecast.hazards.#{hazard}") }.to_sentence diff --git a/app/views/jobs/index.html.haml b/app/views/jobs/index.html.haml index e6ee6a9141..cce44c5463 100644 --- a/app/views/jobs/index.html.haml +++ b/app/views/jobs/index.html.haml @@ -20,40 +20,42 @@ = render 'jobs/ideas_modal' .row - -# A member's own jobs are a notepad across the page. Anyone else's, or everyone's, - -# are a list, with its options beside it. - - if @job_groups - .col-12 - = render 'jobs/notepad', owner: @owner, groups: @job_groups, done_this_week: @done_this_week, ideas_banner: false - - else - .col-md-3 - %h1.h2 - = job_icon - = t('.sidebar_heading') - = link_to show_inactive_tickbox_path('jobs', owner: @owner, crop: nil, show_all: @show_all) do - = check_box_tag 'active', 'all', @show_all - = t('.include_finished_jobs') - - if @owner.present? && @owner != current_member - %hr - = render @owner, cached: true + .col-12 + - if @job_groups + = render 'jobs/notepad', owner: @owner, groups: @job_groups, done_this_week: @done_this_week, + ideas_banner: false, forecast: @weather_forecast + - else + .row + .col-md-3 + %h1.h2 + = job_icon + = t('.sidebar_heading') + = link_to show_inactive_tickbox_path('jobs', owner: @owner, crop: nil, show_all: @show_all) do + = check_box_tag 'active', 'all', @show_all + = t('.include_finished_jobs') + - if @owner.present? && @owner != current_member + %hr + = render @owner, cached: true - %section.open-data.mt-3 - %h2= t('.open_data') - %p= t('label.data') - - ['csv', 'json', 'rss'].each do |format| - .badge.text-bg-info - = link_to (@owner ? member_jobs_path(@owner, format: format) : jobs_path(format: format)) do - = icon 'fas', format.to_s - = format.upcase - - if @owner - .badge.text-bg-info= link_to "iCal", member_jobs_path(@owner, format: 'ics', protocol: 'webcal', only_path: false) - .badge.text-bg-success= link_to t('.api_methods'), '/api-docs' + %section.open-data.mt-3 + %h2= t('.open_data') + %p= t('label.data') + - %w(csv json rss).each do |format| + .badge.text-bg-info + - export_path = @owner ? member_jobs_path(@owner, format: format) : jobs_path(format: format) + = link_to export_path do + = icon 'fas', format.to_s + = format.upcase + - if @owner + - calendar_path = member_jobs_path(@owner, format: 'ics', protocol: 'webcal', only_path: false) + .badge.text-bg-info= link_to 'iCal', calendar_path + .badge.text-bg-success= link_to t('.api_methods'), '/api-docs' - .col-md-9 - %section - %h2= title('jobs', @owner, nil, nil) - = will_paginate @jobs - .index-cards - - @jobs.each do |a| - = render 'jobs/card', job: a - = will_paginate @jobs + .col-md-9 + %section + %h2= title('jobs', @owner, nil, nil) + = will_paginate @jobs + .index-cards + - @jobs.each do |a| + = render 'jobs/card', job: a + = will_paginate @jobs diff --git a/app/views/weather/_forecast.html.haml b/app/views/weather/_forecast.html.haml new file mode 100644 index 0000000000..250c896dae --- /dev/null +++ b/app/views/weather/_forecast.html.haml @@ -0,0 +1,42 @@ +.weather-forecast{ class: local_assigns.fetch(:daily, true) ? 'weather-forecast--daily' : 'weather-forecast--summary' } + = content_tag local_assigns.fetch(:heading, :h2), t('weather_forecast.title', place: forecast.place_name), + class: 'weather-forecast-title' + - if forecast.available? + %p.weather-forecast-period + - from = l(forecast.days.first[:date], format: :short) + - to = l(forecast.days.last[:date], format: :short) + = t('weather_forecast.period', from: from, to: to) + .weather-forecast-figures + %div + %span.weather-forecast-label= t('weather_forecast.temperature') + %strong= forecast_temperature(forecast.temperature_range) + %div + %span.weather-forecast-label= t('weather_forecast.rainfall') + %strong= forecast_rainfall(forecast.rainfall_mm) + - if (outlook = forecast_outlook(forecast)).present? + %p.weather-forecast-outlook= outlook + - if forecast.hazards.any? + %ul.weather-forecast-hazards + - forecast.hazards.each do |hazard| + %li + = icon('fas', 'triangle-exclamation', 'aria-hidden': true) + = t("weather_forecast.hazards.#{hazard}") + - if local_assigns.fetch(:daily, true) + %ul.weather-forecast-days + - forecast.days.each do |day| + - condition = forecast.condition(day) + %li.weather-forecast-day + %time{ datetime: day[:date].iso8601 }= l(day[:date], format: '%a %-d') + - if condition + %span.weather-forecast-condition + = forecast_condition_icon(condition) + = t("weather_forecast.conditions.#{condition}") + %span.weather-forecast-temperature + = forecast_temperature([day[:temp_min_c], day[:temp_max_c]]) if day[:temp_min_c] && day[:temp_max_c] + %span.weather-forecast-rain= forecast_rainfall(day[:rainfall_mm]) + %p.weather-forecast-note= t('weather_forecast.caution') + %p.weather-forecast-credit + = link_to t('weather_forecast.source'), 'https://open-meteo.com/' + = link_to 'CC BY 4.0', 'https://creativecommons.org/licenses/by/4.0/' + - else + %p.weather-forecast-unavailable= t('weather_forecast.unavailable') diff --git a/config/locales/de.yml b/config/locales/de.yml index 8135dc230f..d05a3908e6 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -1,5 +1,39 @@ --- de: + weather_forecast: + title: Vorhersage für %{place} + period: "%{from} – %{to}" + temperature: Tiefst- / Höchsttemperatur + temperature_range: "%{low}–%{high} °C" + rainfall: Regen insgesamt + rainfall_amount: "%{amount} mm" + missing: Nicht verfügbar + unavailable: Die Wettervorhersage ist vorübergehend nicht verfügbar. Bitte versuche es später erneut. + caution: Vorhersagen können sich ändern. Beachte die amtlichen Warnungen deines örtlichen Wetterdienstes. + source: Vorhersage von Open-Meteo + conditions: + clear: Klarer Himmel + partly_cloudy: Teilweise bewölkt + overcast: Bedeckt + fog: Nebel + drizzle: Nieselregen + freezing_rain: Gefrierender Regen + rain: Regen + snow: Schnee + showers: Schauer + thunderstorm: Gewitter + hail: Gewitter mit Hagel + unknown: Wetterlage nicht verfügbar + hazards: + frost: Frost möglich + heat: Hohe Temperaturen + heavy_rain: Starkregen möglich + strong_wind: Starke Böen möglich + thunderstorm: Gewitter möglich + hail: Hagel möglich + snow: Schnee möglich + freezing_rain: Glätte möglich + fog: Nebel möglich likes: description_html: '%{member} gefällt %{item}' shared: diff --git a/config/locales/en.yml b/config/locales/en.yml index 9442171f22..0d30fcc711 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,5 +1,39 @@ --- en: + weather_forecast: + title: Forecast for %{place} + period: "%{from} – %{to}" + temperature: Low / high + temperature_range: "%{low}–%{high} °C" + rainfall: Total rain + rainfall_amount: "%{amount} mm" + missing: Not available + unavailable: The forecast is temporarily unavailable. Please try again later. + caution: Forecasts can change. Check your local weather service for official warnings. + source: Forecast by Open-Meteo + conditions: + clear: Clear skies + partly_cloudy: Partly cloudy + overcast: Overcast + fog: Fog + drizzle: Drizzle + freezing_rain: Freezing rain + rain: Rain + snow: Snow + showers: Showers + thunderstorm: Thunderstorms + hail: Thunderstorms with hail + unknown: Conditions unavailable + hazards: + frost: Frost possible + heat: High temperatures + heavy_rain: Heavy rain possible + strong_wind: Strong gusts possible + thunderstorm: Thunderstorms possible + hail: Hail possible + snow: Snow possible + freezing_rain: Icy conditions possible + fog: Fog possible likes: description_html: '%{member} liked %{item}' shared: diff --git a/config/locales/es.yml b/config/locales/es.yml index 391e05c35b..a6994b747d 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -1,5 +1,39 @@ --- es: + weather_forecast: + title: Pronóstico para %{place} + period: "%{from} – %{to}" + temperature: Mínima / máxima + temperature_range: "%{low}–%{high} °C" + rainfall: Lluvia total + rainfall_amount: "%{amount} mm" + missing: No disponible + unavailable: El pronóstico no está disponible temporalmente. Vuelve a intentarlo más tarde. + caution: El pronóstico puede cambiar. Consulta los avisos oficiales de tu servicio meteorológico local. + source: Pronóstico de Open-Meteo + conditions: + clear: Cielo despejado + partly_cloudy: Parcialmente nublado + overcast: Cubierto + fog: Niebla + drizzle: Llovizna + freezing_rain: Lluvia engelante + rain: Lluvia + snow: Nieve + showers: Chubascos + thunderstorm: Tormentas eléctricas + hail: Tormentas con granizo + unknown: Condiciones no disponibles + hazards: + frost: Posibles heladas + heat: Temperaturas altas + heavy_rain: Posibles lluvias intensas + strong_wind: Posibles rachas fuertes + thunderstorm: Posibles tormentas eléctricas + hail: Posible granizo + snow: Posible nieve + freezing_rain: Posible formación de hielo + fog: Posible niebla likes: description_html: 'A %{member} le gustó %{item}' shared: diff --git a/config/locales/fr.yml b/config/locales/fr.yml index e18634006f..e742e72c2f 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -1,5 +1,39 @@ --- fr: + weather_forecast: + title: Prévisions pour %{place} + period: "%{from} – %{to}" + temperature: Minimale / maximale + temperature_range: "%{low}–%{high} °C" + rainfall: Pluie cumulée + rainfall_amount: "%{amount} mm" + missing: Non disponible + unavailable: Les prévisions sont temporairement indisponibles. Veuillez réessayer plus tard. + caution: Les prévisions peuvent changer. Consultez votre service météorologique local pour les alertes officielles. + source: Prévisions par Open-Meteo + conditions: + clear: Ciel dégagé + partly_cloudy: Partiellement nuageux + overcast: Couvert + fog: Brouillard + drizzle: Bruine + freezing_rain: Pluie verglaçante + rain: Pluie + snow: Neige + showers: Averses + thunderstorm: Orages + hail: Orages avec grêle + unknown: Conditions indisponibles + hazards: + frost: Gel possible + heat: Températures élevées + heavy_rain: Fortes pluies possibles + strong_wind: Fortes rafales possibles + thunderstorm: Orages possibles + hail: Grêle possible + snow: Neige possible + freezing_rain: Verglas possible + fog: Brouillard possible likes: description_html: '%{member} a aimé %{item}' shared: diff --git a/config/locales/ja.yml b/config/locales/ja.yml index a79fbdacf0..67ad1a463d 100644 --- a/config/locales/ja.yml +++ b/config/locales/ja.yml @@ -1,5 +1,39 @@ --- ja: + weather_forecast: + title: "%{place}の天気予報" + period: "%{from}~%{to}" + temperature: 最低 / 最高気温 + temperature_range: "%{low}~%{high} °C" + rainfall: 合計降雨量 + rainfall_amount: "%{amount} mm" + missing: データなし + unavailable: 天気予報を一時的に取得できません。しばらくしてからもう一度お試しください。 + caution: 予報は変わることがあります。公式の警報・注意報は地域の気象機関でご確認ください。 + source: Open-Meteoの天気予報 + conditions: + clear: 晴れ + partly_cloudy: 晴れ時々曇り + overcast: 曇り + fog: 霧 + drizzle: 霧雨 + freezing_rain: 着氷性の雨 + rain: 雨 + snow: 雪 + showers: にわか雨 + thunderstorm: 雷雨 + hail: ひょうを伴う雷雨 + unknown: 天気のデータなし + hazards: + frost: 霜のおそれ + heat: 高温 + heavy_rain: 大雨のおそれ + strong_wind: 強い突風のおそれ + thunderstorm: 雷雨のおそれ + hail: ひょうのおそれ + snow: 雪のおそれ + freezing_rain: 凍結のおそれ + fog: 霧のおそれ activerecord: models: post: 投稿 diff --git a/config/locales/zh.yml b/config/locales/zh.yml index 777d8d0412..5b746bf2f2 100644 --- a/config/locales/zh.yml +++ b/config/locales/zh.yml @@ -1,5 +1,39 @@ --- zh: + weather_forecast: + title: "%{place}的天气预报" + period: "%{from}至%{to}" + temperature: 最低 / 最高气温 + temperature_range: "%{low}至%{high} °C" + rainfall: 总降雨量 + rainfall_amount: "%{amount} mm" + missing: 暂无数据 + unavailable: 暂时无法获取天气预报,请稍后重试。 + caution: 预报可能变化。请查看当地气象部门发布的官方预警。 + source: Open-Meteo天气预报 + conditions: + clear: 晴 + partly_cloudy: 多云 + overcast: 阴 + fog: 雾 + drizzle: 毛毛雨 + freezing_rain: 冻雨 + rain: 雨 + snow: 雪 + showers: 阵雨 + thunderstorm: 雷暴 + hail: 雷暴伴有冰雹 + unknown: 暂无天气状况数据 + hazards: + frost: 可能有霜冻 + heat: 高温 + heavy_rain: 可能有强降雨 + strong_wind: 可能有强阵风 + thunderstorm: 可能有雷暴 + hail: 可能有冰雹 + snow: 可能有降雪 + freezing_rain: 可能结冰 + fog: 可能有雾 likes: description_html: '%{member}赞了%{item}' shared: diff --git a/spec/helpers/weather_forecast_helper_spec.rb b/spec/helpers/weather_forecast_helper_spec.rb new file mode 100644 index 0000000000..9ae3e030b3 --- /dev/null +++ b/spec/helpers/weather_forecast_helper_spec.rb @@ -0,0 +1,108 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe WeatherForecastHelper do + describe '#forecast_temperature' do + it 'formats the temperature range' do + expect(helper.forecast_temperature([-1.2, 18.4])).to eq I18n.t('weather_forecast.temperature_range', low: -1, high: 18) + end + + it 'identifies missing temperatures' do + expect(helper.forecast_temperature(nil)).to eq I18n.t('weather_forecast.missing') + end + end + + describe '#forecast_rainfall' do + it 'keeps zero rainfall as a measurement' do + expect(helper.forecast_rainfall(0)).to eq I18n.t('weather_forecast.rainfall_amount', amount: '0') + end + + it 'identifies missing rain data' do + expect(helper.forecast_rainfall(nil)).to eq I18n.t('weather_forecast.missing') + end + end + + describe '#forecast_outlook' do + it 'translates the forecast conditions' do + forecast = WeatherForecast.new('Greenwich', [{ weather_code: 95 }]) + expect(helper.forecast_outlook(forecast)).to eq I18n.t('weather_forecast.conditions.thunderstorm') + end + end + + describe '#forecast_for_job_group' do + subject(:summary) { helper.forecast_for_job_group(forecast, group) } + + let(:today) { Date.new(2026, 12, 3) } + let(:days) do + 7.times.map do |offset| + { date: today + offset, temp_min_c: offset, temp_max_c: offset + 10, rainfall_mm: offset, weather_code: 0 } + end + end + let(:forecast) { WeatherForecast.new('Greenwich', days) } + let(:group) { JobList::Group.new(key: :weekend, from: today + 2, to: today + 3) } + + it 'uses only the section’s forecast dates' do + expect(summary.days.pluck(:date)).to eq [today + 2, today + 3] + end + + it 'summarizes the section’s temperatures' do + expect(summary.temperature_range).to eq [2, 13] + end + + it 'sums only the section’s rainfall' do + expect(summary.rainfall_mm).to eq 5 + end + + context 'with today’s section' do + let(:group) { JobList::Group.new(key: :today, from: today) } + + it 'uses today alone' do + expect(summary.days.pluck(:date)).to eq [today] + end + end + + context 'with a partially covered period' do + let(:group) { JobList::Group.new(key: :next_weekend, from: today + 6, to: today + 7) } + + it 'does not label a partial forecast as the whole weekend' do + expect(summary).to be_nil + end + end + + context 'without a forecast' do + let(:forecast) { nil } + + it 'leaves out the summary' do + expect(summary).to be_nil + end + end + + %i(overdue later someday done).each do |key| + context "with the #{key} section" do + let(:group) { JobList::Group.new(key:, from: today, to: today + 1) } + + it 'does not attach a forecast to an undated or past section' do + expect(summary).to be_nil + end + end + end + end + + describe '#forecast_header_condition' do + it 'does not label routine conditions or fog' do + forecast = WeatherForecast.new('Adelaide', [{ weather_code: 3 }, { weather_code: 45 }]) + expect(helper.forecast_header_condition(forecast)).to be_nil + end + + it 'indicates high temperatures without claiming an official heat wave' do + forecast = WeatherForecast.new('Adelaide', [{ weather_code: 0, temp_max_c: 40 }]) + expect(helper.forecast_header_condition(forecast)).to eq :heat + end + + it 'prioritizes storms over clear skies' do + forecast = WeatherForecast.new('Greenwich', [{ weather_code: 0 }, { weather_code: 95 }]) + expect(helper.forecast_header_condition(forecast)).to eq :thunderstorm + end + end +end diff --git a/spec/models/domesticated_animal_spec.rb b/spec/models/domesticated_animal_spec.rb new file mode 100644 index 0000000000..5b039c6477 --- /dev/null +++ b/spec/models/domesticated_animal_spec.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe DomesticatedAnimal do + it 'prevents writes through the temporary stub' do + expect { described_class.create! }.to raise_error(ActiveRecord::ReadOnlyRecord) + end +end diff --git a/spec/models/weather_forecast_spec.rb b/spec/models/weather_forecast_spec.rb new file mode 100644 index 0000000000..383aab0f34 --- /dev/null +++ b/spec/models/weather_forecast_spec.rb @@ -0,0 +1,213 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe WeatherForecast, flipper: :planting_weather do + let(:day) do + { date: Date.new(2026, 12, 3), temp_min_c: 4, temp_max_c: 18, rainfall_mm: 2, weather_code: 0, wind_gust_kmh: 10 } + end + + describe '.for' do + subject(:forecast) { described_class.for(member, client:, cache:) } + + let(:member) { build(:london_member) } + let(:client) { instance_double(OpenMeteoForecastClient, daily: [day]) } + let(:cache) { ActiveSupport::Cache::MemoryStore.new } + + it 'fetches the member’s weather cell' do + expect(client).to receive(:daily).with(latitude: 51.5, longitude: 0.0) + forecast + end + + it 'shares cached forecasts between requests' do + expect(client).to receive(:daily).once + forecast + described_class.for(member, client:, cache:) + end + + it 'refreshes after an hour' do + expect(client).to receive(:daily).twice + forecast + Timecop.travel(61.minutes.from_now) { described_class.for(member, client:, cache:) } + end + + it 'shares cached forecasts between members in the same cell' do + expect(client).to receive(:daily).once + forecast + neighbour = build(:member, location: 'Nearby, UK', latitude: 51.49, longitude: 0.01) + described_class.for(neighbour, client:, cache:) + end + + context 'without a location' do + let(:member) { build(:member) } + + it 'does not fetch a forecast' do + expect(client).not_to receive(:daily) + forecast + end + + it 'has no outlook' do + expect(forecast).to be_nil + end + end + + context 'when the weather feature is off', flipper: [] do + it 'does not call the external API' do + expect(client).not_to receive(:daily) + forecast + end + + it 'returns no forecast' do + expect(forecast).to be_nil + end + end + + context 'without a signed-in member' do + let(:member) { nil } + + it 'has no outlook' do + expect(forecast).to be_nil + end + end + + context 'when the API fails' do + before { allow(client).to receive(:daily).and_raise(OpenMeteoForecastClient::Error, 'unavailable') } + + it 'returns an unavailable outlook' do + expect(forecast).not_to be_available + end + + it 'does not retry on every page view' do + expect(client).to receive(:daily).once + forecast + described_class.for(member, client:, cache:) + end + + it 'retries after five minutes' do + expect(client).to receive(:daily).twice + forecast + Timecop.travel(6.minutes.from_now) { described_class.for(member, client:, cache:) } + end + end + end + + describe '#hazards' do + subject(:hazards) { described_class.new('Greenwich', [day.merge(values)]).hazards } + + { + frost: { temp_min_c: 0 }, heat: { temp_max_c: 32 }, heavy_rain: { rainfall_mm: 20 }, + strong_wind: { wind_gust_kmh: 50 }, thunderstorm: { weather_code: 95 }, hail: { weather_code: 99 }, + freezing_rain: { weather_code: 66 }, snow: { snowfall_cm: 1 } + }.each do |hazard, measurements| + context "with #{hazard}" do + let(:values) { measurements } + + it 'includes the caution' do + expect(hazards).to include hazard + end + end + end + + context 'with several adverse conditions' do + let(:values) { { temp_min_c: -2, temp_max_c: 33, rainfall_mm: 25, wind_gust_kmh: 65, weather_code: 95 } } + + it 'keeps all cautions' do + expect(hazards).to contain_exactly(:frost, :heat, :heavy_rain, :strong_wind, :thunderstorm) + end + end + + context 'with mild weather' do + let(:values) { {} } + + it 'has no cautions' do + expect(hazards).to be_empty + end + end + end + + describe '.cached_for' do + subject(:forecast) { described_class.cached_for(member, cache:) } + + let(:member) { build(:london_member) } + let(:cache) { ActiveSupport::Cache::MemoryStore.new } + let(:client) { instance_double(OpenMeteoForecastClient, daily: [day]) } + + it 'returns a previously fetched outlook' do + described_class.for(member, client:, cache:) + expect(forecast.days).to eq [day] + end + + it 'does not make external requests on a cache miss' do + expect(OpenMeteoForecastClient).not_to receive(:new) + forecast + end + + it 'returns no outlook on a cache miss' do + expect(forecast).to be_nil + end + + context 'when the feature is disabled after fetching a forecast' do + before do + described_class.for(member, client:, cache:) + Flipper.disable(:planting_weather) + end + + it 'does not expose the cached forecast' do + expect(forecast).to be_nil + end + end + end + + describe '#rainfall_mm' do + it 'totals the forecast rainfall' do + expect(described_class.new('Greenwich', [day, day]).rainfall_mm).to eq 4 + end + + it 'does not report a misleading total with missing rain data' do + forecast = described_class.new('Greenwich', [day, day.merge(rainfall_mm: nil)]) + expect(forecast.rainfall_mm).to be_nil + end + end + + describe '#temperature_range' do + it 'summarizes the coldest low and warmest high' do + forecast = described_class.new('Greenwich', [day, day.merge(temp_min_c: -2, temp_max_c: 20)]) + expect(forecast.temperature_range).to eq [-2, 20] + end + + it 'does not invent missing temperatures' do + forecast = described_class.new('Greenwich', [day.merge(temp_min_c: nil)]) + expect(forecast.temperature_range).to be_nil + end + end + + describe '#condition' do + [0, 1, 2, 3, 45, 48, 51, 53, 55, 61, 63, 65, 80, 81, 82].each do |code| + context "with non-extreme weather code #{code}" do + it 'does not model a condition' do + expect(described_class.new('Greenwich', []).condition(weather_code: code)).to be_nil + end + end + end + + it 'recognizes heavy thunderstorms' do + expect(described_class.new('Greenwich', []).condition(weather_code: 97)).to eq :thunderstorm + end + + it 'handles missing weather codes' do + expect(described_class.new('Greenwich', []).condition({})).to be_nil + end + end + + describe '#conditions' do + it 'omits fog rather than substituting unknown conditions' do + forecast = described_class.new('Adelaide', [day.merge(weather_code: 45), day.merge(weather_code: 48)]) + expect(forecast.conditions).to be_empty + end + + it 'does not turn fog into a hazard' do + forecast = described_class.new('Adelaide', [day.merge(weather_code: 45)]) + expect(forecast.hazards).to be_empty + end + end +end diff --git a/spec/requests/home_controller_index_weather_invitation_spec.rb b/spec/requests/home_controller_index_weather_invitation_spec.rb index 48e7658699..6c3ca28e9c 100644 --- a/spec/requests/home_controller_index_weather_invitation_spec.rb +++ b/spec/requests/home_controller_index_weather_invitation_spec.rb @@ -42,4 +42,60 @@ it { is_expected.to have_no_css('.weather-invitation') } end + + context 'with a live forecast but no historical weather' do + before do + days = [{ date: Date.new(2026, 12, 3), temp_min_c: 3, temp_max_c: 12, rainfall_mm: 25, weather_code: 95 }] + allow(WeatherForecast).to receive(:for).with(member).and_return(WeatherForecast.new('Greenwich', days)) + get root_path + end + + it 'shows the forecast summary' do + expect(page).to have_css('.weather-invitation .weather-forecast--summary') + end + + it 'keeps the historical introduction visible' do + expect(page).to have_css('.weather-invitation-intro') + end + + it 'includes adverse conditions' do + expect(page).to have_css('.weather-forecast-hazards li', count: 2) + end + + it 'does not present historical loading cards as the forecast' do + expect(page).to have_no_css('.weather-invitation-card') + end + + context 'when historical weather is ready' do + before do + create(:frost_stat, latitude: 51.5, longitude: 0.0, threshold_c: FrostCalculator::FROST_DANGER_C) + get root_path + end + + it 'shows the ready introduction alongside the forecast' do + intro = I18n.t('home.weather_invitation.intro.ready', place: 'Greenwich') + expect(page).to have_css('.weather-invitation-intro', text: intro) + end + + it 'keeps the historical cards visible alongside the forecast' do + expect(page).to have_css('.weather-invitation-card', count: 3) + end + + it 'puts the historical introduction before the forecast' do + expect(page).to have_css('.weather-invitation-body > .weather-invitation-history:first-child .weather-invitation-intro') + end + + it 'groups history and forecast into the combined layout' do + expect(page).to have_css('.weather-invitation-body--combined > .weather-invitation-forecast') + end + + it 'keeps the place link with the historical cards' do + expect(page).to have_css('.weather-invitation-history .weather-invitation-actions a') + end + + it 'uses a subordinate heading for the forecast' do + expect(page).to have_css('.weather-invitation-forecast h3.weather-forecast-title') + end + end + end end diff --git a/spec/requests/jobs_controller_index_forecast_spec.rb b/spec/requests/jobs_controller_index_forecast_spec.rb new file mode 100644 index 0000000000..1c03e25e07 --- /dev/null +++ b/spec/requests/jobs_controller_index_forecast_spec.rb @@ -0,0 +1,178 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe JobsController, '#index forecast', flipper: :planting_weather do + let(:member) { create(:london_member) } + let(:days) do + 14.times.map do |offset| + { date: Date.current + offset, temp_min_c: -1, temp_max_c: 8, rainfall_mm: 22, weather_code: 95 } + end + end + let(:forecast) { WeatherForecast.new('Greenwich', days) } + + before do + allow(WeatherForecast).to receive_messages(for: forecast, cached_for: forecast) + sign_in member + end + + it 'puts weather inline with the section heading' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-group-today .notepad-heading .notepad-weather')).to be_present + end + + it 'keeps the full-width notepad' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.col-12 > .notepad')).to be_present + end + + it 'indicates adverse weather without an alert panel' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-group-today .notepad-weather-caution')).to be_present + end + + it 'does not use personal forecasts on another member’s list' do + expect(WeatherForecast).not_to receive(:for) + get member_jobs_path(create(:member)) + end + + it 'does not show weather for undated sections' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-group-someday .notepad-weather')).to be_nil + end + + it 'removes the large weather sidebar' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.jobs-forecast')).to be_nil + end + + it 'does not fetch forecasts for data exports' do + expect(WeatherForecast).not_to receive(:for) + get member_jobs_path(member, format: :json) + end + + it 'does not fetch forecasts when updating notepad groups' do + expect(WeatherForecast).not_to receive(:for) + get member_jobs_path(member), xhr: true + end + + it 'retains cached weather when refreshing notepad groups' do + get member_jobs_path(member), xhr: true + expect(response.parsed_body.at_css('.notepad-group-today .notepad-weather')).to be_present + end + + it 'retains cached weather after adding a job' do + post jobs_path, params: { job: { name: 'Water the garden' } }, xhr: true + expect(response.parsed_body.at_css('.notepad-group-today .notepad-weather')).to be_present + end + + it 'retains cached weather after completing a job' do + job = create(:job, owner: member) + patch job_path(job), params: { job: { finished: true } }, xhr: true + expect(response.parsed_body.at_css('.notepad-group-today .notepad-weather')).to be_present + end + + context 'when signed out' do + before { sign_out member } + + it 'does not fetch a forecast' do + expect(WeatherForecast).not_to receive(:for) + get jobs_path + end + end + + context 'when the weather feature is off', flipper: [] do + it 'does not fetch a forecast' do + expect(WeatherForecast).not_to receive(:for) + get member_jobs_path(member) + end + + it 'does not show weather in the headers' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather')).to be_nil + end + + it 'does not read cached forecasts on an AJAX refresh' do + expect(WeatherForecast).not_to receive(:cached_for) + get member_jobs_path(member), xhr: true + end + + it 'does not read cached forecasts when adding a job' do + expect(WeatherForecast).not_to receive(:cached_for) + post jobs_path, params: { job: { name: 'Water the garden' } }, xhr: true + end + + it 'does not read cached forecasts when completing a job' do + job = create(:job, owner: member) + expect(WeatherForecast).not_to receive(:cached_for) + patch job_path(job), params: { job: { finished: true } }, xhr: true + end + + context 'when enabled for this member only' do + before { Flipper.enable_actor(:planting_weather, member) } + + it 'shows the forecast for the granted member' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather')).to be_present + end + + it 'keeps the forecast when refreshing their jobs' do + get member_jobs_path(member), xhr: true + expect(response.parsed_body.at_css('.notepad-weather')).to be_present + end + end + + context 'when enabled for another member only' do + before { Flipper.enable_actor(:planting_weather, create(:member)) } + + it 'does not show weather to an ungranted member' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather')).to be_nil + end + end + end + + context 'without a saved location' do + before { allow(WeatherForecast).to receive(:for).and_return(nil) } + + it 'keeps the full-width notepad' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.col-12 > .notepad')).to be_present + end + end + + context 'when the forecast is unavailable' do + let(:days) { [] } + + it 'still renders the jobs' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad')).to be_present + end + + it 'leaves the headers uncluttered' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather')).to be_nil + end + end + + context 'with fog but no extreme weather' do + let(:days) do + [{ date: Date.current, temp_min_c: 13.5, temp_max_c: 24.9, rainfall_mm: 0, weather_code: 45 }] + end + + it 'leaves out the condition label' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather-condition')).to be_nil + end + + it 'keeps the temperature and rainfall figures' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-group-today .notepad-weather-rain')).to be_present + end + + it 'does not include a caution' do + get member_jobs_path(member) + expect(response.parsed_body.at_css('.notepad-weather-caution')).to be_nil + end + end +end diff --git a/spec/services/jobs_notepad_spec.rb b/spec/services/jobs_notepad_spec.rb index 73a58c5887..68a0d38dea 100644 --- a/spec/services/jobs_notepad_spec.rb +++ b/spec/services/jobs_notepad_spec.rb @@ -25,6 +25,22 @@ def names expect(names).not_to include('Someone else\'s') end + context 'with a legacy domesticated animal link' do + before do + # The old type is intentionally not allowed on newly created jobs. + elsewhere.update_columns(jobbable_type: 'DomesticatedAnimal', jobbable_id: in_berries.id) # rubocop:disable Rails/SkipsModelValidations + end + + it 'keeps the job in the notepad' do + expect(names).to include('Sharpen the secateurs') + end + + it 'treats the legacy link as missing rather than loading an unrelated job' do + job = notepad.groups.flat_map(&:jobs).find { |entry| entry.id == elsewhere.id } + expect(job.jobbable).to be_nil + end + end + context 'with a garden' do let(:garden) { berries } diff --git a/spec/services/open_meteo_forecast_client_spec.rb b/spec/services/open_meteo_forecast_client_spec.rb new file mode 100644 index 0000000000..92f21b32b0 --- /dev/null +++ b/spec/services/open_meteo_forecast_client_spec.rb @@ -0,0 +1,91 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe OpenMeteoForecastClient do + subject(:days) { client.daily(latitude: 51.5, longitude: 0.0) } + + let(:client) { described_class.new(connection:) } + let(:stubs) { Faraday::Adapter::Test::Stubs.new } + let(:connection) { Faraday.new(url: 'https://api.test') { |f| f.adapter :test, stubs } } + let(:params) { {} } + let(:body) do + { daily: { time: %w(2026-12-03 2026-12-04), temperature_2m_min: [-1, nil], temperature_2m_max: [8, 9], + rain_sum: [12.5, nil], weather_code: [95, 3], wind_gusts_10m_max: [60, 15], snowfall_sum: [0, 0] } } + end + + around { |example| VCR.turned_off(&example) } + + before do + stubs.get('/v1/forecast') do |env| + params.merge!(env.params) + [200, {}, body.to_json] + end + end + + it 'requests enough days to cover next weekend in the location’s timezone' do + days + expect(params.slice('forecast_days', 'timezone')).to eq('forecast_days' => '14', 'timezone' => 'auto') + end + + it 'requests metric units explicitly' do + days + expect(params.slice('temperature_unit', 'wind_speed_unit', 'precipitation_unit')) + .to eq('temperature_unit' => 'celsius', 'wind_speed_unit' => 'kmh', 'precipitation_unit' => 'mm') + end + + it 'maps the forecast by the provider’s local dates' do + expect(days.first).to eq(date: Date.new(2026, 12, 3), temp_min_c: -1, temp_max_c: 8, rainfall_mm: 12.5, + weather_code: 95, wind_gust_kmh: 60, snowfall_cm: 0) + end + + it 'preserves missing measurements rather than making them zero' do + expect(days.last[:rainfall_mm]).to be_nil + end + + context 'with a malformed response' do + let(:body) { { daily: { time: ['not-a-date'] } } } + + it 'raises a forecast error' do + expect { days }.to raise_error(described_class::Error) + end + end + + context 'without daily data' do + let(:body) { { error: true } } + + it 'raises a forecast error' do + expect { days }.to raise_error(described_class::Error) + end + end + + context 'with an invalid measurement array' do + let(:body) { { daily: { time: ['2026-12-03'], rain_sum: 12 } } } + + it 'raises a forecast error' do + expect { days }.to raise_error(described_class::Error) + end + end + + context 'when the API fails' do + before do + stubs.clear + stubs.get('/v1/forecast') { [429, {}, '{}'] } + end + + it 'raises a forecast error' do + expect { days }.to raise_error(described_class::Error, /429/) + end + end + + context 'when the request times out' do + before do + stubs.clear + stubs.get('/v1/forecast') { raise Faraday::TimeoutError } + end + + it 'raises a forecast error' do + expect { days }.to raise_error(described_class::Error) + end + end +end diff --git a/spec/support/weather_forecast.rb b/spec/support/weather_forecast.rb new file mode 100644 index 0000000000..78a740d403 --- /dev/null +++ b/spec/support/weather_forecast.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# Never call the live forecast API from a page spec. Client specs pass an +# explicit Faraday test connection; model specs inject their own client. +RSpec.configure do |config| + config.before do + allow(OpenMeteoForecastClient).to receive(:new).and_call_original + allow(OpenMeteoForecastClient).to receive(:new).with(no_args) + .and_return(instance_double(OpenMeteoForecastClient, daily: [])) + end +end