m1m02530125 commited on
Commit
0d2bb7c
·
1 Parent(s): 4abfdc1

CSVインポートプレビュー機能、確定解除確認フロー、およびアンドゥ機能の追加

Browse files
db/repositories.py CHANGED
@@ -926,6 +926,45 @@ def save_shift_constraints(constraints: dict):
926
 
927
  # ── 変更履歴ログ ─────────────────────────────────────────────────────────
928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929
  def get_assignment_log(period_id: int, limit: int = 50) -> list[dict]:
930
  """手動割当の変更履歴を新しい順で返す"""
931
  conn = get_connection()
 
926
 
927
  # ── 変更履歴ログ ─────────────────────────────────────────────────────────
928
 
929
+ def undo_last_assignment_change(period_id: int) -> dict | None:
930
+ """直近の手動割当変更を1件取り消し、取り消した内容を返す(履歴がなければ None)。
931
+
932
+ - add(追加)のログ → その割当を削除
933
+ - remove(削除)のログ → その割当を再追加(応援の時間指定までは復元しない)
934
+ 取り消したログ行自体も削除するため、連続実行で履歴を遡れる。
935
+ """
936
+ conn = get_connection()
937
+ try:
938
+ row = conn.execute(
939
+ """SELECT l.*, e.name AS emp_name
940
+ FROM assignment_log l
941
+ LEFT JOIN employees e ON e.id = l.employee_id
942
+ WHERE l.period_id = ?
943
+ ORDER BY l.id DESC LIMIT 1""",
944
+ (period_id,)
945
+ ).fetchone()
946
+ if not row:
947
+ return None
948
+ if row["action"] == "add":
949
+ conn.execute(
950
+ "DELETE FROM shift_assignments WHERE period_id=? AND employee_id=? AND date=? AND time_slot=?",
951
+ (period_id, row["employee_id"], row["date"], row["time_slot"])
952
+ )
953
+ elif row["action"] == "remove" and row["position"]:
954
+ conn.execute(
955
+ """INSERT INTO shift_assignments (period_id, employee_id, date, time_slot, position)
956
+ VALUES (?,?,?,?,?)
957
+ ON CONFLICT(period_id, employee_id, date, time_slot) DO UPDATE SET
958
+ position=excluded.position""",
959
+ (period_id, row["employee_id"], row["date"], row["time_slot"], row["position"])
960
+ )
961
+ conn.execute("DELETE FROM assignment_log WHERE id=?", (row["id"],))
962
+ conn.commit()
963
+ return dict(row._d) if hasattr(row, "_d") else dict(row)
964
+ finally:
965
+ conn.close()
966
+
967
+
968
  def get_assignment_log(period_id: int, limit: int = 50) -> list[dict]:
969
  """手動割当の変更履歴を新しい順で返す"""
970
  conn = get_connection()
routes/schedule.py CHANGED
@@ -491,6 +491,22 @@ def save_staff_note(period_id):
491
  return jsonify({"ok": True})
492
 
493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
  @bp.post("/<int:period_id>/reservation")
495
  def save_reservation(period_id):
496
  """予約客数(朝食見込・夜予約)のインライン保存"""
 
491
  return jsonify({"ok": True})
492
 
493
 
494
+ @bp.post("/<int:period_id>/undo")
495
+ def undo_change(period_id):
496
+ """直前の手動割当変更を取り消す"""
497
+ period = repo.get_period(period_id)
498
+ if period and period.status == "confirmed":
499
+ return jsonify({"ok": False, "error": "確定済みのシフトは変更できません。変更するには確定を解除してください。"}), 403
500
+ entry = repo.undo_last_assignment_change(period_id)
501
+ if not entry:
502
+ return jsonify({"ok": False, "error": "取り消せる変更がありません"}), 404
503
+ slot_jp = "朝食" if entry["time_slot"] == "breakfast" else "ディナー"
504
+ act_jp = "追加" if entry["action"] == "add" else "削除"
505
+ name = entry.get("emp_name") or f"ID{entry['employee_id']}"
506
+ return jsonify({"ok": True,
507
+ "message": f"{entry['date']} {slot_jp}「{name}」の{act_jp}を取り消しました"})
508
+
509
+
510
  @bp.post("/<int:period_id>/reservation")
511
  def save_reservation(period_id):
512
  """予約客数(朝食見込・夜予約)のインライン保存"""
routes/shifts.py CHANGED
@@ -27,10 +27,19 @@ def index():
27
  recent = sorted_periods[:4]
28
  older = sorted_periods[4:]
