m1m02530125 commited on
Commit
fb34fd1
·
1 Parent(s): d16dc06

客数予測(β)機能を追加

Browse files

- DBに customer_count_history(運用開始前の過去客数)・weather_cache(気象データキャッシュ)テーブルと、
reservation_counts.is_special_day(特殊日フラグ)を追加
- optimizer/forecast.py: 過去実績・曜日/祝日区分・特殊日・気象データ(Open-Meteo)から
RandomForestRegressorで朝食/ディナー客数を予測(データ不足時は曜日区分別の加重平均にフォールバック)
- 客数管理ページ: 予測値の表示、未入力日への一括反映ボタン、特殊日チェックボックスを追加
- 過去客数データ入力ページ(/customers/history)を新設。月単位入力+Excelからの貼り付けに対応
- ダッシュボードに今後7日間の客数予測サマリーカードを追加
- 設定画面に「ベータ機能」カード(客数予測の有効化トグル・店舗の緯度経度)を追加
- アプリ設定キャッシュの delete_memoized が引数違いで無効化漏れする不具合を修正

db/database.py CHANGED
@@ -262,6 +262,18 @@ _CREATE_TABLES = [
262
  note TEXT NOT NULL DEFAULT '',
263
  UNIQUE(period_id, employee_id, date)
264
  )""",
 
 
 
 
 
 
 
 
 
 
 
 
265
  ]
266
 
267
  _MIGRATIONS = [
@@ -289,6 +301,7 @@ _MIGRATIONS = [
289
  ("employees", "hall_skill_dinner", "TEXT NOT NULL DEFAULT 'beginner'"),
290
  ("employees", "kitchen_skill_breakfast", "TEXT NOT NULL DEFAULT 'beginner'"),
291
  ("employees", "kitchen_skill_dinner", "TEXT NOT NULL DEFAULT 'beginner'"),
 
292
  ]
293
 
294
  _INDEXES = [
 
262
  note TEXT NOT NULL DEFAULT '',
263
  UNIQUE(period_id, employee_id, date)
264
  )""",
265
+ """CREATE TABLE IF NOT EXISTS customer_count_history (
266
+ date TEXT PRIMARY KEY,
267
+ breakfast INTEGER NOT NULL DEFAULT 0,
268
+ dinner INTEGER NOT NULL DEFAULT 0
269
+ )""",
270
+ """CREATE TABLE IF NOT EXISTS weather_cache (
271
+ date TEXT PRIMARY KEY,
272
+ temp_max REAL,
273
+ temp_min REAL,
274
+ precipitation REAL,
275
+ weather_code INTEGER
276
+ )""",
277
  ]
278
 
279
  _MIGRATIONS = [
 
301
  ("employees", "hall_skill_dinner", "TEXT NOT NULL DEFAULT 'beginner'"),
302
  ("employees", "kitchen_skill_breakfast", "TEXT NOT NULL DEFAULT 'beginner'"),
303
  ("employees", "kitchen_skill_dinner", "TEXT NOT NULL DEFAULT 'beginner'"),
304
+ ("reservation_counts", "is_special_day", "INTEGER NOT NULL DEFAULT 0"),
305
  ]
306
 
