GopiBNA commited on
Commit
b7a04bf
·
verified ·
1 Parent(s): 49bbb08

Upload feedback_store.py

Browse files
Files changed (1) hide show
  1. engine/feedback_store.py +378 -0
engine/feedback_store.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Feedback storage with status tracking + Excel export.
2
+
3
+ The Comparer Tool's Feedback tab collects free-text comments, project
4
+ references, plus uploaded attachments (screenshots, technical files).
5
+ This module is the storage layer.
6
+
7
+ Workflow per submission
8
+ -----------------------
9
+
10
+ 1. The Streamlit handler builds a dict of fields and a list of
11
+ (filename, bytes) attachments.
12
+ 2. ``save_submission()`` writes a self-contained folder under
13
+ ``$BNA_FEEDBACK_DIR`` (default ``/tmp/bna_feedback``) named
14
+ ``YYYYMMDD_HHMMSS_<8-char-id>``:
15
+
16
+ feedback.json -- all form fields + manifest
17
+ admin.json -- status + admin_notes (added later)
18
+ attachments/ -- every uploaded file, original name
19
+ attachments.zip -- same contents zipped
20
+
21
+ 3. The Admin tab can:
22
+ - Edit each submission's status + notes via ``update_submission()``.
23
+ - Pull every submission into one Excel via ``export_all_as_excel()``.
24
+ - Pull every submission + every attachment as one ZIP via
25
+ ``collect_all_as_zip()``.
26
+
27
+ Status workflow
28
+ ---------------
29
+
30
+ New submissions start with ``status = "Open"``. The team lead can move
31
+ each one through:
32
+
33
+ Open -> In Progress -> Resolved
34
+ \-> Won't Fix
35
+ \-> Closed
36
+
37
+ The status + admin_notes live in ``admin.json`` next to ``feedback.json``
38
+ so researcher-side metadata stays separate from team-lead metadata.
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import io
43
+ import json
44
+ import os
45
+ import uuid
46
+ import zipfile
47
+ from datetime import datetime, timezone
48
+ from pathlib import Path
49
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
50
+
51
+
52
+ # ---------------------------------------------------------------------
53
+ # Status workflow.
54
+ # ---------------------------------------------------------------------
55
+
56
+ STATUS_OPTIONS: Tuple[str, ...] = (
57
+ "Open",
58
+ "In Progress",
59
+ "Resolved",
60
+ "Won't Fix",
61
+ "Closed",
62
+ )
63
+
64
+ DEFAULT_STATUS = "Open"
65
+
66
+
67
+ # ---------------------------------------------------------------------
68
+ # Paths.
69
+ # ---------------------------------------------------------------------
70
+
71
+ def _root() -> Path:
72
+ raw = os.environ.get("BNA_FEEDBACK_DIR")
73
+ if raw:
74
+ return Path(raw)
75
+ return Path("/tmp/bna_feedback")
76
+
77
+
78
+ def _submission_dir(submission_id: str) -> Path:
79
+ return _root() / submission_id
80
+
81
+
82
+ # ---------------------------------------------------------------------
83
+ # Save.
84
+ # ---------------------------------------------------------------------
85
+
86
+ def _new_submission_id() -> str:
87
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
88
+ return f"{stamp}_{uuid.uuid4().hex[:8]}"
89
+
90
+
91
+ def _safe_name(name: str) -> str:
92
+ name = (name or "upload").strip().replace("\\", "_").replace("/", "_")
93
+ name = "".join(c for c in name if c.isalnum() or c in (".", "-", "_", " "))
94
+ return name[:120] or "upload"
95
+
96
+
97
+ def save_submission(
98
+ fields: Dict[str, Any],
99
+ attachments: Iterable[Tuple[str, bytes]] = (),
100
+ ) -> Dict[str, Any]:
101
+ """Persist a feedback submission + its attachments. Returns the
102
+ manifest dict written to ``feedback.json``."""
103
+ sid = _new_submission_id()
104
+ sdir = _submission_dir(sid)
105
+ sdir.mkdir(parents=True, exist_ok=True)
106
+ adir = sdir / "attachments"
107
+ adir.mkdir(exist_ok=True)
108
+
109
+ saved_attachments: List[Dict[str, Any]] = []
110
+ for raw_name, blob in attachments:
111
+ if not blob:
112
+ continue
113
+ name = _safe_name(raw_name)
114
+ out = adir / name
115
+ i = 1
116
+ base = out.stem
117
+ ext = out.suffix
118
+ while out.exists():
119
+ out = adir / f"{base}_{i}{ext}"
120
+ i += 1
121
+ out.write_bytes(blob)
122
+ saved_attachments.append({"name": out.name, "bytes": len(blob)})
123
+
124
+ manifest: Dict[str, Any] = {
125
+ "submission_id": sid,
126
+ "received_at": datetime.now(timezone.utc).isoformat(),
127
+ "fields": dict(fields),
128
+ "attachments": saved_attachments,
129
+ }
130
+ (sdir / "feedback.json").write_text(
131
+ json.dumps(manifest, indent=2, ensure_ascii=False),
132
+ encoding="utf-8",
133
+ )
134
+ try:
135
+ os.chmod(sdir / "feedback.json", 0o600)
136
+ except Exception:
137
+ pass
138
+
139
+ # Seed admin.json with the default Open status so it shows up in
140
+ # the data editor right away.
141
+ _write_admin(sid, {"status": DEFAULT_STATUS, "admin_notes": ""})
142
+
143
+ # Zip the per-submission folder for the team-lead bulk download.
144
+ zip_path = sdir / "attachments.zip"
145
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
146
+ zf.write(sdir / "feedback.json", arcname="feedback.json")
147
+ for att in saved_attachments:
148
+ zf.write(adir / att["name"], arcname=f"attachments/{att['name']}")
149
+
150
+ return manifest
151
+
152
+
153
+ # ---------------------------------------------------------------------
154
+ # Admin metadata (status + notes).
155
+ # ---------------------------------------------------------------------
156
+
157
+ def _admin_path(submission_id: str) -> Path:
158
+ return _submission_dir(submission_id) / "admin.json"
159
+
160
+
161
+ def _read_admin(submission_id: str) -> Dict[str, Any]:
162
+ p = _admin_path(submission_id)
163
+ if not p.exists():
164
+ return {"status": DEFAULT_STATUS, "admin_notes": ""}
165
+ try:
166
+ d = json.loads(p.read_text(encoding="utf-8"))
167
+ d.setdefault("status", DEFAULT_STATUS)
168
+ d.setdefault("admin_notes", "")
169
+ return d
170
+ except Exception:
171
+ return {"status": DEFAULT_STATUS, "admin_notes": ""}
172
+
173
+
174
+ def _write_admin(submission_id: str, data: Dict[str, Any]) -> None:
175
+ p = _admin_path(submission_id)
176
+ p.parent.mkdir(parents=True, exist_ok=True)
177
+ payload = {
178
+ "status": data.get("status") or DEFAULT_STATUS,
179
+ "admin_notes": data.get("admin_notes") or "",
180
+ "updated_at": datetime.now(timezone.utc).isoformat(),
181
+ }
182
+ p.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
183
+ try:
184
+ os.chmod(p, 0o600)
185
+ except Exception:
186
+ pass
187
+
188
+
189
+ def update_submission(
190
+ submission_id: str,
191
+ status: Optional[str] = None,
192
+ admin_notes: Optional[str] = None,
193
+ ) -> Dict[str, Any]:
194
+ """Set the team-lead status and / or notes for a submission. Only
195
+ the keys passed are updated; pass None to leave unchanged."""
196
+ cur = _read_admin(submission_id)
197
+ if status is not None:
198
+ if status not in STATUS_OPTIONS:
199
+ status = DEFAULT_STATUS
200
+ cur["status"] = status
201
+ if admin_notes is not None:
202
+ cur["admin_notes"] = admin_notes
203
+ _write_admin(submission_id, cur)
204
+ return cur
205
+
206
+
207
+ def update_many(updates: Dict[str, Dict[str, Any]]) -> int:
208
+ """Bulk update. ``updates`` keyed by submission_id, value is a dict
209
+ with optional ``status`` and ``admin_notes``. Returns count of
210
+ rows touched."""
211
+ n = 0
212
+ for sid, data in updates.items():
213
+ update_submission(
214
+ sid,
215
+ status=data.get("status"),
216
+ admin_notes=data.get("admin_notes"),
217
+ )
218
+ n += 1
219
+ return n
220
+
221
+
222
+ # ---------------------------------------------------------------------
223
+ # Listing + bulk downloads.
224
+ # ---------------------------------------------------------------------
225
+
226
+ def list_submissions() -> List[Dict[str, Any]]:
227
+ """List every submission folder. Newest first. Each row includes
228
+ the researcher manifest AND the admin overlay merged in."""
229
+ root = _root()
230
+ if not root.exists():
231
+ return []
232
+ out: List[Dict[str, Any]] = []
233
+ for sub in sorted(root.iterdir(), reverse=True):
234
+ if not sub.is_dir():
235
+ continue
236
+ meta = sub / "feedback.json"
237
+ if not meta.exists():
238
+ continue
239
+ try:
240
+ rec = json.loads(meta.read_text(encoding="utf-8"))
241
+ except Exception:
242
+ continue
243
+ admin = _read_admin(rec["submission_id"])
244
+ rec["status"] = admin.get("status", DEFAULT_STATUS)
245
+ rec["admin_notes"] = admin.get("admin_notes", "")
246
+ rec["admin_updated_at"] = admin.get("updated_at", "")
247
+ out.append(rec)
248
+ return out
249
+
250
+
251
+ def count_submissions() -> int:
252
+ return len(list_submissions())
253
+
254
+
255
+ def collect_all_as_zip() -> bytes:
256
+ """Bundle every feedback submission folder (researcher fields,
257
+ attachments, admin overlay) into one ZIP."""
258
+ buf = io.BytesIO()
259
+ root = _root()
260
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
261
+ if root.exists():
262
+ for sub in sorted(root.iterdir()):
263
+ if not sub.is_dir():
264
+ continue
265
+ for f in sub.rglob("*"):
266
+ if f.is_file():
267
+ zf.write(f, arcname=str(f.relative_to(root)))
268
+ return buf.getvalue()
269
+
270
+
271
+ # ---------------------------------------------------------------------
272
+ # Excel export -- meeting-friendly view.
273
+ # ---------------------------------------------------------------------
274
+
275
+ def export_all_as_excel() -> bytes:
276
+ """Return an .xlsx blob with one row per submission. The team lead
277
+ downloads this from the Admin tab to discuss in meetings."""
278
+ # Local import so the module stays cheap to import in non-Excel
279
+ # paths (e.g. the form-submit handler).
280
+ import openpyxl
281
+ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
282
+ from openpyxl.utils import get_column_letter
283
+
284
+ NAVY = "FF1E3A8A"
285
+ LIGHT = "FFF8FAFC"
286
+ BORDER_GREY = "FFE5E7EB"
287
+
288
+ headers = [
289
+ "Submission ID",
290
+ "Received at (UTC)",
291
+ "Status",
292
+ "Admin notes",
293
+ "Researcher name",
294
+ "Researcher email",
295
+ "Feedback type",
296
+ "Severity",
297
+ "Project name",
298
+ "Permalink",
299
+ "Subject",
300
+ "Comment",
301
+ "Attachments (count)",
302
+ "Attachment files",
303
+ "Last reviewed (UTC)",
304
+ ]
305
+
306
+ wb = openpyxl.Workbook()
307
+ ws = wb.active
308
+ ws.title = "Feedback log"
309
+
310
+ # Header styling.
311
+ header_font = Font(bold=True, color="FFFFFFFF", name="Calibri", size=11)
312
+ header_fill = PatternFill("solid", fgColor=NAVY)
313
+ thin = Side(style="thin", color=BORDER_GREY)
314
+ border = Border(top=thin, bottom=thin, left=thin, right=thin)
315
+ center = Alignment(horizontal="left", vertical="top", wrap_text=True)
316
+
317
+ for col_idx, h in enumerate(headers, start=1):
318
+ c = ws.cell(row=1, column=col_idx, value=h)
319
+ c.font = header_font
320
+ c.fill = header_fill
321
+ c.alignment = Alignment(horizontal="left", vertical="center")
322
+ c.border = border
323
+
324
+ # Body rows.
325
+ body_font = Font(name="Calibri", size=11)
326
+ row_idx = 2
327
+ for rec in list_submissions():
328
+ f = rec.get("fields", {})
329
+ atts = rec.get("attachments", []) or []
330
+ att_names = ", ".join(a.get("name", "") for a in atts)
331
+
332
+ values = [
333
+ rec.get("submission_id", ""),
334
+ rec.get("received_at", ""),
335
+ rec.get("status", DEFAULT_STATUS),
336
+ rec.get("admin_notes", ""),
337
+ f.get("researcher_name", ""),
338
+ f.get("researcher_email", ""),
339
+ f.get("feedback_type", ""),
340
+ f.get("severity", ""),
341
+ f.get("project_ref", ""),
342
+ f.get("permalink", ""),
343
+ f.get("subject", ""),
344
+ f.get("comment", ""),
345
+ len(atts),
346
+ att_names,
347
+ rec.get("admin_updated_at", ""),
348
+ ]
349
+ for col_idx, v in enumerate(values, start=1):
350
+ c = ws.cell(row=row_idx, column=col_idx, value=v)
351
+ c.font = body_font
352
+ c.alignment = center
353
+ c.border = border
354
+ # Tint the Status cell so it pops in the meeting view.
355
+ status = (rec.get("status") or "").lower()
356
+ status_cell = ws.cell(row=row_idx, column=3)
357
+ tint = {
358
+ "open": "FFFEE2E2",
359
+ "in progress": "FFFEF3C7",
360
+ "resolved": "FFDCFCE7",
361
+ "won't fix": "FFE5E7EB",
362
+ "closed": "FFE5E7EB",
363
+ }.get(status, "FFFFFFFF")
364
+ status_cell.fill = PatternFill("solid", fgColor=tint)
365
+ row_idx += 1
366
+
367
+ # Freeze header + auto column widths.
368
+ ws.freeze_panes = "A2"
369
+ widths = [22, 22, 13, 38, 22, 30, 14, 12, 28, 28, 30, 60, 8, 40, 22]
370
+ for i, w in enumerate(widths, start=1):
371
+ ws.column_dimensions[get_column_letter(i)].width = w
372
+ # Tall rows so wrapped Comment is visible.
373
+ for r in range(2, row_idx):
374
+ ws.row_dimensions[r].height = 42
375
+
376
+ buf = io.BytesIO()
377
+ wb.save(buf)
378
+ return buf.getvalue()