File size: 10,044 Bytes
52ebfd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""
Excel export for Projektkalender.
Extracted from generate_projektkalender.py v6 — returns BytesIO instead of saving to disk.
"""

import io
from datetime import datetime, timedelta
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from config import (FONT_NAME, ALL_ITEMS, LEGEND_ORDER,
                    DAY_ABBREV_DE, MONTH_NAMES_DE, compute_date_range)


def generate_excel_bytes(active_projects, pipeline_projects, project_data):
    """Create day-by-day Excel Gantt chart. Returns BytesIO object."""
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = 'Projektkalender'

    # --- Determine date range ---
    date_range = compute_date_range(project_data)
    if date_range is None:
        buf = io.BytesIO()
        wb.save(buf)
        buf.seek(0)
        return buf

    min_date, max_date, days = date_range
    header_cols = 3

    thin_border = Border(
        left=Side(style='thin', color='D9D9D9'),
        right=Side(style='thin', color='D9D9D9'),
        top=Side(style='thin', color='D9D9D9'),
        bottom=Side(style='thin', color='D9D9D9')
    )

    # --- Legend rows (1-3) ---
    legend_items = [(k, ALL_ITEMS[k]) for k in LEGEND_ORDER if k in ALL_ITEMS]
    for row_idx in range(3):
        for col_idx in range(3):
            li_idx = row_idx * 3 + col_idx
            if li_idx < len(legend_items):
                name, cfg = legend_items[li_idx]
                cell = ws.cell(row=row_idx + 1, column=col_idx + 1, value=cfg['label'])
                cell.fill = PatternFill(start_color=cfg['color'], end_color=cfg['color'], fill_type='solid')
                cell.font = Font(name=FONT_NAME, size=8, bold=True, color=cfg.get('font_color', '000000'))
                cell.alignment = Alignment(horizontal='center', vertical='center')

    # --- Row 1: KW headers ---
    current_kw = None
    kw_start_col = None
    for idx, day in enumerate(days):
        col = header_cols + 1 + idx
        iso_cal = day.isocalendar()
        kw_key = (iso_cal[0], iso_cal[1])
        if kw_key != current_kw:
            if current_kw is not None and kw_start_col is not None:
                prev_col = col - 1
                if prev_col > kw_start_col:
                    ws.merge_cells(start_row=1, start_column=kw_start_col, end_row=1, end_column=prev_col)
            current_kw = kw_key
            kw_start_col = col
            cell = ws.cell(row=1, column=col, value=f'KW{iso_cal[1]}')
            cell.font = Font(name=FONT_NAME, size=8, bold=True)
            cell.alignment = Alignment(horizontal='center')
    if kw_start_col:
        last_col = header_cols + len(days)
        if last_col > kw_start_col:
            ws.merge_cells(start_row=1, start_column=kw_start_col, end_row=1, end_column=last_col)

    # --- Row 2: Month headers ---
    current_month = None
    month_start_col = None
    for idx, day in enumerate(days):
        col = header_cols + 1 + idx
        month_key = (day.year, day.month)
        if month_key != current_month:
            if current_month is not None and month_start_col is not None:
                prev_col = col - 1
                if prev_col > month_start_col:
                    ws.merge_cells(start_row=2, start_column=month_start_col, end_row=2, end_column=prev_col)
            current_month = month_key
            month_start_col = col
            cell = ws.cell(row=2, column=col, value=f'{MONTH_NAMES_DE[day.month]} {day.year}')
            cell.font = Font(name=FONT_NAME, size=7, color='666666')
            cell.alignment = Alignment(horizontal='center')
    if month_start_col:
        last_col = header_cols + len(days)
        if last_col > month_start_col:
            ws.merge_cells(start_row=2, start_column=month_start_col, end_row=2, end_column=last_col)

    # --- Row 3: Date ---
    for idx, day in enumerate(days):
        col = header_cols + 1 + idx
        cell = ws.cell(row=3, column=col, value=day)
        cell.number_format = 'D.M'
        cell.font = Font(name=FONT_NAME, size=6, color='999999')
        cell.alignment = Alignment(horizontal='center')

    # --- Row 4: Weekday abbreviations ---
    for idx, day in enumerate(days):
        col = header_cols + 1 + idx
        cell = ws.cell(row=4, column=col, value=DAY_ABBREV_DE[day.weekday()])
        cell.font = Font(name=FONT_NAME, size=6, color='999999')
        cell.alignment = Alignment(horizontal='center')

    # --- Row 5: Column headers ---
    ws.cell(row=5, column=1, value='Project').font = Font(name=FONT_NAME, size=8, bold=True)
    ws.cell(row=5, column=2, value='Research').font = Font(name=FONT_NAME, size=8, bold=True)
    ws.cell(row=5, column=3, value='PM').font = Font(name=FONT_NAME, size=8, bold=True)

    # --- Column widths ---
    ws.column_dimensions['A'].width = 42
    ws.column_dimensions['B'].width = 16
    ws.column_dimensions['C'].width = 16
    for idx, day in enumerate(days):
        col_letter = get_column_letter(header_cols + 1 + idx)
        ws.column_dimensions[col_letter].width = 2.5 if day.weekday() >= 5 else 3.5

    # --- Data rows ---
    weekend_fill = PatternFill(start_color='F5F5F5', end_color='F5F5F5', fill_type='solid')
    row_num = 6

    def write_project_rows(projects):
        nonlocal row_num
        for proj in projects:
            items = project_data.get(proj['key'], {})
            ws.cell(row=row_num, column=1, value=proj['name']).font = Font(name=FONT_NAME, size=8)
            ws.cell(row=row_num, column=1).alignment = Alignment(wrap_text=True, vertical='center')
            ws.cell(row=row_num, column=2, value=proj['lead']).font = Font(name=FONT_NAME, size=8)
            ws.cell(row=row_num, column=3, value='').font = Font(name=FONT_NAME, size=8)

            for idx, day in enumerate(days):
                col = header_cols + 1 + idx
                cell = ws.cell(row=row_num, column=col)
                cell.border = thin_border
                if day.weekday() >= 5:
                    cell.fill = weekend_fill

                active_item = None
                active_order = -1
                for item_name, config in ALL_ITEMS.items():
                    item_data = items.get(item_name)
                    if not item_data or not item_data.get('start'):
                        continue
                    p_start = datetime.strptime(item_data['start'], '%Y-%m-%d')
                    p_end = datetime.strptime(item_data['end'], '%Y-%m-%d') if item_data.get('end') else p_start
                    if p_start.date() <= day.date() <= p_end.date():
                        if config['order'] > active_order:
                            active_item = item_name
                            active_order = config['order']

                if active_item:
                    cfg = ALL_ITEMS[active_item]
                    cell.fill = PatternFill(start_color=cfg['color'], end_color=cfg['color'], fill_type='solid')
            row_num += 1

    write_project_rows(active_projects)

    # --- Pipeline separator ---
    if pipeline_projects:
        row_num += 1
        pipeline_fill = PatternFill(start_color='D9D9D9', end_color='D9D9D9', fill_type='solid')
        ws.cell(row=row_num, column=1, value='PIPELINE').font = Font(name=FONT_NAME, size=9, bold=True)
        ws.cell(row=row_num, column=1).fill = pipeline_fill
        for c in range(2, header_cols + len(days) + 1):
            ws.cell(row=row_num, column=c).fill = pipeline_fill
        row_num += 1
        write_project_rows(pipeline_projects)

    # --- Freeze panes ---
    ws.freeze_panes = 'D6'

    # --- Today marker ---
    today = datetime.now().date()
    today_col = None
    for idx, day in enumerate(days):
        if day.date() == today:
            today_col = header_cols + 1 + idx
            break

    if today_col:
        red_left = Border(left=Side(style='medium', color='FF0000'),
                          right=Side(style='thin', color='D9D9D9'),
                          top=Side(style='thin', color='D9D9D9'),
                          bottom=Side(style='thin', color='D9D9D9'))
        for r in range(3, 5):
            ws.cell(row=r, column=today_col).font = Font(name=FONT_NAME, size=6, color='FF0000', bold=True)
        for r in range(3, row_num + 1):
            ws.cell(row=r, column=today_col).border = red_left

    buf = io.BytesIO()
    wb.save(buf)
    buf.seek(0)
    return buf


def generate_dates_excel(proj, items_data, imap, pm_name=''):
    """Generate a small Excel with the phase dates for one project."""
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = 'Dates'

    ws.column_dimensions['A'].width = 30
    ws.column_dimensions['B'].width = 14
    ws.column_dimensions['C'].width = 14
    ws.column_dimensions['D'].width = 18

    hdr_font = Font(bold=True, size=10)
    ws.cell(row=1, column=1, value=f'{proj["name"]} ({proj["key"]})').font = Font(bold=True, size=12)
    ws.cell(row=2, column=1, value=f'Research: {proj["lead"]}').font = Font(size=10)
    if pm_name:
        ws.cell(row=2, column=2, value=f'PM: {pm_name}').font = Font(size=10)

    for c, label in enumerate(['Phase / Task', 'Start', 'End', 'Jira Issue'], 1):
        cell = ws.cell(row=4, column=c, value=label)
        cell.font = hdr_font

    row = 5
    for item_name in LEGEND_ORDER:
        if item_name not in ALL_ITEMS:
            continue
        cfg = ALL_ITEMS[item_name]
        item = items_data.get(item_name, {})
        im = imap.get(item_name, {})

        ws.cell(row=row, column=1, value=cfg['label'])
        if item.get('start'):
            ws.cell(row=row, column=2, value=item['start'])
        if item.get('end'):
            ws.cell(row=row, column=3, value=item['end'])

        keys = set(filter(None, [im.get('start_issue_key'), im.get('end_issue_key'), im.get('issue_key')]))
        if keys:
            ws.cell(row=row, column=4, value=', '.join(sorted(keys)))
        row += 1

    buf = io.BytesIO()
    wb.save(buf)
    buf.seek(0)
    return buf