29
  show_all = request.args.get("all", type=int, default=0)
 
 
 
 
 
 
 
30
  return render_template("shifts/index.html",
31
- periods=recent if not show_all else sorted_periods,
32
  has_older=bool(older),
33
- show_all=show_all)
 
 
34
 
35
 
36
  @bp.post("/<int:period_id>/delete")
@@ -235,8 +244,17 @@ def import_csv_form(period_id):
235
  return render_template("shifts/import_csv.html", period=period, employees=employees)
236
 
237
 
 
 
 
 
 
 
 
 
238
  @bp.post("/<int:period_id>/import")
239
  def import_csv(period_id):
 
240
  period = repo.get_period(period_id)
241
  if not period:
242
  return redirect(url_for("shifts.index"))
@@ -246,14 +264,13 @@ def import_csv(period_id):
246
  flash("CSVファイルを選択してください", "error")
247
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
248
  merge = request.form.get("merge", "fill")
 
 
 
249
  try:
250
- import tempfile, os
251
- with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp:
252
- f.save(tmp.name)
253
- tmp_path = tmp.name
254
  from utils.forms_csv_parser import parse_forms_csv
255
  result = parse_forms_csv(tmp_path, period, employees)
256
- os.unlink(tmp_path)
257
  except Exception as e:
258
  flash(f"CSVの解析に失敗しました: {e}", "error")
259
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
@@ -262,6 +279,41 @@ def import_csv(period_id):
262
  flash("取込み可能なデータがありませんでした", "warning")
263
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  if merge == "overwrite":
266
  repo.save_shift_requests(period_id, result.requests)
267
  else:
 
27
  recent = sorted_periods[:4]
28
  older = sorted_periods[4:]
29
  show_all = request.args.get("all", type=int, default=0)
30
+ shown = recent if not show_all else sorted_periods
31
+ # 提出状況バッジ用: {period_id: 提出済みスタッフ数}
32
+ n_active = len(repo.get_all_employees(active_only=True))
33
+ submitted_counts = {
34
+ p.id: len({r.employee_id for r in repo.get_shift_requests(p.id)})
35
+ for p in shown
36
+ }
37
  return render_template("shifts/index.html",
38
+ periods=shown,
39
  has_older=bool(older),
40
+ show_all=show_all,
41
+ submitted_counts=submitted_counts,
42
+ n_active=n_active)
43
 
44
 
45
  @bp.post("/<int:period_id>/delete")
 
244
  return render_template("shifts/import_csv.html", period=period, employees=employees)
245
 
246
 
247
+ def _csv_tmp_path(token: str) -> str:
248
+ """プレビュー用に保存したCSVの一時パスを返す(トークンは英数字のみ許可)"""
249
+ import tempfile, os, re
250
+ if not re.fullmatch(r"[0-9a-f]{32}", token or ""):
251
+ raise ValueError("不正なトークンです")
252
+ return os.path.join(tempfile.gettempdir(), f"sdu_csv_{token}.csv")
253
+
254
+
255
  @bp.post("/<int:period_id>/import")
256
  def import_csv(period_id):
257
+ """CSVを解析してプレビューを表示する(この時点では取込まない)"""
258
  period = repo.get_period(period_id)
259
  if not period:
260
  return redirect(url_for("shifts.index"))
 
264
  flash("CSVファイルを選択してください", "error")
265
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
266
  merge = request.form.get("merge", "fill")
267
+ import uuid
268
+ token = uuid.uuid4().hex
269
+ tmp_path = _csv_tmp_path(token)
270
  try:
271
+ f.save(tmp_path)
 
 
 
272
  from utils.forms_csv_parser import parse_forms_csv
273
  result = parse_forms_csv(tmp_path, period, employees)
 
274
  except Exception as e:
275
  flash(f"CSVの解析に失敗しました: {e}", "error")
276
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
 
279
  flash("取込み可能なデータがありませんでした", "warning")
280
  return redirect(url_for("shifts.import_csv_form", period_id=period_id))
281
 
