m1m02530125 commited on
Commit
44bfede
·
1 Parent(s): 756d862

Excel出力をSDU_shiftテンプレート流し込み方式に変更

Browse files

- SDU_shift.xlsx を export/templates/ にテンプレート資産として同梱(Git LFS管理)
- 自前レイアウト生成をやめ、テンプレートを読み込んで値のみ流し込む方式に変更
(書式・マージ・列幅・印刷設定はテンプレートを完全保持)
- メモ1←日付メモ、朝食見込/夜予約←予約客数を流し込み(2ブロック目は参照式)
- K社員/K A・P/H社員/H A・P の枠に従業員を分類、枠不足時は行挿入で拡張
(マージ・行高・スタイルも追従)
- AY列に勤務時間合計式、AZ列に時給×時間の人件費式を出力
- 有給=緑/指定休=赤/備考=黄 のセル塗りをテンプレート凡例に準拠
- PDF側の希望休ラベルを「休」→「指定休」に統一

.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ export/templates/*.xlsx filter=lfs diff=lfs merge=lfs -text
export/excel_exporter.py CHANGED
@@ -1,67 +1,60 @@
1
- """Excel出力モジュール(従業員×日付 マトリクス形式)
2
-
3
- セルフォーマット: 1日=3列(開始時刻 / 区切り("-")または備考 / 終了時刻)
4
- 通常シフト : "13" / "-" / "22.5"
5
- 備考付きシフト: "6.5" / "オムレツ" / "15"
6
- 有給・休み等 : 3列マージして "有給" / "-" / "休" などを中央表示
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
  from __future__ import annotations
 
9
  from datetime import date
10
- from collections import defaultdict
11
- from openpyxl import Workbook
12
- from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
13
  from openpyxl.utils import get_column_letter
14
- from openpyxl.worksheet.properties import PageSetupProperties
15
  from models.employee import Employee
16
  from models.schedule import SchedulePeriod
17
- from utils.constants import TimeSlot, Position, SHIFT_CONSTRAINTS
18
- from utils.holidays import holiday_set
19
-
20
- # ── スタイル定数 ─────────────────────────────────────────────────────────
21
- THIN = Side(style="thin", color="CBD5E1")
22
- MED = Side(style="medium", color="94A3B8")
23
- BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
24
- BORDER_MED = Border(left=MED, right=MED, top=MED, bottom=MED)
25
-
26
- FILL_HDR = PatternFill("solid", fgColor="1E3A5F") # 濃紺(タイトル)
27
- FILL_NAME = PatternFill("solid", fgColor="E0F2FE") # 水色(名前列)
28
- FILL_SAT_H = PatternFill("solid", fgColor="93C5FD") # 青(土曜ヘッダー)
29
- FILL_SUN_H = PatternFill("solid", fgColor="FCA5A5") # 赤(日曜ヘッダー)
30
- FILL_WD_H = PatternFill("solid", fgColor="E2E8F0") # 薄グレー(平日ヘッダー)
31
- FILL_SAT_D = PatternFill("solid", fgColor="EFF6FF") # 極薄青(土曜データ)
32
- FILL_SUN_D = PatternFill("solid", fgColor="FFF1F2") # 極薄赤(日曜データ)
33
- FILL_LEAVE = PatternFill("solid", fgColor="D1FAE5") # 緑(有給)
34
- FILL_FT_OFF = PatternFill("solid", fgColor="FCA5A5") # 赤塗りつぶし(正社員希望休)
35
- FILL_AM_ONLY = PatternFill("solid", fgColor="DBEAFE") # 水色(朝のみ可)
36
- FILL_PM_ONLY = PatternFill("solid", fgColor="FED7AA") # オレンジ(晩のみ可)
37
- FILL_WHITE = PatternFill("solid", fgColor="FFFFFF") # 白(通常・白地)
38
- FILL_EVEN = PatternFill("solid", fgColor="FFFFFF") # 白(偶数行も白で統一)
39
- FILL_SUMMARY = PatternFill("solid", fgColor="F8FAFC") # 集計行・新規メモ/見込行
40
- # 備考欄:黄色網掛け(lightGray パターン × 黄色 on 白)
41
- FILL_MEMO = PatternFill(patternType="lightGray", fgColor="FDE047", bgColor="FFFFFF")
42
-
43
- FONT_TITLE = Font(color="FFFFFF", bold=True, size=12)
44
- FONT_HDR = Font(color="334155", bold=True, size=9)
45
- FONT_SAT = Font(color="1D4ED8", bold=True, size=9) # 土曜:青
46
- FONT_SUN = Font(color="DC2626", bold=True, size=9) # 日曜:赤
47
- FONT_NAME = Font(bold=True, size=9)
48
- FONT_DATA = Font(size=9)
49
- FONT_NOTE = Font(size=8, bold=True)
50
- FONT_LEAVE = Font(color="166534", bold=True, size=9) # 有給:緑
51
- FONT_FT_OFF = Font(color="DC2626", bold=True, size=9) # 正社員希望休:赤
52
- FONT_AM_ONLY = Font(color="1E40AF", bold=True, size=9) # 朝のみ可:青
53
- FONT_PM_ONLY = Font(color="C2410C", bold=True, size=9) # 晩のみ可:オレンジ
54
- FONT_OFF = Font(color="9CA3AF", size=9)
55
- FONT_SUM = Font(size=8)
56
-
57
- ALIGN_C = Alignment(horizontal="center", vertical="center", wrap_text=False)
58
- ALIGN_L = Alignment(horizontal="left", vertical="center")
59
- ALIGN_W = Alignment(horizontal="center", vertical="center", wrap_text=True)
60
 
61
  DAY_JP = ["月", "火", "水", "木", "金", "土", "日"]
62
 
63
- # 日付ブロックの列内訳(開始時刻 / 区切り・備考 / 終了時刻)
64
- COLS_PER_DAY = 3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  # ── ユーティリティ ────────────────────────────────────────────────────────
@@ -74,11 +67,8 @@ def _to_decimal(time_str: str) -> str:
74
  h, m = map(int, time_str.split(":"))
75
  if m == 0:
76
  return str(h)
77
- frac = m / 60.0
78
- val = h + frac
79
- # 小数点以下2桁、末尾0を除去
80
- s = f"{val:.2f}".rstrip("0").rstrip(".")
81
- return s
82
  except Exception:
83
  return time_str
84
 
@@ -108,7 +98,7 @@ def _get_shift_cells(
108
 
109
  # 正社員希望休
110
  if req and req.pattern_id == "off_request":
111
- return "", "休", "", "ft_off"
112
 
113
  # 有給チェック(paid_leave パターン or メモに「有給」)
114
  if (req and req.pattern_id == "paid_leave") or "有給" in note:
@@ -182,27 +172,58 @@ def _slot_default(b_pos, d_pos) -> tuple[str, str]:
182
  return s, e
183
 
184
 
185
- def _cell(ws, row, col, value="", fill=None, font=None, align=None, border=None):
186
- """セルを設定して返す"""
187
- c = ws.cell(row, col, value)
188
- if fill: c.fill = fill
189
- if font: c.font = font
190
- if align: c.alignment = align
191
- if border: c.border = border
192
- return c
193
-
194
-
195
- def _cell_merged(ws, row, start_col, end_col, value="", fill=None, font=None, align=None, border=None):
196
- """指定範囲を横方向にマージしてセルを設定する(日付1日分=3列など)"""
197
- for c in range(start_col, end_col + 1):
198
- cell = ws.cell(row, c)
199
- if fill: cell.fill = fill
200
- if border: cell.border = border
201
- ws.merge_cells(start_row=row, start_column=start_col, end_row=row, end_column=end_col)
202
- top = ws.cell(row, start_col, value)
203
- if font: top.font = font
204
- if align: top.alignment = align
205
- return top
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
 
208
  # ── メイン出力 ────────────────────────────────────────────────────────────
@@ -213,231 +234,127 @@ def export_excel(
213
  employees: list[Employee],
214
  assignments: dict,
215
  ):
216
- """
217
- シフト表を Excel に出力する。
218
-
219
- フォーマット:
220
- 行: 従業員(1行1人)
221
- 列: 日付(1日=3列: 開始時刻 / 区切り・備考 / 終了時刻)
222
- 両端に氏名列
223
- ヘッダー部に メモ1・メモ2・朝食見込・夜予約 の行(現状は空欄でレイアウトのみ)
224
- """
225
  from db import repositories as repo
226
  requests = repo.get_shift_requests(period.id)
227
  req_map = {(r.employee_id, r.date): r for r in requests}
228
- notes = repo.get_schedule_notes(period.id) # 日付メモ
 
229
 
230
- wb = Workbook()
231
  ws = wb.active
232
- ws.title = f"シフト表_{period.start_date}"
233
-
234
- dates = period.date_range()
235
- n = len(dates)
236
- holidays = holiday_set(dates)
237
-
238
- # 列インデックス
239
- C_NAME_L = 1 # 氏名(左)
240
- C_DATA = 2 # データ先頭
241
- C_NAME_R = C_DATA + n * COLS_PER_DAY # 氏名(右)
242
-
243
- # ──────────────────────────────────────────────────────────────────
244
- # 行 1: 期間タイトル
245
- # ──────────────────────────────────────────────────────────────────
246
- start_d = date.fromisoformat(period.start_date)
247
- title = f"{start_d.month}月 シフト表  {period.start_date} 〜 {period.end_date}"
248
- ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=C_NAME_R)
249
- _cell(ws, 1, 1, title, fill=FILL_HDR, font=FONT_TITLE, align=ALIGN_C)
250
- ws.row_dimensions[1].height = 22
251
-
252
- # ──────────────────────────────────────────────────────────────────
253
- # 行 2: 日付番号
254
- # ──────────────────────────────────────────────────────────────────
255
- _cell(ws, 2, C_NAME_L, "氏名", fill=FILL_NAME, font=FONT_NAME, align=ALIGN_C, border=BORDER)
256
- _cell(ws, 2, C_NAME_R, "氏名", fill=FILL_NAME, font=FONT_NAME, align=ALIGN_C, border=BORDER)
257
- for i, d in enumerate(dates):
258
- start_col = C_DATA + i * COLS_PER_DAY
259
- end_col = start_col + COLS_PER_DAY - 1
260
- dow = d.weekday()
261
- is_h = d.isoformat() in holidays
262
- fill = FILL_SUN_H if (dow == 6 or is_h) else (FILL_SAT_H if dow == 5 else FILL_WD_H)
263
- font = FONT_SUN if (dow == 6 or is_h) else (FONT_SAT if dow == 5 else FONT_HDR)
264
- _cell_merged(ws, 2, start_col, end_col, d.day, fill=fill, font=font, align=ALIGN_C, border=BORDER)
265
- ws.row_dimensions[2].height = 18
266
-
267
- # ──────────────────────────────────────────────────────────────────
268
- # 行 3: 曜日
269
- # ──────────────────────────────────────────────────────────────────
270
- _cell(ws, 3, C_NAME_L, "", fill=FILL_NAME, border=BORDER)
271
- _cell(ws, 3, C_NAME_R, "", fill=FILL_NAME, border=BORDER)
272
- for i, d in enumerate(dates):
273
- start_col = C_DATA + i * COLS_PER_DAY
274
- end_col = start_col + COLS_PER_DAY - 1
275
- dow = d.weekday()
276
- is_h = d.isoformat() in holidays
277
- fill = FILL_SUN_H if (dow == 6 or is_h) else (FILL_SAT_H if dow == 5 else FILL_WD_H)
278
- font = FONT_SUN if (dow == 6 or is_h) else (FONT_SAT if dow == 5 else FONT_HDR)
279
- label = DAY_JP[dow] + ("(祝)" if is_h else "")
280
- _cell_merged(ws, 3, start_col, end_col, label, fill=fill, font=font, align=ALIGN_C, border=BORDER)
281
- ws.row_dimensions[3].height = 15
282
-
283
- # ──────────────────────────────────────────────────────────────────
284
- # 行 4: 備考欄(黄色網掛け)
285
- # ──────────────────────────────────────────────────────────────────
286
- _cell(ws, 4, C_NAME_L, "備考", fill=FILL_MEMO,
287
- font=Font(size=8, color="78350F", bold=True), align=ALIGN_C, border=BORDER)
288
- _cell(ws, 4, C_NAME_R, "", fill=FILL_MEMO, border=BORDER)
289
- for i, d in enumerate(dates):
290
- start_col = C_DATA + i * COLS_PER_DAY
291
- end_col = start_col + COLS_PER_DAY - 1
292
- note = notes.get(d.isoformat(), "")
293
- _cell_merged(ws, 4, start_col, end_col, note, fill=FILL_MEMO,
294
- font=Font(size=8, color="78350F"), align=ALIGN_L, border=BORDER)
295
- ws.row_dimensions[4].height = 16
296
-
297
- # ──────────────────────────────────────────────────────────────────
298
- # 行 5-8: メモ1・メモ2・朝食見込・夜予約(SDU_shift.xlsx準拠のレイアウト、現状は空欄)
299
- # ──────────────────────────────────────────────────────────────────
300
- EXTRA_ROWS = [
301
- (5, "メモ1", 36),
302
- (6, "メモ2", 18),
303
- (7, "朝食見込", 18),
304
- (8, "夜予約", 18),
305
- ]
306
- for row_num, label, height in EXTRA_ROWS:
307
- _cell(ws, row_num, C_NAME_L, label, fill=FILL_SUMMARY, font=FONT_HDR, align=ALIGN_C, border=BORDER)
308
- _cell(ws, row_num, C_NAME_R, "", fill=FILL_SUMMARY, border=BORDER)
309
- for i in range(n):
310
- start_col = C_DATA + i * COLS_PER_DAY
311
- end_col = start_col + COLS_PER_DAY - 1
312
- _cell_merged(ws, row_num, start_col, end_col, "", fill=FILL_SUMMARY,
313
- font=FONT_HDR, align=ALIGN_C, border=BORDER)
314
- ws.row_dimensions[row_num].height = height
315
-
316
- # ──────────────────────────────────────────────────────────────────
317
- # 行 9+: 従業員データ
318
- # ──────────────────────────────────────────────────────────────────
319
- R_DATA = 9
320
- for row_idx, emp in enumerate(employees):
321
- r = R_DATA + row_idx
322
- is_even = (row_idx % 2 == 1)
323
- base_fill = FILL_EVEN if is_even else FILL_WHITE
324
-
325
- # 氏名(左)
326
- _cell(ws, r, C_NAME_L, emp.name, fill=FILL_NAME, font=FONT_NAME,
327
- align=ALIGN_L, border=BORDER)
328
-
329
- for i, d in enumerate(dates):
330
- start_col = C_DATA + i * COLS_PER_DAY
331
- sep_col = start_col + 1
332
- end_col = start_col + 2
333
- date_str = d.isoformat()
334
- dow = d.weekday()
335
- is_h = date_str in holidays
336
- s_txt, m_txt, e_txt, style = _get_shift_cells(emp.id, date_str, assignments, req_map)
337
-
338
- if style == "ft_off":
339
- fill = FILL_FT_OFF
340
- font = FONT_FT_OFF
341
- elif style == "leave":
342
- fill = FILL_LEAVE
343
- font = FONT_LEAVE
344
- elif style == "am_only":
345
- fill = FILL_AM_ONLY
346
- font = FONT_AM_ONLY
347
- elif style == "pm_only":
348
- fill = FILL_PM_ONLY
349
- font = FONT_PM_ONLY
350
- elif style == "off":
351
- fill = FILL_SUN_D if (dow == 6 or is_h) else (FILL_SAT_D if dow == 5 else base_fill)
352
- font = FONT_OFF
353
- elif style == "assigned_note":
354
- fill = base_fill
355
- font = FONT_NOTE
356
- else:
357
- fill = base_fill
358
- font = FONT_DATA
359
-
360
- if style in ("assigned", "assigned_note"):
361
- _cell(ws, r, start_col, s_txt, fill=fill, font=font, align=ALIGN_C, border=BORDER)
362
- _cell(ws, r, sep_col, m_txt, fill=fill, font=font, align=ALIGN_C, border=BORDER)
363
- _cell(ws, r, end_col, e_txt, fill=fill, font=font, align=ALIGN_C, border=BORDER)
364
- else:
365
- _cell_merged(ws, r, start_col, end_col, m_txt, fill=fill, font=font, align=ALIGN_C, border=BORDER)
366
-
367
- # 氏名(右)
368
- _cell(ws, r, C_NAME_R, emp.name, fill=FILL_NAME, font=FONT_NAME,
369
- align=ALIGN_L, border=BORDER)
370
-
371
- ws.row_dimensions[r].height = 18
372
-
373
- # ──────────────────────────────────────────────────────────────────
374
- # 集計行(ポジション×スロット別の人数・熟練者数)
375
- # ──────────────────────────────────────────────────────────────────
376
- count_map = defaultdict(int)
377
- skilled_map = defaultdict(int)
378
- for (emp_id, ds, slot_v), asgn_val in assignments.items():
379
- pos_v = asgn_val[0] if isinstance(asgn_val, tuple) else asgn_val
380
- count_map[(ds, slot_v, pos_v)] += 1
381
- emp = next((e for e in employees if e.id == emp_id), None)
382
- if emp and emp.is_skilled(pos_v, slot_v):
383
- skilled_map[(ds, slot_v, pos_v)] += 1
384
-
385
- SLOT_ROWS = [
386
- ("朝食 ホール", TimeSlot.BREAKFAST, Position.HALL),
387
- ("朝食 キッチン", TimeSlot.BREAKFAST, Position.KITCHEN),
388
- ("ディナー ホール", TimeSlot.DINNER, Position.HALL),
389
- ("ディナー キッチン", TimeSlot.DINNER, Position.KITCHEN),
390
- ]
391
- R_SUM = R_DATA + len(employees)
392
- for rel, (lbl, slot, pos) in enumerate(SLOT_ROWS):
393
- r = R_SUM + rel
394
- _cell(ws, r, C_NAME_L, lbl, fill=FILL_SUMMARY,
395
- font=Font(bold=True, size=8), align=ALIGN_C, border=BORDER)
396
-
397
- key = (slot, pos)
398
- const = SHIFT_CONSTRAINTS.get(key, {})
399
- min_req = const.get("min", 0)
400
- min_sk = const.get("min_skilled", 0)
401
-
402
- for i, d in enumerate(dates):
403
- start_col = C_DATA + i * COLS_PER_DAY
404
- end_col = start_col + COLS_PER_DAY - 1
405
- ds = d.isoformat()
406
- cnt = count_map[(ds, slot.value, pos.value)]
407
- sk = skilled_map[(ds, slot.value, pos.value)]
408
-
409
- if cnt < min_req or sk < min_sk:
410
- fill = PatternFill("solid", fgColor="FEE2E2")
411
- elif cnt == min_req:
412
- fill = PatternFill("solid", fgColor="FEF3C7")
413
- else:
414
- fill = PatternFill("solid", fgColor="D1FAE5")
415
-
416
- _cell_merged(ws, r, start_col, end_col, f"{cnt}名\n熟{sk}",
417
- fill=fill, font=FONT_SUM, align=ALIGN_W, border=BORDER)
418
-
419
- _cell(ws, r, C_NAME_R, "", fill=FILL_SUMMARY, border=BORDER)
420
- ws.row_dimensions[r].height = 26
421
-
422
- # ──────────────────────────────────────────────────────────────────
423
- # 列幅・印刷設定
424
- # ──────────────────────────────────────────────────────────────────
425
- ws.column_dimensions[get_column_letter(C_NAME_L)].width = 10
426
- ws.column_dimensions[get_column_letter(C_NAME_R)].width = 10
427
- for i in range(n):
428
- start_col = C_DATA + i * COLS_PER_DAY
429
- ws.column_dimensions[get_column_letter(start_col)].width = 4.5 # 開始時刻
430
- ws.column_dimensions[get_column_letter(start_col + 1)].width = 3 # 区切り・備考
431
- ws.column_dimensions[get_column_letter(start_col + 2)].width = 4.5 # 終了時刻
432
-
433
- ws.freeze_panes = "B9" # 名前列・ヘッダー(1-8行)を固定
434
-
435
- # 印刷設定: A4横向き・1ページに収める
436
- ws.sheet_properties.pageSetUpPr = PageSetupProperties(fitToPage=True)
437
- ws.page_setup.orientation = "landscape"
438
- ws.page_setup.paperSize = 9 # A4
439
- ws.page_setup.fitToWidth = 1 # 横1ページ
440
- ws.page_setup.fitToHeight = 1 # 縦1ページ
441
- ws.print_title_rows = "1:8"
442
 
443
  wb.save(path)
 
1
+ """Excel出力モジュール(SDU_shift テンプレート流し込み方式)
2
+
3
+ export/templates/SDU_shift_template.xlsx を読み込み、生成済みシフトデータを
4
+ 値として流し込む。書式・マージ・列幅・印刷設定はテンプレートのものを保持する。
5
+
6
+ テンプレートのレイアウト(1日 = 3列: 開始時刻 / 区切り("-")・備考 / 終了時刻):
7
+ 行1-2 : 日付・曜日(16ブロック、B〜AW列)
8
+ 行3-5 : メモ1(日付ごと縦3行マージ)← 日付メモ(schedule_notes)を流し込み
9
+ 行6 : メモ2(空欄のまま)
10
+ 行7-8 : 朝食見込・夜予約 ← 予約客数(reservation_counts)を流し込み
11
+ 行9-10 : キッチン社員 / 行11-28: キッチンA・P
12
+ 行29-32 : 2ブロック目ヘッダー(日付・曜日・朝食見込・夜予約=1ブロック目参照式)
13
+ 行33-35 : ホール社員 / 行36-51: ホールA・P
14
+ 行52-53 : フッター(日付・曜日)
15
+ AX列 : 右側氏名 / AY列: 勤務時間合計式 / AZ列: 人件費式(時給×時間)
16
+
17
+ 従業員数が枠数を超える場合はグループ末尾に行を挿入する(行高・マージも追従)。
18
  """
19
  from __future__ import annotations
20
+ from copy import copy
21
  from datetime import date
22
+ from pathlib import Path
23
+ from openpyxl import load_workbook
24
+ from openpyxl.styles import PatternFill
25
  from openpyxl.utils import get_column_letter
 
26
  from models.employee import Employee
27
  from models.schedule import SchedulePeriod
28
+ from utils.constants import TimeSlot, EmploymentType, PrimaryPosition
29
+
30
+ TEMPLATE_PATH = Path(__file__).parent / "templates" / "SDU_shift_template.xlsx"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  DAY_JP = ["月", "火", "水", "木", "金", "土", "日"]
33
 
34
+ # ── テンプレートのレイアウト定数 ─────────────────────────────────────────
35
+ N_BLOCKS = 16 # 日付ブロック数(B〜AW列)
36
+ COLS_PER_DAY = 3 # 1日 = 3列(開始 / 区切り・備考 / 終了)
37
+ C_DATA = 2 # データ先頭列(B)
38
+ C_NAME_L = 1 # 氏名列(左、A)
39
+ C_NAME_R = 50 # 氏名列(右、AX)
40
+ C_HOURS = 51 # 勤務時間合計式(AY)
41
+ C_WAGE = 52 # 人件費式(AZ)
42
+
43
+ R_DATE1, R_DOW1 = 1, 2 # 1ブロック目: 日付・曜日
44
+ R_MEMO1, R_MEMO2 = 3, 6 # メモ1(3-5行マージ)・メモ2
45
+ R_BF, R_DIN = 7, 8 # 朝食見込・夜予約
46
+ K_FT_START, K_FT_SLOTS = 9, 2 # キッチン社員
47
+ K_PT_START, K_PT_SLOTS = 11, 18 # キッチンA・P
48
+ R_DATE2 = 29 # 2ブロック目ヘッダー(日付/曜日/朝食見込/夜予約)
49
+ H_FT_START, H_FT_SLOTS = 33, 3 # ホール社員
50
+ H_PT_START, H_PT_SLOTS = 36, 16 # ホールA・P
51
+ R_DATE3 = 52 # フッター(日付/曜日)
52
+
53
+ # ── ステータス別のセル装飾(テンプレートの凡例に準拠)──────────────────
54
+ FILL_NONE = PatternFill(fill_type=None)
55
+ FILL_NOTE = PatternFill("solid", fgColor="FFFF00") # 黄: 備考メモ
56
+ FILL_LEAVE = PatternFill("solid", fgColor="B3E5A1") # 緑: 有給
57
+ FILL_FTOFF = PatternFill("solid", fgColor="FF0000") # 赤: 指定休
58
 
59
 
60
  # ── ユーティリティ ────────────────────────────────────────────────────────
 
67
  h, m = map(int, time_str.split(":"))
68
  if m == 0:
69
  return str(h)
70
+ val = h + m / 60.0
71
+ return f"{val:.2f}".rstrip("0").rstrip(".")
 
 
 
72
  except Exception:
73
  return time_str
74
 
 
98
 
99
  # 正社員希望休
100
  if req and req.pattern_id == "off_request":
101
+ return "", "指定休", "", "ft_off"
102
 
103
  # 有給チェック(paid_leave パターン or メモに「有給」)
104
  if (req and req.pattern_id == "paid_leave") or "有給" in note:
 
172
  return s, e
173
 
174
 
175
+ def _num_or_text(v: str):
176
+ """数値に変換できれば float/int、できなければ文字列のまま返す"""
177
+ if v == "":
178
+ return None
179
+ try:
180
+ f = float(v)
181
+ return int(f) if f.is_integer() else f
182
+ except ValueError:
183
+ return v
184
+
185
+
186
+ def _insert_rows_keep_layout(ws, idx: int, amount: int):
187
+ """idx 行の直前に amount 行挿入する。
188
+ openpyxl の insert_rows はマージセル・行高を追従させないため手動でずらし、
189
+ 挿入行のスタイル・行高は直前の行(同グループの枠)からコピーする。"""
190
+ if amount <= 0:
191
+ return
192
+ # マージ範囲の退避とシフト
193
+ to_shift = [r for r in list(ws.merged_cells.ranges) if r.min_row >= idx]
194
+ for r in to_shift:
195
+ ws.unmerge_cells(str(r))
196
+ ws.insert_rows(idx, amount)
197
+ for r in to_shift:
198
+ ws.merge_cells(start_row=r.min_row + amount, end_row=r.max_row + amount,
199
+ start_column=r.min_col, end_column=r.max_col)
200
+ # 行高のシフト(下から処理して上書きを防ぐ)
201
+ heights = {r: dim.height for r, dim in ws.row_dimensions.items()
202
+ if r >= idx and dim.height is not None}
203
+ for r in sorted(heights, reverse=True):
204
+ ws.row_dimensions[r + amount].height = heights[r]
205
+ # 挿入行: 直前の行からスタイル・行高をコピー
206
+ donor = idx - 1
207
+ donor_h = ws.row_dimensions[donor].height
208
+ for r in range(idx, idx + amount):
209
+ if donor_h:
210
+ ws.row_dimensions[r].height = donor_h
211
+ for c in range(1, C_WAGE + 1):
212
+ ws.cell(r, c)._style = copy(ws.cell(donor, c)._style)
213
+
214
+
215
+ def _block_col(i: int) -> int:
216
+ """日付ブロック i (0始まり) の先頭列"""
217
+ return C_DATA + i * COLS_PER_DAY
218
+
219
+
220
+ def _hours_formula(row: int) -> str:
221
+ """=(D9-B9)+(G9-E9)+...+(AW9-AU9) 形式の勤務時間合計式を返す"""
222
+ terms = []
223
+ for i in range(N_BLOCKS):
224
+ c = _block_col(i)
225
+ terms.append(f"({get_column_letter(c + 2)}{row}-{get_column_letter(c)}{row})")
226
+ return "=" + "+".join(terms)
227
 
228
 
229
  # ── メイン出力 ────────────────────────────────────────────────────────────
 
234
  employees: list[Employee],
235
  assignments: dict,
236
  ):
237
+ """SDU_shift テンプレートにシフトデータを流し込んで Excel を出力する"""
 
 
 
 
 
 
 
 
238
  from db import repositories as repo
239
  requests = repo.get_shift_requests(period.id)
240
  req_map = {(r.employee_id, r.date): r for r in requests}
241
+ notes = repo.get_schedule_notes(period.id) # 日付メモ → メモ1欄
242
+ reserves = repo.get_reservation_counts(period.id) # 予約客数 → 朝食見込・夜予約
243
 
244
+ wb = load_workbook(TEMPLATE_PATH)
245
  ws = wb.active
246
+
247
+ dates = list(period.date_range())[:N_BLOCKS] # テンプレートは最大16日分
248
+ n = len(dates)
249
+
250
+ # ── 従業員をテンプレートの4グループに分類 ─────────────────────────
251
+ # output_position 優先、未設定なら primary_position で判断
252
+ def _out_pos(e):
253
+ return e.output_position or e.primary_position
254
+
255
+ def _is_ft(e):
256
+ return e.employment_type == EmploymentType.FULL_TIME
257
+
258
+ kitchen = [e for e in employees if _out_pos(e) == PrimaryPosition.KITCHEN]
259
+ hall = [e for e in employees if _out_pos(e) != PrimaryPosition.KITCHEN]
260
+ k_ft = [e for e in kitchen if _is_ft(e)]
261
+ k_pt = [e for e in kitchen if not _is_ft(e)]
262
+ h_ft = [e for e in hall if _is_ft(e)]
263
+ h_pt = [e for e in hall if not _is_ft(e)]
264
+
265
+ # ── 枠が足りないグループには行を挿入(下のグルー��から処理)────────
266
+ k_ft_extra = max(0, len(k_ft) - K_FT_SLOTS)
267
+ k_pt_extra = max(0, len(k_pt) - K_PT_SLOTS)
268
+ h_ft_extra = max(0, len(h_ft) - H_FT_SLOTS)
269
+ h_pt_extra = max(0, len(h_pt) - H_PT_SLOTS)
270
+ _insert_rows_keep_layout(ws, H_PT_START + H_PT_SLOTS, h_pt_extra)
271
+ _insert_rows_keep_layout(ws, H_FT_START + H_FT_SLOTS, h_ft_extra)
272
+ _insert_rows_keep_layout(ws, K_PT_START + K_PT_SLOTS, k_pt_extra)
273
+ _insert_rows_keep_layout(ws, K_FT_START + K_FT_SLOTS, k_ft_extra)
274
+
275
+ # 挿入後の行位置
276
+ ko = k_ft_extra + k_pt_extra
277
+ k_pt_row = K_PT_START + k_ft_extra
278
+ r_date2 = R_DATE2 + ko
279
+ h_ft_row = H_FT_START + ko
280
+ h_pt_row = H_PT_START + ko + h_ft_extra
281
+ r_date3 = R_DATE3 + ko + h_ft_extra + h_pt_extra
282
+
283
+ # ── タイトル・シート名 ─────────────────────────────────────────────
284
+ start_d = date.fromisoformat(period.start_date)
285
+ end_d = date.fromisoformat(period.end_date)
286
+ half = "前半" if start_d.day <= 15 else "後半"
287
+ title = f"{start_d.month}月      {half}"
288
+ for r in (R_DATE1, r_date2, r_date3):
289
+ ws.cell(r, C_NAME_L).value = title
290
+ ws.cell(r, C_NAME_R).value = title
291
+ ws.title = (f"{start_d.month:02d}{start_d.day:02d}_{end_d.month:02d}{end_d.day:02d}"
292
+ + ("(確定)" if period.status == "confirmed" else ""))
293
+
294
+ # ── ヘッダー・フッター(日付/曜日/メモ/朝食見込/夜予約)────────────
295
+ for i in range(N_BLOCKS):
296
+ col = _block_col(i)
297
+ cl = get_column_letter(col)
298
+ if i < n:
299
+ d = dates[i]
300
+ ds = d.isoformat()
301
+ day_val = d.day
302
+ dow = DAY_JP[d.weekday()]
303
+ note = notes.get(ds, "") or None
304
+ res = reserves.get(ds, {})
305
+ bf = res.get("breakfast")
306
+ din = res.get("dinner")
307
+ else:
308
+ day_val = dow = note = bf = din = None
309
+
310
+ for r in (R_DATE1, r_date2, r_date3):
311
+ ws.cell(r, col).value = day_val
312
+ ws.cell(r + 1, col).value = dow
313
+ ws.cell(R_MEMO1, col).value = note
314
+ ws.cell(R_MEMO2, col).value = None
315
+ ws.cell(R_BF, col).value = bf
316
+ ws.cell(R_DIN, col).value = din
317
+ # 2ブロック目の朝食見込・夜予約は1ブロック目を参照する式(テンプレート流儀)
318
+ ws.cell(r_date2 + 2, col).value = f"={cl}{R_BF}" if bf is not None else None
319
+ ws.cell(r_date2 + 3, col).value = f"={cl}{R_DIN}" if din is not None else None
320
+
321
+ # ── 従業員グループの流し込み ───────────────────────────────────────
322
+ def _fill_group(start_row: int, slot_count: int, emps: list[Employee]):
323
+ for j in range(slot_count):
324
+ r = start_row + j
325
+ emp = emps[j] if j < len(emps) else None
326
+ ws.cell(r, C_NAME_L).value = emp.name if emp else None
327
+ ws.cell(r, C_NAME_R).value = emp.name if emp else None
328
+ # 全ブロックをクリア(テンプレートの凡例サンプル・前回値を消す)
329
+ for i in range(N_BLOCKS):
330
+ col = _block_col(i)
331
+ for cc in range(col, col + COLS_PER_DAY):
332
+ cell = ws.cell(r, cc)
333
+ cell.value = None
334
+ cell.fill = FILL_NONE
335
+ if emp is None:
336
+ ws.cell(r, C_HOURS).value = None
337
+ ws.cell(r, C_WAGE).value = None
338
+ continue
339
+ for i, d in enumerate(dates):
340
+ col = _block_col(i)
341
+ s_txt, m_txt, e_txt, style = _get_shift_cells(
342
+ emp.id, d.isoformat(), assignments, req_map)
343
+ ws.cell(r, col).value = _num_or_text(s_txt)
344
+ ws.cell(r, col + 1).value = m_txt or None
345
+ ws.cell(r, col + 2).value = _num_or_text(e_txt)
346
+ if style in ("assigned_note", "am_only", "pm_only"):
347
+ ws.cell(r, col + 1).fill = FILL_NOTE
348
+ elif style == "leave":
349
+ ws.cell(r, col + 1).fill = FILL_LEAVE
350
+ elif style == "ft_off":
351
+ ws.cell(r, col + 1).fill = FILL_FTOFF
352
+ ws.cell(r, C_HOURS).value = _hours_formula(r)
353
+ ws.cell(r, C_WAGE).value = f"=AY{r}*{emp.hourly_wage}" if emp.hourly_wage else None
354
+
355
+ _fill_group(K_FT_START, K_FT_SLOTS + k_ft_extra, k_ft)
356
+ _fill_group(k_pt_row, K_PT_SLOTS + k_pt_extra, k_pt)
357
+ _fill_group(h_ft_row, H_FT_SLOTS + h_ft_extra, h_ft)
358
+ _fill_group(h_pt_row, H_PT_SLOTS + h_pt_extra, h_pt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
 
360
  wb.save(path)
export/pdf_exporter.py CHANGED
@@ -3,7 +3,7 @@
3
  セルフォーマット: 1日=3列(開始時刻 / 区切り("-")または備考 / 終了時刻)
4
  通常シフト : "13" / "-" / "22.5"
5
  備考付きシフト: "6.5" / "オムレツ" / "15"
6
- 有給・休み等 : 3列分をSPANして "有給" / "-" / "休" などを中央表示
7
  """
8
  from __future__ import annotations
9
  from datetime import date
@@ -124,7 +124,7 @@ def _get_shift_cells(
124
 
125
  # 正社員希望休
126
  if req and req.pattern_id == "off_request":
127
- return "", "休", "", "ft_off"
128
 
129
  if (req and req.pattern_id == "paid_leave") or "有給" in note:
130
  return "", "有給", "", "leave"
 
3
  セルフォーマット: 1日=3列(開始時刻 / 区切り("-")または備考 / 終了時刻)
4
  通常シフト : "13" / "-" / "22.5"
5
  備考付きシフト: "6.5" / "オムレツ" / "15"
6
+ 有給・休み等 : 3列分をSPANして "有給" / "-" / "指定休" などを中央表示
7
  """
8
  from __future__ import annotations
9
  from datetime import date
 
124
 
125
  # 正社員希望休
126
  if req and req.pattern_id == "off_request":
127
+ return "", "指定休", "", "ft_off"
128
 
129
  if (req and req.pattern_id == "paid_leave") or "有給" in note:
130
  return "", "有給", "", "leave"
export/templates/SDU_shift_template.xlsx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:013e37c1ff501247a75a515acc34e0d600a934205b50fd8e4a83e444db3df3d0
3
+ size 142966