File size: 13,820 Bytes
4a4c518
 
 
 
 
 
 
 
387308c
 
4a4c518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25c892e
4a4c518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import io
import os
import shutil
import zipfile
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from dotenv import load_dotenv
import streamlit as st

from reporter.generate import generate_selected, list_people

load_dotenv()


st.set_page_config(page_title="BDC Report Generator", layout="wide")


def _require_login() -> None:
    """Login semplice via variabili d'ambiente (file .env).

    Variabili attese:
    - AUTH_USER
    - AUTH_PASSWORD

    Se non configurate, l'app resta accessibile (utile in sviluppo).
    """
    user = os.getenv("AUTH_USER", "")
    pwd = os.getenv("AUTH_PASSWORD", "")

    if not user or not pwd:
        return

    if st.session_state.get("auth_ok"):
        return

    st.markdown("<br>" * 3, unsafe_allow_html=True)
    _, col, _ = st.columns([1, 1.2, 1])
    with col:
        st.title("Bilancio Competenze")
        u = st.text_input("Username", key="_login_u", placeholder="inserisci username")
        p = st.text_input("Password", type="password", key="_login_p", placeholder="inserisci password")
        st.markdown("<br>", unsafe_allow_html=True)
        if st.button("Accedi", type="primary", use_container_width=True):
            if u == user and p == pwd:
                st.session_state.auth_ok = True
                st.rerun()
            else:
                st.error("Credenziali non valide", icon="πŸ”’")

    st.stop()


def _save_upload(upload, to_dir: Path) -> Optional[Path]:
    if upload is None:
        return None
    p = to_dir / upload.name
    p.write_bytes(upload.getbuffer())
    return p


def _zip_bytes(paths: List[Path]) -> bytes:
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
        for p in paths:
            if p.exists() and p.is_file():
                z.write(p, arcname=p.name)
    return buf.getvalue()


_require_login()

make_pdf = True

work_root = Path("/tmp/bdc_app")
work_root.mkdir(parents=True, exist_ok=True)


def _ensure_tmp() -> Path:
    if work_root.exists():
        shutil.rmtree(work_root)
    work_root.mkdir(parents=True, exist_ok=True)
    return work_root


def _load_people_lists(
    c_auto_p: Optional[Path],
    c_val_p: Optional[Path],
    m_auto_p: Optional[Path],
    m_val_p: Optional[Path],
) -> Tuple[List[str], List[str]]:
    collab_people: List[str] = []
    manager_people: List[str] = []
    if c_auto_p and c_val_p:
        collab_people = list_people(c_auto_p, c_val_p)
    if m_auto_p and m_val_p:
        manager_people = list_people(m_auto_p, m_val_p)
    return collab_people, manager_people


# ── Sidebar ────────────────────────────────────────────────────────────────────
with st.sidebar:
    st.title("βš™οΈ Impostazioni")
    sezioni = st.multiselect(
        "Tipologia",
        options=["Collaboratori", "Manager"],
        default=["Collaboratori", "Manager"],
    )

    show_collab = "Collaboratori" in sezioni
    show_manager = "Manager" in sezioni

    if show_collab:
        st.divider()
        st.title("πŸ‘₯ Collaboratori")
        tpl_collab = st.file_uploader("Modello Documento", type=["docx"], key="tpl_c")
        c_auto = st.file_uploader("Autovalutazione", type=["xlsx"], key="c_auto")
        c_val = st.file_uploader("Valutazione", type=["xlsx"], key="c_val")
        if all([tpl_collab, c_auto, c_val]):
            st.success("Files collaboratori inseriti", icon="βœ…")
        else:
            st.error("Inserire files collaboratori", icon="❌")
    else:
        tpl_collab = c_auto = c_val = None

    if show_manager:
        st.divider()
        st.title("🏒 Manager")
        tpl_manager = st.file_uploader("Modello Documento", type=["docx"], key="tpl_m")
        m_auto = st.file_uploader("Autovalutazione", type=["xlsx"], key="m_auto")
        m_val = st.file_uploader("Valutazione", type=["xlsx"], key="m_val")
        if all([tpl_manager, m_auto, m_val]):
            st.success("Files manager inseriti", icon="βœ…")
        else:
            st.error("Inserire files manager", icon="❌")
    else:
        tpl_manager = m_auto = m_val = None

    collab_ready = all([tpl_collab, c_auto, c_val])
    manager_ready = all([tpl_manager, m_auto, m_val])
    can_prepare = collab_ready or manager_ready

    st.divider()
    if st.button("Genera Report", type="primary", disabled=not can_prepare, use_container_width=True):
        tmp = _ensure_tmp()
        tpl_c_p = _save_upload(tpl_collab, tmp) if collab_ready else None
        tpl_m_p = _save_upload(tpl_manager, tmp) if manager_ready else None
        c_auto_p = _save_upload(c_auto, tmp) if collab_ready else None
        c_val_p = _save_upload(c_val, tmp) if collab_ready else None
        m_auto_p = _save_upload(m_auto, tmp) if manager_ready else None
        m_val_p = _save_upload(m_val, tmp) if manager_ready else None

        collab_people, manager_people = _load_people_lists(c_auto_p, c_val_p, m_auto_p, m_val_p)

        if not collab_people and not manager_people:
            st.error("Non ho trovato nessun nome nei file. Controlla la colonna 'Nome e cognome'.")
        else:
            st.session_state._paths = {
                "tpl_c": str(tpl_c_p) if tpl_c_p else "",
                "tpl_m": str(tpl_m_p) if tpl_m_p else "",
                "c_auto": str(c_auto_p) if c_auto_p else "",
                "c_val": str(c_val_p) if c_val_p else "",
                "m_auto": str(m_auto_p) if m_auto_p else "",
                "m_val": str(m_val_p) if m_val_p else "",
                "tmp": str(tmp),
            }
            st.session_state._collab_people = collab_people
            st.session_state._manager_people = manager_people
            st.session_state._phase = "select"
            st.session_state._results_ready = False
            st.rerun()