282
+ # fillモードで実際に追加される件数(既存と重複する分はスキップされる)
283
+ existing_keys = {(r.employee_id, r.date) for r in repo.get_shift_requests(period_id)}
284
+ n_new = sum(1 for r in result.requests if (r.employee_id, r.date) not in existing_keys)
285
+ n_skip = len(result.requests) - n_new
286
+
287
+ return render_template(
288
+ "shifts/import_preview.html",
289
+ period=period, token=token, merge=merge,
290
+ matched=result.matched, unmatched=result.unmatched_names,
291
+ warnings=result.warnings,
292
+ n_total=len(result.requests), n_new=n_new, n_skip=n_skip,
293
+ )
294
+
295
+
296
+ @bp.post("/<int:period_id>/import/confirm")
297
+ def import_csv_confirm(period_id):
298
+ """プレビュー確認後にCSV取込を実行する"""
299
+ import os
300
+ period = repo.get_period(period_id)
301
+ if not period:
302
+ return redirect(url_for("shifts.index"))
303
+ employees = repo.get_all_employees(active_only=True)
304
+ merge = request.form.get("merge", "fill")
305
+ try:
306
+ tmp_path = _csv_tmp_path(request.form.get("token", ""))
307
+ if not os.path.exists(tmp_path):
308
+ flash("プレビューの有効期限が切れました。もう一度ファイルを選択してください", "warning")
309
+ return redirect(url_for("shifts.import_csv_form", period_id=period_id))
310
+ from utils.forms_csv_parser import parse_forms_csv
311
+ result = parse_forms_csv(tmp_path, period, employees)
312
+ os.unlink(tmp_path)
313
+ except Exception as e:
314
+ flash(f"CSVの取込に失敗しました: {e}", "error")
315
+ return redirect(url_for("shifts.import_csv_form", period_id=period_id))
316
+
317
  if merge == "overwrite":
318
  repo.save_shift_requests(period_id, result.requests)
319
  else:
templates/schedule/index.html CHANGED
@@ -11,6 +11,9 @@
11
  .sched-grid th, .sched-grid td { white-space: nowrap; padding: .3rem .4rem; vertical-align: middle; min-width: 62px; }
12
  /* 左固定(横スクロール) */
13
  .sched-grid .emp-col { position: sticky; left: 0; background: white; z-index: 1; min-width: 90px; font-weight: 600; }
 
 
 
14
  /* 上固定(縦スクロール) */
