m1m02530125 commited on
Commit
ef2d721
·
1 Parent(s): fb35f3c

シフト表に日ごとの天気・気温を表示

Browse files

店舗の緯度・経度(store_lat/store_lon)が設定されている場合、Open-Meteoから
取得した気象情報をシフト表の日付ヘッダーにアイコンと最高/最低気温で表示する。
DBへの読み書きは行わず(weather_cacheのハング再発防止のため)、
30分キャッシュ(cache.memoize)でAPI呼び出し頻度を抑える。
緯度経度の設定変更時はキャッシュを破棄して即時反映する。

optimizer/forecast.py CHANGED
@@ -33,6 +33,49 @@ _OPEN_METEO_ARCHIVE = "https://archive-api.open-meteo.com/v1/archive"
33
  _OPEN_METEO_FORECAST = "https://api.open-meteo.com/v1/forecast"
34
  _DAILY_FIELDS = "temperature_2m_max,temperature_2m_min,precipitation_sum,weathercode"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  METHOD_LABELS = {
37
  "ml": "機械学習モデル",
38
  "weekday": "同じ曜日区分の実績平均",
@@ -162,6 +205,24 @@ def _get_weather_map(dates: list[date], lat: float | None, lon: float | None) ->
162
  return fetched
163
 
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  def _weather_means(history: list[dict], weather_map: dict[str, dict]) -> dict[str, float]:
166
  """欠損気象データの補完用に、学習データ期間の平均値を計算する"""
167
  defaults = {"temp_max": 20.0, "temp_min": 10.0, "precipitation": 0.0, "weather_code": 0.0}
 
33
  _OPEN_METEO_FORECAST = "https://api.open-meteo.com/v1/forecast"
34
  _DAILY_FIELDS = "temperature_2m_max,temperature_2m_min,precipitation_sum,weathercode"
35
 
36
+ # Open-Meteo の天気コード(WMO Weather interpretation codes)→ (Bootstrap Icon, 日本語ラベル)
37
+ WEATHER_CODE_MAP = {
38
+ 0: ("bi-sun", "快晴"),
39
+ 1: ("bi-brightness-high", "晴れ"),
40
+ 2: ("bi-cloud-sun", "晴れ時々曇り"),
41
+ 3: ("bi-clouds", "曇り"),
42
+ 45: ("bi-cloud-fog2", "霧"),
43
+ 48: ("bi-cloud-fog2", "霧(霜)"),
44
+ 51: ("bi-cloud-drizzle", "小雨"),
45
+ 53: ("bi-cloud-drizzle", "霧雨"),
46
+ 55: ("bi-cloud-drizzle-fill", "強い霧雨"),
47
+ 56: ("bi-cloud-sleet", "着氷性の霧雨"),
48
+ 57: ("bi-cloud-sleet-fill", "強い着氷性の霧雨"),
49
+ 61: ("bi-cloud-rain", "小雨"),
50
+ 63: ("bi-cloud-rain", "雨"),
51
+ 65: ("bi-cloud-rain-heavy", "大雨"),
52
+ 66: ("bi-cloud-sleet", "着氷性の雨"),
53
+ 67: ("bi-cloud-sleet-fill", "強い着氷性の雨"),
54
+ 71: ("bi-cloud-snow", "小雪"),
55
+ 73: ("bi-cloud-snow", "雪"),
56
+ 75: ("bi-cloud-snow-fill", "大雪"),
57
+ 77: ("bi-cloud-snow", "霧雪"),
58
+ 80: ("bi-cloud-rain", "にわか雨"),
59
+ 81: ("bi-cloud-rain-heavy", "強いにわか雨"),
60
+ 82: ("bi-cloud-rain-heavy-fill", "激しいにわか雨"),
61
+ 85: ("bi-cloud-snow", "にわか雪"),
62
+ 86: ("bi-cloud-snow-fill", "強いにわか雪"),
63
+ 95: ("bi-cloud-lightning", "雷雨"),
64
+ 96: ("bi-cloud-lightning-rain", "雷雨(ひょう)"),
65
+ 99: ("bi-cloud-lightning-rain-fill", "雷雨(激しいひょう)"),
66
+ }
67
+ _UNKNOWN_WEATHER = ("bi-question-circle", "不明")
68
+
69
+
70
+ def weather_icon_label(code) -> tuple[str, str]:
71
+ """WMO天気コードから (Bootstrap Iconクラス, 日本語ラベル) を返す(不明な場合はクエスチョンアイコン)"""
72
+ if code is None:
73
+ return _UNKNOWN_WEATHER
74
+ try:
75
+ return WEATHER_CODE_MAP.get(int(code), _UNKNOWN_WEATHER)
76
+ except (TypeError, ValueError):
77
+ return _UNKNOWN_WEATHER
78
+
79
  METHOD_LABELS = {
80
  "ml": "機械学習モデル",
81
  "weekday": "同じ曜日区分の実績平均",
 
205
  return fetched
206
 
207
 
208
+ @cache.memoize(timeout=1800)
209
+ def get_weather_map_cached(date_strs: tuple[str, ...]) -> dict[str, dict]:
210
+ """シフト表画面用の気象情報を {date_str: {"temp_max","temp_min","precipitation","weather_code"}} で返す(30分キャッシュ)
211
+
212
+ 店舗の緯度・経度(store_lat/store_lon)が未設定の場合は{}を返す。
213
+ """
214
+ lat_s = repo.get_app_setting("store_lat", "")
215
+ lon_s = repo.get_app_setting("store_lon", "")
216
+ try:
217
+ lat = float(lat_s) if lat_s else None
218
+ lon = float(lon_s) if lon_s else None
219
+ except ValueError:
220
+ lat, lon = None, None
221
+
222
+ dates = [date.fromisoformat(ds) for ds in date_strs]
223
+ return _get_weather_map(dates, lat, lon)
224
+
225
+
226
  def _weather_means(history: list[dict], weather_map: dict[str, dict]) -> dict[str, float]:
227
  """欠損気象データの補完用に、学習データ期間の平均値を計算する"""
228
  defaults = {"temp_max": 20.0, "temp_min": 10.0, "precipitation": 0.0, "weather_code": 0.0}
routes/schedule.py CHANGED
@@ -4,6 +4,7 @@ from db import repositories as repo
4
  from models.schedule import ShiftAssignment
5
  from utils.constants import TimeSlot, Position
6
 
 
7
  from utils.holidays import holiday_set
8
  from utils.reservation import tiered_extra
9
 
@@ -232,6 +233,9 @@ def index(period_id):
232
 
233
  holidays = holiday_set(dates)
234
 
 
 
 
235
  # 社員デフォルト勤務時間(ポジション別・設定画面で変更可能)
236
  def _ft_time(pos_key, slot_key):
237
  s = repo.get_app_setting(f"ft_{pos_key}_{slot_key}_start",
@@ -270,6 +274,8 @@ def index(period_id):
270
  today=today,
271
  ft_times=ft_times,
272
  holidays=holidays,
 
 
273
  TimeSlot=TimeSlot,
274
  Position=Position,
275
  )
 
4
  from models.schedule import ShiftAssignment
5
  from utils.constants import TimeSlot, Position
6
 
7
+ from optimizer import forecast
8
  from utils.holidays import holiday_set
9
  from utils.reservation import tiered_extra
10
 
 
233
 
234
  holidays = holiday_set(dates)
235
 
236
+ # シフト表ヘッダーに表示する気象情報(店舗の緯度経度が未設定なら空)
237
+ weather_map = forecast.get_weather_map_cached(tuple(d.isoformat() for d in dates))
238
+
239
  # 社員デフォルト勤務時間(ポジション別・設定画面で変更可能)
240
  def _ft_time(pos_key, slot_key):
241
  s = repo.get_app_setting(f"ft_{pos_key}_{slot_key}_start",
 
274
  today=today,
275
  ft_times=ft_times,
276
  holidays=holidays,
277
+ weather_map=weather_map,
278
+ weather_icon_label=forecast.weather_icon_label,
279
  TimeSlot=TimeSlot,
280
  Position=Position,
281
  )
routes/settings_routes.py CHANGED
@@ -1,7 +1,9 @@
1
  import io, json
2
  from datetime import datetime
3
  from flask import Blueprint, render_template, request, redirect, url_for, flash, send_file, jsonify
 
4
  from db import repositories as repo
 
5
  from utils.constants import TimeSlot, Position
6
 
7
  bp = Blueprint("settings", __name__, url_prefix="/settings")
@@ -57,6 +59,10 @@ def save():
57
  new_settings["customer_forecast_enabled"] = "1" if request.form.get("customer_forecast_enabled") else "0"
58
  repo.save_all_app_settings(new_settings)
59
 
 
 
 
 
60
  band_constraints = repo.get_breakfast_band_constraints()
61
  new_band = {}
62
  for (band, pos) in band_constraints:
 
1
  import io, json
2
  from datetime import datetime
3
  from flask import Blueprint, render_template, request, redirect, url_for, flash, send_file, jsonify
4
+ from cache import cache
5
  from db import repositories as repo
6
+ from optimizer import forecast
7
  from utils.constants import TimeSlot, Position
8
 
9
  bp = Blueprint("settings", __name__, url_prefix="/settings")
 
59
  new_settings["customer_forecast_enabled"] = "1" if request.form.get("customer_forecast_enabled") else "0"
60
  repo.save_all_app_settings(new_settings)
61
 
62
+ # 緯度・経度を変更したら気象キャッシュ・客数予測キャッシュを破棄して即時反映する
63
+ cache.delete_memoized(forecast.get_weather_map_cached)
64
+ cache.delete_memoized(forecast.predict_customer_counts_cached)
65
+
66
  band_constraints = repo.get_breakfast_band_constraints()
67
  new_band = {}
68
  for (band, pos) in band_constraints:
templates/schedule/index.html CHANGED
@@ -360,10 +360,19 @@
360
  {% set hdr_cls = 'short-staff' if (st_b.get('short_staff') or st_d.get('short_staff')) else 'short-leader' if (st_b.get('short_leader') or st_d.get('short_leader')) else '' %}
361
  {% set is_today = ds_h == today %}
362
  {% set day_cls = 'sun' if (dow == 6 or is_holiday) else 'sat' if dow == 5 else '' %}
 
363
  <th class="text-center {{ day_cls }} {{ hdr_cls }} {{ 'today-col' if is_today else '' }}"
364
  style="cursor:pointer" onclick="openTimeline('{{ ds_h }}')">
365
  {{ '★ ' if is_today else '' }}{{ d.strftime('%m/%d') }}<br>
366
  <small>{{ ['月','火','水','木','金','土','日'][dow] }}{{ '(祝)' if is_holiday else '' }}</small>
 
 
 
 
 
 
 
 
367
  <div class="d-flex gap-1 justify-content-center flex-wrap mt-1">
368
  {% set badge_b = 'count-short' if st_b.short_staff else 'count-leader' if st_b.short_leader else 'count-ok' %}
369
  <span class="count-badge {{ badge_b }}" title="朝食">
 
360
  {% set hdr_cls = 'short-staff' if (st_b.get('short_staff') or st_d.get('short_staff')) else 'short-leader' if (st_b.get('short_leader') or st_d.get('short_leader')) else '' %}
361
  {% set is_today = ds_h == today %}
362
  {% set day_cls = 'sun' if (dow == 6 or is_holiday) else 'sat' if dow == 5 else '' %}
363
+ {% set w = weather_map.get(ds_h) %}
364
  <th class="text-center {{ day_cls }} {{ hdr_cls }} {{ 'today-col' if is_today else '' }}"
365
  style="cursor:pointer" onclick="openTimeline('{{ ds_h }}')">
366
  {{ '★ ' if is_today else '' }}{{ d.strftime('%m/%d') }}<br>
367
  <small>{{ ['月','火','水','木','金','土','日'][dow] }}{{ '(祝)' if is_holiday else '' }}</small>
368
+ {% if w %}
369
+ {% set wicon, wlabel = weather_icon_label(w.weather_code) %}
370
+ <div class="small" title="{{ wlabel }}">
371
+ <i class="bi {{ wicon }}"></i>
372
+ {% if w.temp_max is not none %}<span class="text-danger">{{ w.temp_max | round | int }}°</span>{% endif %}
373
+ {% if w.temp_min is not none %}/<span class="text-primary">{{ w.temp_min | round | int }}°</span>{% endif %}
374
+ </div>
375
+ {% endif %}
376
  <div class="d-flex gap-1 justify-content-center flex-wrap mt-1">
377
  {% set badge_b = 'count-short' if st_b.short_staff else 'count-leader' if st_b.short_leader else 'count-ok' %}
378
  <span class="count-badge {{ badge_b }}" title="朝食">