# ── Main area ──────────────────────────────────────────────────────────────────
st.title("πŸ“Š Bilancio Competenze")
with st.expander("ℹ️ Funzionamento", expanded=True):
    st.markdown(
        """
        Questa app genera report individuali di **Bilancio delle Competenze** in Word e PDF.
        ##### Istruzioni: 
        1. Nella barra laterale seleziona le sezioni da attivare (**Collaboratori**, **Manager**, o entrambe)
        2. Carica il template Word e i due file Excel (autovalutazione e valutazione) per ciascuna sezione
        3. Clicca **Genera Report** β€” scegli le persone da includere e scarica i report
        """
    )
st.divider()
phase = st.session_state.get("_phase")


# ── Fase: selezione persone ────────────────────────────────────────────────────
if phase == "select":
    collab_people: List[str] = st.session_state.get("_collab_people", [])
    manager_people: List[str] = st.session_state.get("_manager_people", [])

    col_c, col_m = st.columns(2)
    sel_c: List[str] = []
    sel_m: List[str] = []

    with col_c:
        st.subheader(f"πŸ‘₯ Collaboratori")
        for n in collab_people:
            if st.checkbox(n, value=True, key=f"c_{n}"):
                sel_c.append(n)

    with col_m:
        st.subheader(f"🏒 Manager")
        for n in manager_people:
            if st.checkbox(n, value=True, key=f"m_{n}"):
                sel_m.append(n)

    tot = len(sel_c) + len(sel_m)
    c1, c2= st.columns([1, 1])
    with c1:
        if st.button("Annulla", use_container_width=True):
            st.session_state._phase = None
            st.rerun()
    with c2:
        if st.button(f"Genera {tot} report", type="primary", disabled=tot == 0, use_container_width=True):
            st.session_state._selected_c = sel_c
            st.session_state._selected_m = sel_m
            st.session_state._phase = "generate"
            st.rerun()