15
  .sched-grid thead th { position: sticky; top: 0; z-index: 2; background: #1e293b; color: white; }
16
  /* 左上セル:縦横両方固定 */
@@ -224,6 +227,11 @@
224
  title="PDF出力{{ draft_hint }}" aria-label="PDF出力">
225
  <i class="bi bi-file-earmark-pdf"></i>
226
  </a>
 
 
 
 
 
227
  <button class="btn btn-outline-light btn-sm" onclick="openHistory({{ period.id }})" title="変更履歴" aria-label="変更履歴">
228
  <i class="bi bi-clock-history"></i>
229
  </button>
@@ -258,7 +266,7 @@
258
  <form id="confirm-form" method="post" action="{{ url_for('schedule.confirm', period_id=period.id) }}" style="display:none"></form>
259
  {% else %}
260
  <span class="badge bg-success flex-shrink-0"><i class="bi bi-lock-fill me-1"></i>確定済</span>
261
- <form method="post" action="{{ url_for('schedule.unconfirm', period_id=period.id) }}" class="flex-shrink-0">
262
  <button class="btn btn-outline-danger btn-sm">
263
  <i class="bi bi-lock-fill me-1"></i>確定解除
264
  </button>
@@ -343,7 +351,7 @@
343
  </div>
344
 
345
  <!-- シフトグリッド(朝食・ディナーを1つの表にまとめて表示) -->
346
- <div class="sched-grid">
347
  <table class="table table-bordered table-sm mb-0">
348
  <thead>
349
  <tr>
@@ -816,9 +824,26 @@ function openConfirmDialog() {
816
  new bootstrap.Modal(document.getElementById('confirmDialog')).show();
817
  }
818
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819
  function openAssignModal(cell) {
820
  if (IS_CONFIRMED) {
821
- showToast('確定済みのシフトは変更できません。変更するには確定を解除してください。', 'warning');
 
 
822
  return;
823
  }
824
  _cell = cell;
 
11
  .sched-grid th, .sched-grid td { white-space: nowrap; padding: .3rem .4rem; vertical-align: middle; min-width: 62px; }
12
  /* 左固定(横スクロール) */
13
  .sched-grid .emp-col { position: sticky; left: 0; background: white; z-index: 1; min-width: 90px; font-weight: 600; }
14
+ /* 確定中は割当セルをロック表示(クリックは「解除して編集」確認に流す) */
15
+ .sched-locked .cell-half { cursor: not-allowed !important; opacity: .8; }
16
+ .sched-locked .cell-half:hover { background: inherit !important; }
17
  /* 上固定(縦スクロール) */
18
  .sched-grid thead th { position: sticky; top: 0; z-index: 2; background: #1e293b; color: white; }
19
  /* 左上セル:縦横両方固定 */
 
227
  title="PDF出力{{ draft_hint }}" aria-label="PDF出力">
228
  <i class="bi bi-file-earmark-pdf"></i>
229
  </a>
230
+ {% if period.status != 'confirmed' %}
231
+ <button class="btn btn-outline-light btn-sm" onclick="undoLastChange()" title="直前の変更を元に戻す" aria-label="直前の変更を元に戻す">
232
+ <i class="bi bi-arrow-counterclockwise"></i>
233
+ </button>
234
+ {% endif %}
235
  <button class="btn btn-outline-light btn-sm" onclick="openHistory({{ period.id }})" title="変更履歴" aria-label="変更履歴">
236
  <i class="bi bi-clock-history"></i>
237
  </button>
 
266
  <form id="confirm-form" method="post" action="{{ url_for('schedule.confirm', period_id=period.id) }}" style="display:none"></form>
267
  {% else %}
268
  <span class="badge bg-success flex-shrink-0"><i class="bi bi-lock-fill me-1"></i>確定済</span>
269
+ <form id="unconfirm-form" method="post" action="{{ url_for('schedule.unconfirm', period_id=period.id) }}" class="flex-shrink-0">
270
  <button class="btn btn-outline-danger btn-sm">
271
  <i class="bi bi-lock-fill me-1"></i>確定解除
272
  </button>
 
351
  </div>
352
 
353
  <!-- シフトグリッド(朝食・ディナーを1つの表にまとめて表示) -->
354
+ <div class="sched-grid {{ 'sched-locked' if period.status == 'confirmed' else '' }}">
355
  <table class="table table-bordered table-sm mb-0">
356
  <thead>
357
  <tr>
 
824
  new bootstrap.Modal(document.getElementById('confirmDialog')).show();
825
  }
826
 
827
+ async function undoLastChange() {
828
+ try {
829
+ const res = await fetch(`/schedule/${PERIOD_ID}/undo`, {method: 'POST'});
830
+ const data = await res.json();
831
+ if (data.ok) {
832
+ showToast(data.message, 'success');
833
+ setTimeout(() => location.reload(), 700);
834
+ } else {
835
+ showToast(data.error || '取り消しに失敗しました', 'warning');
836
+ }
837
+ } catch (e) {
838
+ showToast('取り消しに失敗しました', 'danger');
839
+ }
840
+ }
841
+
842
  function openAssignModal(cell) {
843
  if (IS_CONFIRMED) {
844
+ if (confirm('このシフトは確定済みです。\n確定を解除して編集しますか?')) {
845
+ document.getElementById('unconfirm-form').submit();
846
+ }
847
  return;
848
  }
849
  _cell = cell;
templates/shifts/import_preview.html ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}CSV取込プレビュー - SDU-Shift{% endblock %}
3
+ {% block content %}
4
+ <div class="page-header">
5
+ <a href="{{ url_for('shifts.import_csv_form', period_id=period.id) }}" class="text-white me-2">
6
+ <i class="bi bi-arrow-left"></i>
7
+ </a>
8
+ <h1 class="fs-6"><i class="bi bi-search me-1"></i>CSV取込プレビュー</h1>
9
+ </div>
10
+ <div class="content">
11
+
12
+ <div class="alert alert-info small mb-3">
13
+ まだ取込まれていません。内容を確認して「取込を実行」を押してください。
14
+ </div>
15
+
16
+ {# ── サマリー ── #}
17
+ <div class="card mb-3">
18
+ <div class="card-body">
19
+ <h6 class="card-title text-muted mb-3">
20
+ {{ period.start_date }} 〜 {{ period.end_date }} への取込内容
21
+ </h6>
22
+ <div class="d-flex flex-wrap gap-3 mb-2">
23
+ <div>
24
+ <div class="fs-4 fw-bold">{{ matched | length }}<small class="fs-6 fw-normal text-muted">名</small></div>
25
+ <div class="small text-muted">マッチしたスタッフ</div>
26
+ </div>
27
+ <div>
28
+ <div class="fs-4 fw-bold">{{ n_total }}<small class="fs-6 fw-normal text-muted">件</small></div>
29
+ <div class="small text-muted">希望シフト合計</div>
30
+ </div>
31
+ {% if merge == 'fill' %}
32
+ <div>
33
+ <div class="fs-4 fw-bold text-success">{{ n_new }}<small class="fs-6 fw-normal text-muted">件</small></div>
34
+ <div class="small text-muted">追加される件数</div>
35
+ </div>
36
+ {% if n_skip %}
37
+ <div>
38
+ <div class="fs-4 fw-bold text-muted">{{ n_skip }}<small class="fs-6 fw-normal text-muted">件</small></div>
39
+ <div class="small text-muted">入力済みのためスキップ</div>
40
+ </div>
41
+ {% endif %}
42
+ {% endif %}
43
+ </div>
44
+ <div class="small text-muted">
45
+ 取込みモード:
46
+ {% if merge == 'overwrite' %}<strong class="text-danger">全て上書き</strong>(CSVの内容で全日付を置き換えます)
47
+ {% else %}<strong>未入力のみ追加</strong>(既に入力済みの日付は変更しません){% endif %}
48
+ </div>
49
+ </div>
50
+ </div>
51
+
52
+ {# ── 不一致・警告 ── #}
53
+ {% if unmatched %}
54
+ <div class="alert alert-warning small mb-3">
55
+ <strong><i class="bi bi-person-x me-1"></i>マッチしなかった名前({{ unmatched | length }}名):</strong>
56
+ この回答は取込まれません。スタッフ登録名と一致しているか確認してください。<br>
57
+ {% for name in unmatched %}<span class="badge bg-warning text-dark me-1">{{ name }}</span>{% endfor %}
58
+ </div>
59
+ {% endif %}
60
+ {% if warnings %}
61
+ <div class="alert alert-secondary small mb-3">
62
+ <strong><i class="bi bi-info-circle me-1"></i>解析時の注意:</strong>
63
+ <ul class="mb-0 mt-1">
64
+ {% for w in warnings %}<li>{{ w }}</li>{% endfor %}
65
+ </ul>
66
+ </div>
67
+ {% endif %}
68
+
69
+ {# ── スタッフ別件数 ── #}
70
+ <div class="card mb-3">
71
+ <div class="card-body">
72
+ <h6 class="card-title text-muted mb-2">スタッフ別の取込件数</h6>
73
+ <div class="d-flex flex-wrap gap-1">
74
+ {% for name, cnt in matched.items() %}
75
+ <span class="badge bg-secondary">{{ name }} <span class="badge bg-dark ms-1">{{ cnt }}</span></span>
76
+ {% endfor %}
77
+ </div>
78
+ </div>
79
+ </div>
80
+
81
+ {# ── 実行 / キャンセル ── #}
82
+ <div class="d-flex gap-2">
83
+ <form method="post" action="{{ url_for('shifts.import_csv_confirm', period_id=period.id) }}">
84
+ <input type="hidden" name="token" value="{{ token }}">
85
+ <input type="hidden" name="merge" value="{{ merge }}">
86
+ <button type="submit" class="btn btn-primary" data-loading="取込中…">
87
+ <i class="bi bi-check-lg me-1"></i>取込を実行
88
+ </button>
89
+ </form>
90
+ <a href="{{ url_for('shifts.import_csv_form', period_id=period.id) }}" class="btn btn-outline-secondary">
91
+ キャンセル
92
+ </a>
93
+ </div>
94
+ </div>
95
+ {% endblock %}
templates/shifts/index.html CHANGED
@@ -56,6 +56,11 @@
56
  <span class="badge {{ 'bg-success' if period.status == 'confirmed' else 'bg-secondary' }}">
57
  {{ '確定' if period.status == 'confirmed' else '下書き' }}
58
  </span>
 
 
 
 
 
59
  </div>
60
  <a href="{{ url_for('shifts.input', period_id=period.id) }}"
61
  class="btn btn-outline-primary btn-sm flex-shrink-0">
 
56
  <span class="badge {{ 'bg-success' if period.status == 'confirmed' else 'bg-secondary' }}">
57
  {{ '確定' if period.status == 'confirmed' else '下書き' }}
58
  </span>
59
+ {% set sub = submitted_counts.get(period.id, 0) %}
60
+ <span class="badge {{ 'bg-success' if sub >= n_active else 'bg-warning text-dark' if sub else 'bg-secondary' }}"
61
+ title="希望シフトを提出済みのスタッフ数 / 在籍スタッフ数">
62
+ <i class="bi bi-person-check me-1"></i>提出 {{ sub }}/{{ n_active }}
63
+ </span>
64
  </div>
65
  <a href="{{ url_for('shifts.input', period_id=period.id) }}"
66
  class="btn btn-outline-primary btn-sm flex-shrink-0">