307
  _INDEXES = [
db/repositories.py CHANGED
@@ -1,6 +1,7 @@
1
  """DB操作の集約モジュール"""
2
  from __future__ import annotations
3
  from typing import Optional
 
4
  from db.database import get_connection, Connection
5
  from models.employee import Employee, FixedPattern
6
  from models.schedule import ShiftRequest, ShiftAssignment, SchedulePeriod
@@ -514,14 +515,17 @@ def remove_assignment(period_id: int, employee_id: int, date: str, time_slot: Ti
514
  # ── 予約客数 ─────────────────────────────────────────────────────────────
515
 
516
  def get_reservation_counts(period_id: int) -> dict[str, dict[str, int]]:
517
- """期間の予約客数を {date_str: {"breakfast": int, "dinner": int}} で返す"""
518
  conn = get_connection()
519
  rows = conn.execute(
520
- "SELECT date, breakfast, dinner FROM reservation_counts WHERE period_id=? ORDER BY date",
521
  (period_id,)
522
  ).fetchall()
523
  conn.close()
524
- return {r["date"]: {"breakfast": r["breakfast"], "dinner": r["dinner"]} for r in rows}
 
 
 
525
 
526
 
527
  def get_total_customer_counts(period_ids: list[int]) -> dict[str, int]:
@@ -540,19 +544,110 @@ def get_total_customer_counts(period_ids: list[int]) -> dict[str, int]:
540
  return {"breakfast": b, "dinner": d, "total": b + d}
541
 
542
 
543
- def save_reservation_count(period_id: int, date_str: str, breakfast: int, dinner: int):
544
  """予約客数を保存"""
545
  conn = get_connection()
546
  conn.execute(
547
- """INSERT INTO reservation_counts (period_id, date, breakfast, dinner) VALUES (?,?,?,?)
548
  ON CONFLICT(period_id, date) DO UPDATE SET
549
- breakfast=excluded.breakfast, dinner=excluded.dinner""",
550
- (period_id, date_str, breakfast, dinner)
551
  )
552
  conn.commit()
553
  conn.close()
554
 
555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  # ── アプリ設定 ────────────────────────────────────────────────────────────
557
 
558
  @cache.memoize(timeout=300)
@@ -571,7 +666,7 @@ def save_app_setting(key: str, value: str):
571
  )
572
  conn.commit()
573
  conn.close()
574
- cache.delete_memoized(get_app_setting, key)
575
  cache.delete_memoized(get_all_app_settings) # get_all_app_settings も無効化
576
 
577
 
@@ -593,8 +688,7 @@ def save_all_app_settings(settings: dict[str, str]):
593
  conn.commit()
594
  conn.close()
595
  cache.delete_memoized(get_all_app_settings)
596
- for key in settings:
597
- cache.delete_memoized(get_app_setting, key)
598
 
599
 
600
  def get_breakfast_band_constraints() -> dict[tuple[str, str], dict]:
 
1
  """DB操作の集約モジュール"""
2
  from __future__ import annotations
3
  from typing import Optional
4
+ from datetime import date as _date
5
  from db.database import get_connection, Connection
6
  from models.employee import Employee, FixedPattern
7
  from models.schedule import ShiftRequest, ShiftAssignment, SchedulePeriod
 
515
  # ── 予約客数 ─────────────────────────────────────────────────────────────
516
 
517
  def get_reservation_counts(period_id: int) -> dict[str, dict[str, int]]:
518
+ """期間の予約客数を {date_str: {"breakfast": int, "dinner": int, "is_special_day": int}} で返す"""
519
  conn = get_connection()
520
  rows = conn.execute(
521
+ "SELECT date, breakfast, dinner, is_special_day FROM reservation_counts WHERE period_id=? ORDER BY date",
522
  (period_id,)
523
  ).fetchall()
524
  conn.close()
525
+ return {
526
+ r["date"]: {"breakfast": r["breakfast"], "dinner": r["dinner"], "is_special_day": r["is_special_day"]}
527
+ for r in rows
528
+ }
529
 
530
 
531
  def get_total_customer_counts(period_ids: list[int]) -> dict[str, int]:
 
544
  return {"breakfast": b, "dinner": d, "total": b + d}
545
 
546
 
547
+ def save_reservation_count(period_id: int, date_str: str, breakfast: int, dinner: int, is_special_day: int = 0):
548
  """予約客数を保存"""
549
  conn = get_connection()
550
  conn.execute(
551
+ """INSERT INTO reservation_counts (period_id, date, breakfast, dinner, is_special_day) VALUES (?,?,?,?,?)
552
  ON CONFLICT(period_id, date) DO UPDATE SET
553
+ breakfast=excluded.breakfast, dinner=excluded.dinner, is_special_day=excluded.is_special_day""",
554
+ (period_id, date_str, breakfast, dinner, is_special_day)
555
  )
556
  conn.commit()
557
  conn.close()
558
 
559
 
560
+ # ── 客数予測(β)─────────────────────────────────────────────────────────
561
+
562
+ def get_customer_count_history(year_month: str) -> dict[str, dict[str, int]]:
563
+ """指定月(YYYY-MM)の過去客数(運用開始前の手入力分)を {date_str: {"breakfast": int, "dinner": int}} で返す"""
564
+ conn = get_connection()
565
+ rows = conn.execute(
566
+ "SELECT date, breakfast, dinner FROM customer_count_history WHERE date LIKE ? ORDER BY date",
567
+ (f"{year_month}-%",)
568
+ ).fetchall()
569
+ conn.close()
570
+ return {r["date"]: {"breakfast": r["breakfast"], "dinner": r["dinner"]} for r in rows}
571
+
572
+
573
+ def save_customer_count_history(entries: dict[str, dict[str, int]]):
574
+ """過去客数データ({date_str: {"breakfast": int, "dinner": int}})を一括保存"""
575
+ conn = get_connection()
576
+ for date_str, vals in entries.items():
577
+ conn.execute(
578
+ """INSERT INTO customer_count_history (date, breakfast, dinner) VALUES (?,?,?)
579
+ ON CONFLICT(date) DO UPDATE SET
580
+ breakfast=excluded.breakfast, dinner=excluded.dinner""",
581
+ (date_str, vals.get("breakfast", 0), vals.get("dinner", 0))
582
+ )
583
+ conn.commit()
584
+ conn.close()
585
+
586
+
587
+ def get_forecast_training_data() -> list[dict]:
588
+ """
589
+ 客数予測モデルの学習データを返す。
590
+ customer_count_history(運用開始前の手入力分)と reservation_counts(運用後・本日より前の実績)を
591
+ 日付で統合し、日付昇順のリストで返す。各要素:
592
+ {"date": str, "breakfast": int, "dinner": int, "is_special_day": int}
593
+ """
594
+ today_str = _date.today().isoformat()
595
+ conn = get_connection()
596
+ hist_rows = conn.execute(
597
+ "SELECT date, breakfast, dinner FROM customer_count_history"
598
+ ).fetchall()
599
+ actual_rows = conn.execute(
600
+ "SELECT date, breakfast, dinner, is_special_day FROM reservation_counts WHERE date < ?",
601
+ (today_str,)
602
+ ).fetchall()
603
+ conn.close()
604
+
605
+ merged: dict[str, dict] = {}
606
+ for r in hist_rows:
607
+ merged[r["date"]] = {"date": r["date"], "breakfast": r["breakfast"], "dinner": r["dinner"], "is_special_day": 0}
608
+ for r in actual_rows:
609
+ # 実績データを優先(重複日があれば上書き)
610
+ merged[r["date"]] = {
611
+ "date": r["date"], "breakfast": r["breakfast"], "dinner": r["dinner"],
612
+ "is_special_day": r["is_special_day"],
613
+ }
614
+ return sorted(merged.values(), key=lambda x: x["date"])
615
+
616
+
617
+ def get_weather_cache(dates: list[str]) -> dict[str, dict]:
618
+ """指定日付群の気象キャッシュを {date_str: {"temp_max", "temp_min", "precipitation", "weather_code"}} で返す"""
619
+ if not dates:
620
+ return {}
621
+ conn = get_connection()
622
+ ph = ",".join(["?"] * len(dates))
623
+ rows = conn.execute(
624
+ f"SELECT * FROM weather_cache WHERE date IN ({ph})", dates
625
+ ).fetchall()
626
+ conn.close()
627
+ return {
628
+ r["date"]: {
629
+ "temp_max": r["temp_max"], "temp_min": r["temp_min"],
630
+ "precipitation": r["precipitation"], "weather_code": r["weather_code"],
631
+ }
632
+ for r in rows
633
+ }
634
+
635
+
636
+ def save_weather_cache(entries: dict[str, dict]):
637
+ """気象データ({date_str: {"temp_max","temp_min","precipitation","weather_code"}})を一括キャッシュ保存"""
638
+ conn = get_connection()
639
+ for date_str, vals in entries.items():
640
+ conn.execute(
641
+ """INSERT INTO weather_cache (date, temp_max, temp_min, precipitation, weather_code) VALUES (?,?,?,?,?)
642
+ ON CONFLICT(date) DO UPDATE SET
643
+ temp_max=excluded.temp_max, temp_min=excluded.temp_min,
644
+ precipitation=excluded.precipitation, weather_code=excluded.weather_code""",
645
+ (date_str, vals.get("temp_max"), vals.get("temp_min"), vals.get("precipitation"), vals.get("weather_code"))
646
+ )
647
+ conn.commit()
648
+ conn.close()
649
+
650
+
651
  # ── アプリ設定 ────────────────────────────────────────────────────────────
652
 
653
  @cache.memoize(timeout=300)
 
666
  )
667
  conn.commit()
668
  conn.close()
669
+ cache.delete_memoized(get_app_setting) # 引数違いで残るキャッシュも含めて全消去
670
  cache.delete_memoized(get_all_app_settings) # get_all_app_settings も無効化
671
 
672
 
 
688
  conn.commit()
689
  conn.close()
690
  cache.delete_memoized(get_all_app_settings)
691
+ cache.delete_memoized(get_app_setting) # 引数違いで残るキャッシュも含めて全消去
 
692
 
693
 
694
  def get_breakfast_band_constraints() -> dict[tuple[str, str], dict]:
optimizer/forecast.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """客数予測(β機能)
2
+
3
+ 過去の客数実績・曜日/祝日区分・気象データから、朝食/ディナーの客数を予測する。
4
+
5
+ - 学習データが少ない間は、曜日(祝日は曜日に関わらず別区分)別の加重移動平均
6
+ (Tier1: 同じ曜日区分 → Tier2: 平日/休日(土日祝) → Tier3: 全体平均)にフォールバックする。
7
+ - 学習データが十分(既定30件以上)にある場合は scikit-learn の RandomForestRegressor で
8
+ 曜日・祝日・特殊日フラグ・月・気象(Open-Meteo)・直近の同曜日傾向を特徴量として学習する。
9
+ - 気象APIや scikit-learn が利用できない場合も例外を投げず、統計フォールバックの結果を返す。
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from datetime import date
18
+
19
+ from cache import cache
20
+ from db import repositories as repo
21
+ from utils.holidays import is_holiday
22
+
23
+ _DAY_CATS = ["月", "火", "水", "木", "金", "土", "日"]
24
+ _WEEKEND_CATS = {"土", "日", "祝日"}
25
+
26
+ _DECAY = 0.85 # 加重平均の減衰率(新しいデータほど重視)
27
+ _MIN_TIER_SAMPLES = 3 # 各階層フォールバックで使う最低サンプル数
28
+ _MIN_ML_SAMPLES = 30 # MLモデルを学習する最低データ件数
29
+ _MAX_HISTORY_DAYS = 730 # 学習に使う直近データの上限(約2年分)
30
+ _MAX_FORECAST_DAYS = 16 # Open-Meteo予報の取得可能日数
31
+
32
+ _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": "同じ曜日区分の実績平均",
39
+ "weekday_group": "平日/休日の実績平均",
40
+ "overall": "全体の実績平均",
41
+ "no_data": "データ不足",
42
+ }
43
+
44
+
45
+ def _day_category(d: date) -> str:
46
+ """日付から曜日区分を返す(祝日は曜日に関わらず"祝日"扱い)"""
47
+ if is_holiday(d):
48
+ return "祝日"
49
+ return _DAY_CATS[d.weekday()]
50
+
51
+
52
+ def _tiered_average(values: list[float], cats: list[str], target_cat: str) -> dict:
53
+ """
54
+ 曜日区分別の加重平均(Tier1〜3フォールバック)。
55
+ values, cats は同じ並び(古い→新しい順)の実績値・曜日区分のリスト。
56
+ """
57
+ is_weekend = target_cat in _WEEKEND_CATS
58
+
59
+ tier1 = [v for v, c in zip(values, cats) if c == target_cat]
60
+ tier2 = [v for v, c in zip(values, cats) if (c in _WEEKEND_CATS) == is_weekend]
61
+ tier3 = values
62
+
63
+ if len(tier1) >= _MIN_TIER_SAMPLES:
64
+ samples, method = tier1, "weekday"
65
+ elif len(tier2) >= _MIN_TIER_SAMPLES:
66
+ samples, method = tier2, "weekday_group"
67
+ elif tier3:
68
+ samples, method = tier3, "overall"
69
+ else:
70
+ return {"predicted": None, "low": None, "high": None, "n_samples": 0, "method": "no_data"}
71
+
72
+ n = len(samples)
73
+ weights = [_DECAY ** (n - 1 - i) for i in range(n)]
74
+ wsum = sum(weights)
75
+ mean = sum(w * v for w, v in zip(weights, samples)) / wsum
76
+ if n >= 2:
77
+ var = sum((v - mean) ** 2 for v in samples) / (n - 1)
78
+ sd = var ** 0.5
79
+ else:
80
+ sd = 0.0
81
+
82
+ return {
83
+ "predicted": max(0, round(mean)),
84
+ "low": max(0, round(mean - sd)),
85
+ "high": max(0, round(mean + sd)),
86
+ "n_samples": n,
87
+ "method": method,
88
+ }
89
+
90
+
91
+ # ── 気象データ(Open-Meteo) ─────────────────────────────────────────────
92
+
93
+ def _http_get_json(url: str, timeout: int = 8) -> dict | None:
94
+ try:
95
+ req = urllib.request.Request(url, headers={"User-Agent": "SDU-Shift-Forecast"})
96
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
97
+ return json.loads(resp.read().decode())
98
+ except (urllib.error.URLError, TimeoutError, ValueError, OSError):
99
+ return None
100
+
101
+
102
+ def _safe_get(lst, i):
103
+ if not lst or i >= len(lst):
104
+ return None
105
+ return lst[i]
106
+
107
+
108
+ def _fetch_weather_range(lat: float, lon: float, start: date, end: date, archive: bool) -> dict[str, dict]:
109
+ """指定期間の気象データを取得し {date_str: {...}} で返す(失敗時は{})"""
110
+ base = _OPEN_METEO_ARCHIVE if archive else _OPEN_METEO_FORECAST
111
+ params = {
112
+ "latitude": lat, "longitude": lon,
113
+ "daily": _DAILY_FIELDS,
114
+ "timezone": "Asia/Tokyo",
115
+ }
116
+ if archive:
117
+ params["start_date"] = start.isoformat()
118
+ params["end_date"] = end.isoformat()
119
+ else:
120
+ params["forecast_days"] = min(_MAX_FORECAST_DAYS, max(1, (end - date.today()).days + 1))
121
+
122
+ data = _http_get_json(f"{base}?{urllib.parse.urlencode(params)}")
123
+ if not data or "daily" not in data:
124
+ return {}
125
+
126
+ daily = data["daily"]
127
+ times = daily.get("time", [])
128
+ return {
129
+ d: {
130
+ "temp_max": _safe_get(daily.get("temperature_2m_max"), i),
131
+ "temp_min": _safe_get(daily.get("temperature_2m_min"), i),
132
+ "precipitation": _safe_get(daily.get("precipitation_sum"), i),
133
+ "weather_code": _safe_get(daily.get("weathercode"), i),
134
+ }
135
+ for i, d in enumerate(times)
136
+ }
137
+
138
+
139
+ def _get_weather_map(dates: list[date], lat: float | None, lon: float | None) -> dict[str, dict]:
140
+ """指定日付群の気象データを {date_str: {...}} で返す(DBキャッシュ+Open-Meteo)"""
141
+ if lat is None or lon is None or not dates:
142
+ return {}
143
+
144
+ date_strs = sorted({d.isoformat() for d in dates})
145
+ cached = repo.get_weather_cache(date_strs)
146
+ missing = [ds for ds in date_strs if ds not in cached]
147
+ if not missing:
148
+ return cached
149
+
150
+ today = date.today()
151
+ missing_dates = [date.fromisoformat(ds) for ds in missing]
152
+ past = [d for d in missing_dates if d < today]
153
+ future = [d for d in missing_dates if d >= today]
154
+
155
+ fetched: dict[str, dict] = {}
156
+ if past:
157
+ fetched.update(_fetch_weather_range(lat, lon, min(past), max(past), archive=True))
158
+ if future:
159
+ fetched.update(_fetch_weather_range(lat, lon, min(future), max(future), archive=False))
160
+
161
+ if fetched:
162
+ repo.save_weather_cache(fetched)
163
+ cached.update(fetched)
164
+ return cached
165
+
166
+
167
+ def _weather_means(history: list[dict], weather_map: dict[str, dict]) -> dict[str, float]:
168
+ """欠損気象データの補完用に、学習データ期間の平均値を計算する"""
169
+ defaults = {"temp_max": 20.0, "temp_min": 10.0, "precipitation": 0.0, "weather_code": 0.0}
170
+ sums: dict[str, list[float]] = {k: [] for k in defaults}
171
+ for r in history:
172
+ w = weather_map.get(r["date"])
173
+ if not w:
174
+ continue
175
+ for k in defaults:
176
+ if w.get(k) is not None:
177
+ sums[k].append(w[k])
178
+ return {k: (sum(v) / len(v) if v else defaults[k]) for k, v in sums.items()}
179
+
180
+
181
+ # ── 特徴量・MLモデル ────────────────────────────────────────────────────
182
+
183
+ def _feature_row(d: date, weather: dict | None, is_special_day: int, means: dict, lag_avg: float) -> list[float]:
184
+ weekday_onehot = [1.0 if d.weekday() == i else 0.0 for i in range(7)]
185
+ holiday_flag = 1.0 if is_holiday(d) else 0.0
186
+ w = weather or {}
187
+ temp_max = w.get("temp_max") if w.get("temp_max") is not None else means["temp_max"]
188
+ temp_min = w.get("temp_min") if w.get("temp_min") is not None else means["temp_min"]
189
+ precip = w.get("precipitation") if w.get("precipitation") is not None else means["precipitation"]
190
+ wcode = w.get("weather_code") if w.get("weather_code") is not None else means["weather_code"]
191
+ return weekday_onehot + [holiday_flag, float(is_special_day), float(d.month),
192
+ temp_max, temp_min, precip, wcode, lag_avg]
193
+
194
+
195
+ def _build_training_set(history: list[dict], cats: list[str], slot: str,
196
+ weather_map: dict[str, dict], means: dict) -> tuple[list, list]:
197
+ values = [r[slot] for r in history]
198
+ X, y = [], []
199
+ for i, r in enumerate(history):
200
+ if i == 0:
201
+ continue # 直近傾向(ラグ特徴量)の算出に過去データが1件も無い行は除外
202
+ d = date.fromisoformat(r["date"])
203
+ lag_stat = _tiered_average(values[:i], cats[:i], cats[i])
204
+ feat = _feature_row(d, weather_map.get(r["date"]), r["is_special_day"], means, lag_stat["predicted"])
205
+ X.append(feat)
206
+ y.append(r[slot])
207
+ return X, y
208
+
209
+
210
+ def predict_customer_counts(target_dates: list[date], special_days: set[str] | None = None) -> dict[str, dict]:
211
+ """
212
+ 指定した日付リストについて朝食・ディナーの客数を予測する。
213
+
214
+ 戻り値: {date_str: {"breakfast": {予測結果}, "dinner": {予測結果}}}
215
+ 予測結果: {"predicted": int|None, "low": int|None, "high": int|None,
216
+ "n_samples": int, "method": str}
217
+ method は METHOD_LABELS のキーのいずれか。
218
+ """
219
+ special_days = special_days or set()
220
+ history_all = repo.get_forecast_training_data()
221
+ history = history_all[-_MAX_HISTORY_DAYS:]
222
+
223
+ empty_slot = {"predicted": None, "low": None, "high": None, "n_samples": 0, "method": "no_data"}
224
+ if not history:
225
+ return {d.isoformat(): {"breakfast": dict(empty_slot), "dinner": dict(empty_slot)} for d in target_dates}
226
+
227
+ cats = [_day_category(date.fromisoformat(r["date"])) for r in history]
228
+
229
+ lat_s = repo.get_app_setting("store_lat", "")
230
+ lon_s = repo.get_app_setting("store_lon", "")
231
+ try:
232
+ lat = float(lat_s) if lat_s else None
233
+ lon = float(lon_s) if lon_s else None
234
+ except ValueError:
235
+ lat, lon = None, None
236
+
237
+ weather_map = _get_weather_map(
238
+ [date.fromisoformat(r["date"]) for r in history] + list(target_dates), lat, lon
239
+ )
240
+ means = _weather_means(history, weather_map)
241
+
242
+ result: dict[str, dict] = {ds: {} for ds in (d.isoformat() for d in target_dates)}
243
+
244
+ for slot in ("breakfast", "dinner"):
245
+ values = [r[slot] for r in history]
246
+
247
+ model = None
248
+ if len(history) >= _MIN_ML_SAMPLES:
249
+ X, y = _build_training_set(history, cats, slot, weather_map, means)
250
+ if len(X) >= _MIN_ML_SAMPLES:
251
+ try:
252
+ from sklearn.ensemble import RandomForestRegressor
253
+ model = RandomForestRegressor(n_estimators=200, max_depth=8, random_state=42)
254
+ model.fit(X, y)
255
+ except Exception:
256
+ model = None
257
+
258
+ for d in target_dates:
259
+ ds = d.isoformat()
260
+ target_cat = _day_category(d)
261
+ stat = _tiered_average(values, cats, target_cat)
262
+
263
+ if model is not None:
264
+ try:
265
+ is_special = 1 if ds in special_days else 0
266
+ lag_stat = _tiered_average(values, cats, target_cat)
267
+ feat = _feature_row(d, weather_map.get(ds), is_special, means, lag_stat["predicted"])
268
+ pred = float(model.predict([feat])[0])
269
+ stat = {**stat, "predicted": max(0, round(pred)), "method": "ml"}
270
+ except Exception:
271
+ pass
272
+
273
+ result[ds][slot] = stat
274
+
275
+ return result
276
+
277
+
278
+ @cache.memoize(timeout=300)
279
+ def predict_customer_counts_cached(target_date_strs: tuple[str, ...], special_days: tuple[str, ...]) -> dict:
280
+ """predict_customer_counts() のキャッシュ付きラッパー(モデル再学習のコスト軽減のため5分間キャッシュ)"""
281
+ target_dates = [date.fromisoformat(ds) for ds in target_date_strs]
282
+ return predict_customer_counts(target_dates, set(special_days))
requirements-web.txt CHANGED
@@ -8,3 +8,4 @@ ortools>=9.7.0
8
  openpyxl>=3.1.0
9
  reportlab>=4.0.0
10
  jpholiday>=0.1.0
 
 
8
  openpyxl>=3.1.0
9
  reportlab>=4.0.0
10
  jpholiday>=0.1.0
11
+ scikit-learn>=1.3.0
requirements.txt CHANGED
@@ -7,3 +7,4 @@ flask>=3.0.0
7
  gunicorn>=21.0.0
8
  jpholiday>=0.1.0
9
  psycopg2-binary>=2.9.0
 
 
7
  gunicorn>=21.0.0
8
  jpholiday>=0.1.0
9
  psycopg2-binary>=2.9.0
10
+ scikit-learn>=1.3.0
routes/customers.py CHANGED
@@ -1,5 +1,9 @@
 
 
1
  from flask import Blueprint, render_template, request, redirect, url_for, flash
 
2
  from db import repositories as repo
 
3
  from utils.holidays import holiday_set
4
 
5
  bp = Blueprint("customers", __name__, url_prefix="/customers")
@@ -27,12 +31,23 @@ def index(period_id):
27
  thresh_d = int(repo.get_app_setting("reserv_threshold_dinner", "25"))
28
  gen = repo.get_period_gen_status(period_id)
29
  needs_regen = gen.get("needs_regen", False)
 
 
 
 
 
 
 
 
30
  return render_template(
31
  "customers/index.html",
32
  period=period, periods=periods, dates=dates, counts=counts,
33
  thresh_b=thresh_b, thresh_d=thresh_d,
34
  needs_regen=needs_regen,
35
  holidays=holiday_set(dates),
 
 
 
36
  )
37
 
38
 
@@ -46,14 +61,20 @@ def save(period_id):
46
  # 変更前の値を取得して比較
47
  old_counts = repo.get_reservation_counts(period_id)
48
  changed = False
 
49
  for d in dates:
50
  ds = str(d)
51
  new_b = int(request.form.get(f"b_{ds}", 0) or 0)
52
  new_dn = int(request.form.get(f"d_{ds}", 0) or 0)
 
53
  old = old_counts.get(ds, {})
54
  if new_b != old.get("breakfast", 0) or new_dn != old.get("dinner", 0):
55
  changed = True
56
- repo.save_reservation_count(period_id, ds, new_b, new_dn)
 
 
 
 
57
  # 値が実際に変わった && 生成済みシフトがある場合のみ再生成フラグを立てる
58
  if changed:
59
  gen = repo.get_period_gen_status(period_id)
@@ -65,3 +86,64 @@ def save(period_id):
65
  else:
66
  flash("予約客数を保存しました(変更なし)", "success")
67
  return redirect(url_for("customers.index", period_id=period_id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import calendar
2
+ from datetime import date
3
  from flask import Blueprint, render_template, request, redirect, url_for, flash
4
+ from cache import cache
5
  from db import repositories as repo
6
+ from optimizer import forecast
7
  from utils.holidays import holiday_set
8
 
9
  bp = Blueprint("customers", __name__, url_prefix="/customers")
 
31
  thresh_d = int(repo.get_app_setting("reserv_threshold_dinner", "25"))
32
  gen = repo.get_period_gen_status(period_id)
33
  needs_regen = gen.get("needs_regen", False)
34
+
35
+ forecast_enabled = repo.get_app_setting("customer_forecast_enabled", "0") == "1"
36
+ forecast_data = {}
37
+ if forecast_enabled:
38
+ special_days = tuple(sorted(ds for ds, c in counts.items() if c.get("is_special_day")))
39
+ date_strs = tuple(d.isoformat() for d in dates)
40
+ forecast_data = forecast.predict_customer_counts_cached(date_strs, special_days)
41
+
42
  return render_template(
43
  "customers/index.html",
44
  period=period, periods=periods, dates=dates, counts=counts,
45
  thresh_b=thresh_b, thresh_d=thresh_d,
46
  needs_regen=needs_regen,
47
  holidays=holiday_set(dates),
48
+ forecast_enabled=forecast_enabled,
49
+ forecast=forecast_data,
50
+ method_labels=forecast.METHOD_LABELS,
51
  )
52
 
53
 
 
61
  # 変更前の値を取得して比較
62
  old_counts = repo.get_reservation_counts(period_id)
63
  changed = False
64
+ forecast_changed = False
65
  for d in dates:
66
  ds = str(d)
67
  new_b = int(request.form.get(f"b_{ds}", 0) or 0)
68
  new_dn = int(request.form.get(f"d_{ds}", 0) or 0)
69
+ new_special = 1 if request.form.get(f"special_{ds}") else 0
70
  old = old_counts.get(ds, {})
71
  if new_b != old.get("breakfast", 0) or new_dn != old.get("dinner", 0):
72
  changed = True
73
+ if new_special != old.get("is_special_day", 0):
74
+ forecast_changed = True
75
+ repo.save_reservation_count(period_id, ds, new_b, new_dn, new_special)
76
+ if changed or forecast_changed:
77
+ cache.delete_memoized(forecast.predict_customer_counts_cached)
78
  # 値が実際に変わった && 生成済みシフトがある場合のみ再生成フラグを立てる
79
  if changed:
80
  gen = repo.get_period_gen_status(period_id)
 
86
  else:
87
  flash("予約客数を保存しました(変更なし)", "success")
88
  return redirect(url_for("customers.index", period_id=period_id))
89
+
90
+
91
+ # ── 過去客数データ入力(β)────────────────────────────────────────────
92
+
93
+ @bp.get("/history")
94
+ def history():
95
+ """運用開始前の過去客数(紙の集計表など)を月単位で入力する画面"""
96
+ today = date.today()
97
+ ym = request.args.get("ym", "")
98
+ try:
99
+ year, month = (int(p) for p in ym.split("-"))
100
+ if month < 1 or month > 12:
101
+ raise ValueError
102
+ except ValueError:
103
+ year, month = today.year, today.month
104
+
105
+ last_day = calendar.monthrange(year, month)[1]
106
+ dates = [date(year, month, d) for d in range(1, last_day + 1)]
107
+ ym = f"{year:04d}-{month:02d}"
108
+ data = repo.get_customer_count_history(ym)
109
+
110
+ if month == 1:
111
+ prev_ym = f"{year - 1:04d}-12"
112
+ else:
113
+ prev_ym = f"{year:04d}-{month - 1:02d}"
114
+ if month == 12:
115
+ next_ym = f"{year + 1:04d}-01"
116
+ else:
117
+ next_ym = f"{year:04d}-{month + 1:02d}"
118
+
119
+ return render_template(
120
+ "customers/history.html",
121
+ dates=dates, data=data, ym=ym,
122
+ prev_ym=prev_ym, next_ym=next_ym,
123
+ holidays=holiday_set(dates),
124
+ )
125
+
126
+
127
+ @bp.post("/history/save")
128
+ def save_history():
129
+ ym = request.form.get("ym", "")
130
+ try:
131
+ year, month = (int(p) for p in ym.split("-"))
132
+ last_day = calendar.monthrange(year, month)[1]
133
+ except ValueError:
134
+ flash("年月が不正です", "error")
135
+ return redirect(url_for("customers.history"))
136
+
137
+ entries = {}
138
+ for d in range(1, last_day + 1):
139
+ ds = f"{year:04d}-{month:02d}-{d:02d}"
140
+ b = request.form.get(f"b_{ds}", "")
141
+ dn = request.form.get(f"d_{ds}", "")
142
+ entries[ds] = {
143
+ "breakfast": int(b) if b else 0,
144
+ "dinner": int(dn) if dn else 0,
145
+ }
146
+ repo.save_customer_count_history(entries)
147
+ cache.delete_memoized(forecast.predict_customer_counts_cached)
148
+ flash("過去客数データを保存しました", "success")
149
+ return redirect(url_for("customers.history", ym=ym))
routes/dashboard.py CHANGED
@@ -1,9 +1,12 @@
1
- from datetime import date as _date
2
  from collections import defaultdict
3
  from flask import Blueprint, render_template, url_for
4
  from db import repositories as repo
 
5
  from utils.constants import TimeSlot, Position
6
 
 
 
7
  bp = Blueprint("dashboard", __name__)
8
 
9
  _DAY_JP = ['月', '火', '水', '木', '金', '土', '日']
@@ -29,6 +32,7 @@ def index():
29
  upcoming_short_days = [] # 直近7日の不足日ラベル
30
  unsubmitted = [] # 希望未提出スタッフ
31
  todos = [] # TODOアイテム
 
32
 
33
  if not latest:
34
  todos.append({
@@ -164,6 +168,26 @@ def index():
164
  'url': url_for('customers.list_periods'),
165
  })
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  return render_template(
168
  'dashboard/index.html',
169
  today=today,
@@ -177,4 +201,8 @@ def index():
177
  upcoming_short_days=upcoming_short_days,
178
  todos=todos,
179
  DAY_JP=_DAY_JP,
 
 
 
 
180
  )
 
1
+ from datetime import date as _date, timedelta
2
  from collections import defaultdict
3
  from flask import Blueprint, render_template, url_for
4
  from db import repositories as repo
5
+ from optimizer import forecast as forecast_mod
6
  from utils.constants import TimeSlot, Position
7
 
8
+ _FORECAST_DAYS = 7
9
+
10
  bp = Blueprint("dashboard", __name__)
11
 
12
  _DAY_JP = ['月', '火', '水', '木', '金', '土', '日']
 
32
  upcoming_short_days = [] # 直近7日の不足日ラベル
33
  unsubmitted = [] # 希望未提出スタッフ
34
  todos = [] # TODOアイテム
35
+ res_counts = {} # 予約客数(特殊日フラグ参照用)
36
 
37
  if not latest:
38
  todos.append({
 
168
  'url': url_for('customers.list_periods'),
169
  })
170
 
171
+ # ── 客数予測(β):今後N日分のサマリー ──
172
+ forecast_enabled = repo.get_app_setting("customer_forecast_enabled", "0") == "1"
173
+ forecast_rows = []
174
+ if forecast_enabled:
175
+ fc_dates = [today + timedelta(days=i) for i in range(_FORECAST_DAYS)]
176
+ fc_strs = tuple(d.isoformat() for d in fc_dates)
177
+ special_days = tuple(sorted(
178
+ ds for ds, c in res_counts.items() if c.get("is_special_day") and ds in fc_strs
179
+ ))
180
+ fc_data = forecast_mod.predict_customer_counts_cached(fc_strs, special_days)
181
+ thresh_b = int(repo.get_app_setting("reserv_threshold_breakfast", "100"))
182
+ thresh_d = int(repo.get_app_setting("reserv_threshold_dinner", "25"))
183
+ for d in fc_dates:
184
+ fc = fc_data.get(d.isoformat(), {})
185
+ forecast_rows.append({
186
+ 'date': d,
187
+ 'breakfast': fc.get('breakfast', {}),
188
+ 'dinner': fc.get('dinner', {}),
189
+ })
190
+
191
  return render_template(
192
  'dashboard/index.html',
193
  today=today,
 
201
  upcoming_short_days=upcoming_short_days,
202
  todos=todos,
203
  DAY_JP=_DAY_JP,
204
+ forecast_enabled=forecast_enabled,
205
+ forecast_rows=forecast_rows,
206
+ thresh_b=thresh_b if forecast_enabled else 0,
207
+ thresh_d=thresh_d if forecast_enabled else 0,
208
  )
routes/settings_routes.py CHANGED
@@ -51,8 +51,10 @@ def save():
51
  "base_hourly_wage", "early_morning_allowance",
52
  "early_allowance_start", "early_allowance_end",
53
  "max_consecutive_days", "min_days_off",
 
54
  ]
55
  new_settings = {k: request.form.get(k, "") for k in settings_keys}
 
56
  repo.save_all_app_settings(new_settings)
57
 
58
  band_constraints = repo.get_breakfast_band_constraints()
 
51
  "base_hourly_wage", "early_morning_allowance",
52
  "early_allowance_start", "early_allowance_end",
53
  "max_consecutive_days", "min_days_off",
54
+ "store_lat", "store_lon",
55
  ]
56
  new_settings = {k: request.form.get(k, "") for k in settings_keys}
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()
templates/customers/history.html ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}過去客数データ入力 - SDU-Shift{% endblock %}
3
+ {% block content %}
4
+ <div class="page-header">
5
+ <div>
6
+ <div class="fw-semibold"><i class="bi bi-clock-history me-2"></i>過去客数データ入力(β)</div>
7
+ <div style="font-size:.72rem;color:#94a3b8;line-height:1.2">
8
+ {{ ym }} の客数実績
9
+ </div>
10
+ </div>
11
+ <button form="history-form" type="submit" class="btn btn-primary btn-sm ms-auto"
12
+ data-loading="保存中…">
13
+ <i class="bi bi-floppy-fill"></i> 保存
14
+ </button>
15
+ </div>
16
+ <div class="content">
17
+
18
+ <div class="d-flex align-items-start gap-2 mb-3 p-3 rounded-3"
19
+ style="background:#1e293b;border-left:4px solid #38bdf8">
20
+ <i class="bi bi-info-circle text-info mt-1" style="flex-shrink:0"></i>
21
+ <div style="font-size:.85rem;color:#e2e8f0;line-height:1.6">
22
+ 運用開始前の紙の集計表などにある客数実績を入力すると、客数予測(β)の精度向上に利用されます。<br>
23
+ Excelなどで「朝食・ディナー」の2列を選択してコピーし、入力したい開始日の朝食欄をクリックして貼り付けると、複数日分をまとめて入力できます。
24
+ </div>
25
+ </div>
26
+
27
+ <!-- 月セレクター -->
28
+ <div class="d-flex align-items-center justify-content-between mb-3">
29
+ <a href="{{ url_for('customers.history', ym=prev_ym) }}" class="btn btn-outline-secondary btn-sm">
30
+ <i class="bi bi-chevron-left"></i> 前月
31
+ </a>
32
+ <div class="fw-semibold">{{ ym }}</div>
33
+ <a href="{{ url_for('customers.history', ym=next_ym) }}" class="btn btn-outline-secondary btn-sm">
34
+ 次月 <i class="bi bi-chevron-right"></i>
35
+ </a>
36
+ </div>
37
+
38
+ <form id="history-form" method="post" action="{{ url_for('customers.save_history') }}" data-dirty-form>
39
+ <input type="hidden" name="ym" value="{{ ym }}">
40
+ <div class="card">
41
+ <div class="table-responsive">
42
+ <table class="table table-bordered table-sm mb-0">
43
+ <thead class="table-dark">
44
+ <tr>
45
+ <th>日付</th>
46
+ <th class="text-center">朝食</th>
47
+ <th class="text-center">ディナー</th>
48
+ </tr>
49
+ </thead>
50
+ <tbody>
51
+ {% for d in dates %}
52
+ {% set ds = d|string %}
53
+ {% set cnt = data.get(ds, {}) %}
54
+ {% set dow = d.weekday() %}
55
+ {% set is_holiday = ds in holidays %}
56
+ <tr class="{{ 'table-danger' if (dow == 6 or is_holiday) else 'table-primary' if dow == 5 else '' }}">
57
+ <td>
58
+ {{ d.strftime('%m/%d') }}
59
+ <small class="text-muted">{{ ['月','火','水','木','金','土','日'][dow] }}{{ '(祝)' if is_holiday else '' }}</small>
60
+ </td>
61
+ <td>
62
+ <input type="number" id="b_{{ ds }}" name="b_{{ ds }}"
63
+ value="{{ cnt.get('breakfast', '') }}"
64
+ class="form-control form-control-sm text-center" min="0" style="width:80px"
65
+ onpaste="handleHistoryPaste(event, {{ loop.index0 }}, 0)">
66
+ </td>
67
+ <td>
68
+ <input type="number" id="d_{{ ds }}" name="d_{{ ds }}"
69
+ value="{{ cnt.get('dinner', '') }}"
70
+ class="form-control form-control-sm text-center" min="0" style="width:80px"
71
+ onpaste="handleHistoryPaste(event, {{ loop.index0 }}, 1)">
72
+ </td>
73
+ </tr>
74
+ {% endfor %}
75
+ </tbody>
76
+ </table>
77
+ </div>
78
+ </div>
79
+ </form>
80
+ </div>
81
+ {% endblock %}
82
+ {% block scripts %}
83
+ <script>
84
+ const HISTORY_DATES = {{ (dates | map('string') | list) | tojson }};
85
+
86
+ function handleHistoryPaste(e, rowIdx, col) {
87
+ const text = (e.clipboardData || window.clipboardData).getData('text');
88
+ if (!text) return;
89
+ let rows = text.replace(/\r/g, '').split('\n');
90
+ if (rows.length > 1 && rows[rows.length - 1] === '') rows.pop();
91
+ if (rows.length === 1 && !rows[0].includes('\t')) return; // 単一値はデフォルトの貼り付けに任せる
92
+ e.preventDefault();
93
+ rows.forEach((rowText, rOffset) => {
94
+ rowText.split('\t').forEach((val, cOffset) => {
95
+ const di = rowIdx + rOffset;
96
+ const ci = col + cOffset;
97
+ if (di >= HISTORY_DATES.length || ci > 1) return;
98
+ const input = document.getElementById((ci === 0 ? 'b_' : 'd_') + HISTORY_DATES[di]);
99
+ if (!input) return;
100
+ const num = val.trim().replace(/,/g, '');
101
+ input.value = num === '' ? '' : (parseInt(num, 10) || 0);
102
+ input.dispatchEvent(new Event('input', { bubbles: true }));
103
+ });
104
+ });
105
+ }
106
+ </script>
107
+ {% endblock %}
templates/customers/index.html CHANGED
@@ -31,24 +31,45 @@
31
  {% endif %}
32
 
33
  <!-- 期間セレクター -->
34
- <select class="form-select form-select-sm mb-3" style="max-width:220px"
35
- onchange="location.href='/customers/'+this.value">
36
- {% for p in periods %}
37
- <option value="{{ p.id }}" {{ 'selected' if p.id == period.id else '' }}>
38
- {{ p.start_date }} 〜 {{ p.end_date }}
39
- </option>
40
- {% endfor %}
41
- </select>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  <form id="cust-form" method="post" action="{{ url_for('customers.save', period_id=period.id) }}" data-dirty-form>
44
  <div class="card">
45
  <div class="table-responsive">
46
- <table class="table table-bordered table-sm mb-0">
47
  <thead class="table-dark">
48
  <tr>
49
  <th>日付</th>
50
  <th class="text-center">朝食</th>
51
  <th class="text-center">ディナー</th>
 
 
 
52
  </tr>
53
  </thead>
54
  <tbody>
@@ -59,7 +80,16 @@
59
  {% set is_holiday = ds in holidays %}
60
  {% set b_val = cnt.get('breakfast', 0) %}
61
  {% set d_val = cnt.get('dinner', 0) %}
62
- <tr class="{{ 'table-danger' if (dow == 6 or is_holiday) else 'table-primary' if dow == 5 else '' }}">
 
 
 
 
 
 
 
 
 
63
  <td>
64
  {{ d.strftime('%m/%d') }}
65
  <small class="text-muted">{{ ['月','火','水','木','金','土','日'][dow] }}{{ '(祝)' if is_holiday else '' }}</small>
@@ -75,6 +105,12 @@
75
  </span>
76
  {% endif %}
77
  </div>
 
 
 
 
 
 
78
  </td>
79
  <td>
80
  <div class="d-flex align-items-center gap-1">
@@ -87,7 +123,20 @@
87
  </span>
88
  {% endif %}
89
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
90
  </td>
 
91
  </tr>
92
  {% endfor %}
93
  </tbody>
@@ -114,5 +163,22 @@ function colorCell(input, threshold) {
114
  }
115
  document.querySelectorAll('input[name^="b_"]').forEach(el => colorCell(el, {{ thresh_b }}));
116
  document.querySelectorAll('input[name^="d_"]').forEach(el => colorCell(el, {{ thresh_d }}));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  </script>
118
  {% endblock %}
 
31
  {% endif %}
32
 
33
  <!-- 期間セレクター -->
34
+ <div class="d-flex align-items-center justify-content-between gap-2 mb-3 flex-wrap">
35
+ <select class="form-select form-select-sm" style="max-width:220px"
36
+ onchange="location.href='/customers/'+this.value">
37
+ {% for p in periods %}
38
+ <option value="{{ p.id }}" {{ 'selected' if p.id == period.id else '' }}>
39
+ {{ p.start_date }} 〜 {{ p.end_date }}
40
+ </option>
41
+ {% endfor %}
42
+ </select>
43
+ <a href="{{ url_for('customers.history') }}" class="btn btn-outline-secondary btn-sm">
44
+ <i class="bi bi-clock-history me-1"></i>過去客数データ入力(β)
45
+ </a>
46
+ </div>
47
+
48
+ {% if forecast_enabled %}
49
+ <div class="d-flex align-items-start gap-2 mb-3 p-3 rounded-3"
50
+ style="background:#1e293b;border-left:4px solid #38bdf8">
51
+ <i class="bi bi-graph-up-arrow text-info mt-1" style="flex-shrink:0"></i>
52
+ <div style="font-size:.85rem;color:#e2e8f0;line-height:1.6;flex:1">
53
+ 未入力の日には客数予測(β)を表示しています。<br>
54
+ <button type="button" class="btn btn-info btn-sm mt-1" onclick="applyForecast()">
55
+ <i class="bi bi-magic me-1"></i>予測値を未入力欄に反映
56
+ </button>
57
+ </div>
58
+ </div>
59
+ {% endif %}
60
 
61
  <form id="cust-form" method="post" action="{{ url_for('customers.save', period_id=period.id) }}" data-dirty-form>
62
  <div class="card">
63
  <div class="table-responsive">
64
+ <table class="table table-bordered table-sm mb-0" id="cust-table">
65
  <thead class="table-dark">
66
  <tr>
67
  <th>日付</th>
68
  <th class="text-center">朝食</th>
69
  <th class="text-center">ディナー</th>
70
+ {% if forecast_enabled %}
71
+ <th class="text-center" style="width:64px" title="特殊なイベント等で客数が大きく変動する日(予測モデルの学習・特徴量に使用)">特殊日</th>
72
+ {% endif %}
73
  </tr>
74
  </thead>
75
  <tbody>
 
80
  {% set is_holiday = ds in holidays %}
81
  {% set b_val = cnt.get('breakfast', 0) %}
82
  {% set d_val = cnt.get('dinner', 0) %}
83
+ {% set has_data = ds in counts %}
84
+ {% set fc = forecast.get(ds, {}) %}
85
+ {% set fc_b = fc.get('breakfast', {}) %}
86
+ {% set fc_d = fc.get('dinner', {}) %}
87
+ <tr class="{{ 'table-danger' if (dow == 6 or is_holiday) else 'table-primary' if dow == 5 else '' }}"
88
+ {% if forecast_enabled %}
89
+ data-has-data="{{ '1' if has_data else '0' }}"
90
+ data-fc-b="{{ fc_b.predicted if fc_b.predicted is not none else '' }}"
91
+ data-fc-d="{{ fc_d.predicted if fc_d.predicted is not none else '' }}"
92
+ {% endif %}>
93
  <td>
94
  {{ d.strftime('%m/%d') }}
95
  <small class="text-muted">{{ ['月','火','水','木','金','土','日'][dow] }}{{ '(祝)' if is_holiday else '' }}</small>
 
105
  </span>
106
  {% endif %}
107
  </div>
108
+ {% if forecast_enabled and fc_b.predicted is not none %}
109
+ <div class="text-muted" style="font-size:.68rem"
110
+ title="{{ method_labels.get(fc_b.method, '') }}{% if fc_b.low is not none %}({{ fc_b.low }}〜{{ fc_b.high }}人){% endif %}">
111
+ 予測 {{ fc_b.predicted }}人
112
+ </div>
113
+ {% endif %}
114
  </td>
115
  <td>
116
  <div class="d-flex align-items-center gap-1">
 
123
  </span>
124
  {% endif %}
125
  </div>
126
+ {% if forecast_enabled and fc_d.predicted is not none %}
127
+ <div class="text-muted" style="font-size:.68rem"
128
+ title="{{ method_labels.get(fc_d.method, '') }}{% if fc_d.low is not none %}({{ fc_d.low }}〜{{ fc_d.high }}人){% endif %}">
129
+ 予測 {{ fc_d.predicted }}人
130
+ </div>
131
+ {% endif %}
132
+ </td>
133
+ {% if forecast_enabled %}
134
+ <td class="text-center align-middle">
135
+ <input type="checkbox" class="form-check-input" name="special_{{ ds }}" value="1"
136
+ {{ 'checked' if cnt.get('is_special_day') else '' }}
137
+ onchange="window._formDirty = true">
138
  </td>
139
+ {% endif %}
140
  </tr>
141
  {% endfor %}
142
  </tbody>
 
163
  }
164
  document.querySelectorAll('input[name^="b_"]').forEach(el => colorCell(el, {{ thresh_b }}));
165
  document.querySelectorAll('input[name^="d_"]').forEach(el => colorCell(el, {{ thresh_d }}));
166
+
167
+ function applyForecast() {
168
+ document.querySelectorAll('#cust-table tbody tr').forEach(tr => {
169
+ if (tr.dataset.hasData === '1') return;
170
+ const fcB = tr.dataset.fcB, fcD = tr.dataset.fcD;
171
+ const inputB = tr.querySelector('input[name^="b_"]');
172
+ const inputD = tr.querySelector('input[name^="d_"]');
173
+ if (fcB && inputB) {
174
+ inputB.value = fcB;
175
+ inputB.dispatchEvent(new Event('input', { bubbles: true }));
176
+ }
177
+ if (fcD && inputD) {
178
+ inputD.value = fcD;
179
+ inputD.dispatchEvent(new Event('input', { bubbles: true }));
180
+ }
181
+ });
182
+ }
183
  </script>
184
  {% endblock %}
templates/dashboard/index.html CHANGED
@@ -263,6 +263,51 @@
263
  {% endif %}
264
  </div>
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  {# ───────────── 2. TODOリスト ───────────── #}
267
  <div class="section-label">TODO</div>
268
  {% if todos %}
 
263
  {% endif %}
264
  </div>
265
 
266
+ {# ───────────── 1.5 客数予測(β) ───────────── #}
267
+ {% if forecast_enabled %}
268
+ <div class="section-label">今後の客数予測(β)</div>
269
+ <div class="db-card-dark">
270
+ <div class="table-responsive">
271
+ <table class="table table-sm table-borderless mb-0" style="color:#e2e8f0;font-size:.78rem">
272
+ <thead>
273
+ <tr style="color:#64748b;font-size:.7rem">
274
+ <th></th>
275
+ <th class="text-center"><i class="bi bi-sun" style="color:#f59e0b"></i> 朝食</th>
276
+ <th class="text-center"><i class="bi bi-moon" style="color:#818cf8"></i> ディナー</th>
277
+ </tr>
278
+ </thead>
279
+ <tbody>
280
+ {% for row in forecast_rows %}
281
+ {% set b = row.breakfast %}
282
+ {% set dn = row.dinner %}
283
+ <tr>
284
+ <td>
285
+ {{ row.date.strftime('%m/%d') }}
286
+ <small class="text-muted">({{ DAY_JP[row.date.weekday()] }})</small>
287
+ {% if loop.first %}<small class="text-muted">本日</small>{% endif %}
288
+ </td>
289
+ <td class="text-center">
290
+ {% if b.predicted is not none %}
291
+ <span style="font-weight:700;{{ 'color:#f87171' if (thresh_b > 0 and b.predicted >= thresh_b) else 'color:#e2e8f0' }}">{{ b.predicted }}名</span>
292
+ {% else %}<span class="text-muted">―</span>{% endif %}
293
+ </td>
294
+ <td class="text-center">
295
+ {% if dn.predicted is not none %}
296
+ <span style="font-weight:700;{{ 'color:#f87171' if (thresh_d > 0 and dn.predicted >= thresh_d) else 'color:#e2e8f0' }}">{{ dn.predicted }}名</span>
297
+ {% else %}<span class="text-muted">―</span>{% endif %}
298
+ </td>
299
+ </tr>
300
+ {% endfor %}
301
+ </tbody>
302
+ </table>
303
+ </div>
304
+ <div class="text-muted" style="font-size:.68rem;margin-top:.4rem">
305
+ 過去の実績・曜日・気象などをもとにしたAI予測です。
306
+ <a href="{{ url_for('customers.list_periods') }}" style="color:#38bdf8">客数管理ページ</a>で実績を入力すると精度が向上します。
307
+ </div>
308
+ </div>
309
+ {% endif %}
310
+
311
  {# ───────────── 2. TODOリスト ───────────── #}
312
  <div class="section-label">TODO</div>
313
  {% if todos %}
templates/settings/index.html CHANGED
@@ -233,6 +233,39 @@
233
  </div>
234
  </div>
235
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  </form>
237
 
238
  <!-- バックアップ / リストア -->
 
233
  </div>
234
  </div>
235
  </div>
236
+
237
+ <!-- ベータ機能 -->
238
+ <div class="card mb-3">
239
+ <div class="card-body">
240
+ <h6 class="card-title text-muted mb-3">ベータ機能
241
+ <span class="help-btn" data-bs-toggle="popover" data-bs-trigger="click" data-bs-placement="bottom"
242
+ data-bs-title="客数予測(β)"
243
+ data-bs-content="過去の客数実績・曜日/祝日・気象データなどから朝食/ディナーの客数を予測し、客数管理ページとダッシュボードに表示します。予測精度を高めるには、客数管理画面で実績を入力し続けるか、過去客数データ入力ページから過去の実績を登録してください。緯度・経度を設定すると気象データを予測に利用できます(任意)。">?</span>
244
+ </h6>
245
+ <div class="form-check form-switch mb-3">
246
+ <input class="form-check-input" type="checkbox" role="switch" id="customer_forecast_enabled" name="customer_forecast_enabled"
247
+ {% if settings.get('customer_forecast_enabled', '0') == '1' %}checked{% endif %}>
248
+ <label class="form-check-label small fw-semibold" for="customer_forecast_enabled">
249
+ 客数予測機能を有効にする(β)
250
+ </label>
251
+ </div>
252
+ <div class="d-flex gap-3 flex-wrap">
253
+ <div>
254
+ <label class="form-label small fw-semibold mb-1">店舗の緯度</label>
255
+ <input type="number" name="store_lat" value="{{ settings.get('store_lat', '') }}"
256
+ step="0.0001" class="form-control form-control-sm" style="width:130px" placeholder="例: 35.6895">
257
+ </div>
258
+ <div>
259
+ <label class="form-label small fw-semibold mb-1">店舗の経度</label>
260
+ <input type="number" name="store_lon" value="{{ settings.get('store_lon', '') }}"
261
+ step="0.0001" class="form-control form-control-sm" style="width:130px" placeholder="例: 139.6917">
262
+ </div>
263
+ </div>
264
+ <div class="text-muted small mt-2">
265
+ 緯度・経度を設定すると、気象データ(Open-Meteo)を客数予測の精度向上に利用します。
266
+ </div>
267
+ </div>
268
+ </div>
269
  </form>
270
 
271
  <!-- バックアップ / リストア -->