# ── Fase: generazione ─────────────────────────────────────────────────────────
elif phase == "generate":
    sel_c = st.session_state.get("_selected_c", [])
    sel_m = st.session_state.get("_selected_m", [])
    total = len(sel_c) + len(sel_m)

    paths = st.session_state._paths

    def _p(key: str) -> Optional[Path]:
        v = paths.get(key, "")
        return Path(v) if v else None

    tpl_c_p, tpl_m_p = _p("tpl_c"), _p("tpl_m")
    c_auto_p, c_val_p = _p("c_auto"), _p("c_val")
    m_auto_p, m_val_p = _p("m_auto"), _p("m_val")
    out_dir = Path(paths["tmp"]) / "output"
    out_dir.mkdir(parents=True, exist_ok=True)

    header = st.empty()
    header.subheader(f"Generazione in corso… (0/{total})")
    progress = st.progress(0)
    log_area = st.empty()

    all_produced = []
    all_warnings: List[str] = []
    done = 0
    log_lines: List[str] = []

    for name in sel_c:
        log_lines.append(f"⏳ Collaboratore: **{name}**")
        log_area.markdown("\n\n".join(log_lines))
        r = generate_selected(
            collab_auto=c_auto_p, collab_valut=c_val_p, collab_template=tpl_c_p,
            manager_auto=None, manager_valut=None, manager_template=None,
            selected_collaboratori=[name], selected_manager=[],
            output_dir=out_dir, make_pdf=make_pdf,
        )
        all_produced.extend(r.produced)
        all_warnings.extend(r.warnings)
        done += 1
        log_lines[-1] = f"βœ… Collaboratore: **{name}**"
        log_area.markdown("\n\n".join(log_lines))
        progress.progress(done / total)
        header.subheader(f"Generazione in corso… ({done}/{total})")

    for name in sel_m:
        log_lines.append(f"⏳ Manager: **{name}**")
        log_area.markdown("\n\n".join(log_lines))
        r = generate_selected(
            collab_auto=None, collab_valut=None, collab_template=None,
            manager_auto=m_auto_p, manager_valut=m_val_p, manager_template=tpl_m_p,
            selected_collaboratori=[], selected_manager=[name],
            output_dir=out_dir, make_pdf=make_pdf,
        )
        all_produced.extend(r.produced)
        all_warnings.extend(r.warnings)
        done += 1
        log_lines[-1] = f"βœ… Manager: **{name}**"
        log_area.markdown("\n\n".join(log_lines))
        progress.progress(done / total)
        header.subheader(f"Generazione in corso… ({done}/{total})")

    header.subheader(f"Completato β€” {total} report generati βœ…")

    st.session_state._results = [
        {"person": a.person, "kind": a.kind,
         "docx_path": a.docx_path, "pdf_path": a.pdf_path, "notes": a.notes}
        for a in all_produced
    ]
    st.session_state._result_warnings = all_warnings
    st.session_state._results_ready = True
    st.session_state._phase = "results"
    st.rerun()


# ── Fase: risultati ────────────────────────────────────────────────────────────
elif phase == "results":
    results = st.session_state._results
    warnings = st.session_state.get("_result_warnings", [])

    if warnings:
        st.warning("\n".join(warnings))

    st.success(f"Generazione completata: {len(results)} report", icon="βœ…")

    all_files: List[Path] = []
    by_kind: Dict[str, list] = {}
    for a in sorted(results, key=lambda x: (x["kind"], x["person"])):
        by_kind.setdefault(a["kind"], []).append(a)

    def _render_table(artifacts: list) -> None:
        # Intestazione
        h0, h1, h2 = st.columns([4, 1, 1])
        h0.markdown("**Persona**")
        h1.markdown("**Word**")
        h2.markdown("**PDF**")
        for a in artifacts:
            c0, c1, c2 = st.columns([4, 1, 1])
            label = a["person"]
            if a["notes"]:
                label += f"  \n*{a['notes']}*"
            c0.markdown(label)

            docx_path = Path(a["docx_path"])
            all_files.append(docx_path)
            c1.download_button(
                "DOCX",
                data=docx_path.read_bytes(),
                file_name=docx_path.name,
                mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                use_container_width=True,
                key=f"docx_{a['kind']}_{a['person']}",
            )

            has_pdf = a["pdf_path"] and Path(a["pdf_path"]).exists()
            if has_pdf:
                pdf_path = Path(a["pdf_path"])
                all_files.append(pdf_path)
                c2.download_button(
                    "PDF",
                    data=pdf_path.read_bytes(),
                    file_name=pdf_path.name,
                    mime="application/pdf",
                    use_container_width=True,
                    key=f"pdf_{a['kind']}_{a['person']}",
                    type="primary",
                )

    kinds = list(by_kind.keys())
    if len(kinds) > 1:
        tabs = st.tabs(kinds)
        for tab, kind in zip(tabs, kinds):
            with tab:
                _render_table(by_kind[kind])
    else:
        st.subheader(kinds[0])
        _render_table(by_kind[kinds[0]])

    st.divider()
    c1, c2= st.columns([1, 1])
    with c1:
        if st.button("Annulla", use_container_width=True):
            st.session_state._phase = None
            st.rerun()
    with c2:             
        st.download_button(
            "Scarica Tutti i Files",
            data=_zip_bytes(all_files),
            file_name="BDC_report_output.zip",
            mime="application/zip",
            use_container_width=True,
            key="zip_all",
            type="primary",
        )