File size: 12,356 Bytes
b7a04bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Feedback storage with status tracking + Excel export.

The Comparer Tool's Feedback tab collects free-text comments, project
references, plus uploaded attachments (screenshots, technical files).
This module is the storage layer.

Workflow per submission
-----------------------

1. The Streamlit handler builds a dict of fields and a list of
   (filename, bytes) attachments.
2. ``save_submission()`` writes a self-contained folder under
   ``$BNA_FEEDBACK_DIR`` (default ``/tmp/bna_feedback``) named
   ``YYYYMMDD_HHMMSS_<8-char-id>``:

       feedback.json          -- all form fields + manifest
       admin.json             -- status + admin_notes (added later)
       attachments/           -- every uploaded file, original name
       attachments.zip        -- same contents zipped

3. The Admin tab can:
   - Edit each submission's status + notes via ``update_submission()``.
   - Pull every submission into one Excel via ``export_all_as_excel()``.
   - Pull every submission + every attachment as one ZIP via
     ``collect_all_as_zip()``.

Status workflow
---------------

New submissions start with ``status = "Open"``. The team lead can move
each one through:

    Open -> In Progress -> Resolved
                       \-> Won't Fix
                       \-> Closed

The status + admin_notes live in ``admin.json`` next to ``feedback.json``
so researcher-side metadata stays separate from team-lead metadata.
"""
from __future__ import annotations

import io
import json
import os
import uuid
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple


# ---------------------------------------------------------------------
# Status workflow.
# ---------------------------------------------------------------------

STATUS_OPTIONS: Tuple[str, ...] = (
    "Open",
    "In Progress",
    "Resolved",
    "Won't Fix",
    "Closed",
)

DEFAULT_STATUS = "Open"


# ---------------------------------------------------------------------
# Paths.
# ---------------------------------------------------------------------

def _root() -> Path:
    raw = os.environ.get("BNA_FEEDBACK_DIR")
    if raw:
        return Path(raw)
    return Path("/tmp/bna_feedback")


def _submission_dir(submission_id: str) -> Path:
    return _root() / submission_id


# ---------------------------------------------------------------------
# Save.
# ---------------------------------------------------------------------

def _new_submission_id() -> str:
    stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    return f"{stamp}_{uuid.uuid4().hex[:8]}"


def _safe_name(name: str) -> str:
    name = (name or "upload").strip().replace("\\", "_").replace("/", "_")
    name = "".join(c for c in name if c.isalnum() or c in (".", "-", "_", " "))
    return name[:120] or "upload"


def save_submission(
    fields: Dict[str, Any],
    attachments: Iterable[Tuple[str, bytes]] = (),
) -> Dict[str, Any]:
    """Persist a feedback submission + its attachments. Returns the
    manifest dict written to ``feedback.json``."""
    sid = _new_submission_id()
    sdir = _submission_dir(sid)
    sdir.mkdir(parents=True, exist_ok=True)
    adir = sdir / "attachments"
    adir.mkdir(exist_ok=True)

    saved_attachments: List[Dict[str, Any]] = []
    for raw_name, blob in attachments:
        if not blob:
            continue
        name = _safe_name(raw_name)
        out = adir / name
        i = 1
        base = out.stem
        ext = out.suffix
        while out.exists():
            out = adir / f"{base}_{i}{ext}"
            i += 1
        out.write_bytes(blob)
        saved_attachments.append({"name": out.name, "bytes": len(blob)})

    manifest: Dict[str, Any] = {
        "submission_id": sid,
        "received_at": datetime.now(timezone.utc).isoformat(),
        "fields": dict(fields),
        "attachments": saved_attachments,
    }
    (sdir / "feedback.json").write_text(
        json.dumps(manifest, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    try:
        os.chmod(sdir / "feedback.json", 0o600)
    except Exception:
        pass

    # Seed admin.json with the default Open status so it shows up in
    # the data editor right away.
    _write_admin(sid, {"status": DEFAULT_STATUS, "admin_notes": ""})

    # Zip the per-submission folder for the team-lead bulk download.
    zip_path = sdir / "attachments.zip"
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.write(sdir / "feedback.json", arcname="feedback.json")
        for att in saved_attachments:
            zf.write(adir / att["name"], arcname=f"attachments/{att['name']}")

    return manifest


# ---------------------------------------------------------------------
# Admin metadata (status + notes).
# ---------------------------------------------------------------------

def _admin_path(submission_id: str) -> Path:
    return _submission_dir(submission_id) / "admin.json"


def _read_admin(submission_id: str) -> Dict[str, Any]:
    p = _admin_path(submission_id)
    if not p.exists():
        return {"status": DEFAULT_STATUS, "admin_notes": ""}
    try:
        d = json.loads(p.read_text(encoding="utf-8"))
        d.setdefault("status", DEFAULT_STATUS)
        d.setdefault("admin_notes", "")
        return d
    except Exception:
        return {"status": DEFAULT_STATUS, "admin_notes": ""}


def _write_admin(submission_id: str, data: Dict[str, Any]) -> None:
    p = _admin_path(submission_id)
    p.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "status": data.get("status") or DEFAULT_STATUS,
        "admin_notes": data.get("admin_notes") or "",
        "updated_at": datetime.now(timezone.utc).isoformat(),
    }
    p.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
    try:
        os.chmod(p, 0o600)
    except Exception:
        pass


def update_submission(
    submission_id: str,
    status: Optional[str] = None,
    admin_notes: Optional[str] = None,
) -> Dict[str, Any]:
    """Set the team-lead status and / or notes for a submission. Only
    the keys passed are updated; pass None to leave unchanged."""
    cur = _read_admin(submission_id)
    if status is not None:
        if status not in STATUS_OPTIONS:
            status = DEFAULT_STATUS
        cur["status"] = status
    if admin_notes is not None:
        cur["admin_notes"] = admin_notes
    _write_admin(submission_id, cur)
    return cur


def update_many(updates: Dict[str, Dict[str, Any]]) -> int:
    """Bulk update. ``updates`` keyed by submission_id, value is a dict
    with optional ``status`` and ``admin_notes``. Returns count of
    rows touched."""
    n = 0
    for sid, data in updates.items():
        update_submission(
            sid,
            status=data.get("status"),
            admin_notes=data.get("admin_notes"),
        )
        n += 1
    return n


# ---------------------------------------------------------------------
# Listing + bulk downloads.
# ---------------------------------------------------------------------

def list_submissions() -> List[Dict[str, Any]]:
    """List every submission folder. Newest first. Each row includes
    the researcher manifest AND the admin overlay merged in."""
    root = _root()
    if not root.exists():
        return []
    out: List[Dict[str, Any]] = []
    for sub in sorted(root.iterdir(), reverse=True):
        if not sub.is_dir():
            continue
        meta = sub / "feedback.json"
        if not meta.exists():
            continue
        try:
            rec = json.loads(meta.read_text(encoding="utf-8"))
        except Exception:
            continue
        admin = _read_admin(rec["submission_id"])
        rec["status"] = admin.get("status", DEFAULT_STATUS)
        rec["admin_notes"] = admin.get("admin_notes", "")
        rec["admin_updated_at"] = admin.get("updated_at", "")
        out.append(rec)
    return out


def count_submissions() -> int:
    return len(list_submissions())


def collect_all_as_zip() -> bytes:
    """Bundle every feedback submission folder (researcher fields,
    attachments, admin overlay) into one ZIP."""
    buf = io.BytesIO()
    root = _root()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
        if root.exists():
            for sub in sorted(root.iterdir()):
                if not sub.is_dir():
                    continue
                for f in sub.rglob("*"):
                    if f.is_file():
                        zf.write(f, arcname=str(f.relative_to(root)))
    return buf.getvalue()


# ---------------------------------------------------------------------
# Excel export -- meeting-friendly view.
# ---------------------------------------------------------------------

def export_all_as_excel() -> bytes:
    """Return an .xlsx blob with one row per submission. The team lead
    downloads this from the Admin tab to discuss in meetings."""
    # Local import so the module stays cheap to import in non-Excel
    # paths (e.g. the form-submit handler).
    import openpyxl
    from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
    from openpyxl.utils import get_column_letter

    NAVY = "FF1E3A8A"
    LIGHT = "FFF8FAFC"
    BORDER_GREY = "FFE5E7EB"

    headers = [
        "Submission ID",
        "Received at (UTC)",
        "Status",
        "Admin notes",
        "Researcher name",
        "Researcher email",
        "Feedback type",
        "Severity",
        "Project name",
        "Permalink",
        "Subject",
        "Comment",
        "Attachments (count)",
        "Attachment files",
        "Last reviewed (UTC)",
    ]

    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Feedback log"

    # Header styling.
    header_font = Font(bold=True, color="FFFFFFFF", name="Calibri", size=11)
    header_fill = PatternFill("solid", fgColor=NAVY)
    thin = Side(style="thin", color=BORDER_GREY)
    border = Border(top=thin, bottom=thin, left=thin, right=thin)
    center = Alignment(horizontal="left", vertical="top", wrap_text=True)

    for col_idx, h in enumerate(headers, start=1):
        c = ws.cell(row=1, column=col_idx, value=h)
        c.font = header_font
        c.fill = header_fill
        c.alignment = Alignment(horizontal="left", vertical="center")
        c.border = border

    # Body rows.
    body_font = Font(name="Calibri", size=11)
    row_idx = 2
    for rec in list_submissions():
        f = rec.get("fields", {})
        atts = rec.get("attachments", []) or []
        att_names = ", ".join(a.get("name", "") for a in atts)

        values = [
            rec.get("submission_id", ""),
            rec.get("received_at", ""),
            rec.get("status", DEFAULT_STATUS),
            rec.get("admin_notes", ""),
            f.get("researcher_name", ""),
            f.get("researcher_email", ""),
            f.get("feedback_type", ""),
            f.get("severity", ""),
            f.get("project_ref", ""),
            f.get("permalink", ""),
            f.get("subject", ""),
            f.get("comment", ""),
            len(atts),
            att_names,
            rec.get("admin_updated_at", ""),
        ]
        for col_idx, v in enumerate(values, start=1):
            c = ws.cell(row=row_idx, column=col_idx, value=v)
            c.font = body_font
            c.alignment = center
            c.border = border
        # Tint the Status cell so it pops in the meeting view.
        status = (rec.get("status") or "").lower()
        status_cell = ws.cell(row=row_idx, column=3)
        tint = {
            "open": "FFFEE2E2",
            "in progress": "FFFEF3C7",
            "resolved": "FFDCFCE7",
            "won't fix": "FFE5E7EB",
            "closed": "FFE5E7EB",
        }.get(status, "FFFFFFFF")
        status_cell.fill = PatternFill("solid", fgColor=tint)
        row_idx += 1

    # Freeze header + auto column widths.
    ws.freeze_panes = "A2"
    widths = [22, 22, 13, 38, 22, 30, 14, 12, 28, 28, 30, 60, 8, 40, 22]
    for i, w in enumerate(widths, start=1):
        ws.column_dimensions[get_column_letter(i)].width = w
    # Tall rows so wrapped Comment is visible.
    for r in range(2, row_idx):
        ws.row_dimensions[r].height = 42

    buf = io.BytesIO()
    wb.save(buf)
    return buf.getvalue()