local-triage 0.0.0-stage → 0.10.0-dev.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/THIRD-PARTY-NOTICES.md +48 -0
  4. package/app/__init__.py +3 -0
  5. package/app/affiliation.py +137 -0
  6. package/app/ask.py +300 -0
  7. package/app/build_info.py +98 -0
  8. package/app/capec.py +168 -0
  9. package/app/capec_view.py +27 -0
  10. package/app/codecmp.py +59 -0
  11. package/app/config.py +411 -0
  12. package/app/context.py +1451 -0
  13. package/app/cvss.py +357 -0
  14. package/app/db.py +6234 -0
  15. package/app/defect.py +670 -0
  16. package/app/defect_check.py +323 -0
  17. package/app/defect_drafts.py +612 -0
  18. package/app/defect_dto.py +149 -0
  19. package/app/defect_fields.py +248 -0
  20. package/app/defect_form.py +124 -0
  21. package/app/defect_links.py +107 -0
  22. package/app/defect_local_text.py +103 -0
  23. package/app/defect_references.py +164 -0
  24. package/app/defect_where.py +147 -0
  25. package/app/ecosystem.py +51 -0
  26. package/app/executors.py +660 -0
  27. package/app/feeds.py +1231 -0
  28. package/app/guard.py +164 -0
  29. package/app/hub_block_builder.py +200 -0
  30. package/app/hub_block_version.py +220 -0
  31. package/app/hub_defects.py +4469 -0
  32. package/app/hub_effects.py +421 -0
  33. package/app/hub_entity_versions.py +108 -0
  34. package/app/hub_import.py +2054 -0
  35. package/app/hub_onboarding.py +114 -0
  36. package/app/hub_ops.py +330 -0
  37. package/app/hub_pull.py +1195 -0
  38. package/app/hub_state.py +255 -0
  39. package/app/hub_status.py +237 -0
  40. package/app/hub_sync.py +619 -0
  41. package/app/hub_sync_api.py +241 -0
  42. package/app/hub_sync_compare.py +1054 -0
  43. package/app/hub_sync_contract.py +75 -0
  44. package/app/hub_template_model.py +74 -0
  45. package/app/hub_text_scale.py +159 -0
  46. package/app/journal.py +250 -0
  47. package/app/llm.py +850 -0
  48. package/app/llm_chat.py +596 -0
  49. package/app/llm_http.py +319 -0
  50. package/app/llm_messages.py +401 -0
  51. package/app/llm_net.py +764 -0
  52. package/app/llm_ollama.py +571 -0
  53. package/app/lockfile.py +505 -0
  54. package/app/logsafe.py +54 -0
  55. package/app/main.py +367 -0
  56. package/app/mask_display.py +132 -0
  57. package/app/masking.py +814 -0
  58. package/app/metrics.py +194 -0
  59. package/app/model_traffic.py +519 -0
  60. package/app/models.py +483 -0
  61. package/app/navigation.py +121 -0
  62. package/app/osv.py +279 -0
  63. package/app/package_identity.py +189 -0
  64. package/app/package_transition.py +824 -0
  65. package/app/profile_gate.py +71 -0
  66. package/app/prompts.py +1108 -0
  67. package/app/provider_keys.py +189 -0
  68. package/app/providers.py +511 -0
  69. package/app/routes/__init__.py +10 -0
  70. package/app/routes/api.py +153 -0
  71. package/app/routes/capec.py +186 -0
  72. package/app/routes/common.py +407 -0
  73. package/app/routes/components.py +1499 -0
  74. package/app/routes/cwe.py +168 -0
  75. package/app/routes/decision_selected.py +153 -0
  76. package/app/routes/defect_add.py +223 -0
  77. package/app/routes/defect_card_routes.py +363 -0
  78. package/app/routes/defect_selected.py +342 -0
  79. package/app/routes/feeds.py +155 -0
  80. package/app/routes/findings.py +2736 -0
  81. package/app/routes/hub.py +402 -0
  82. package/app/routes/hub_bulk.py +288 -0
  83. package/app/routes/hub_defect_routes.py +1945 -0
  84. package/app/routes/hub_status_routes.py +1132 -0
  85. package/app/routes/hub_sync_routes.py +463 -0
  86. package/app/routes/journal.py +132 -0
  87. package/app/routes/projects.py +1601 -0
  88. package/app/routes/providers.py +336 -0
  89. package/app/routes/references.py +26 -0
  90. package/app/routes/runs.py +219 -0
  91. package/app/routes/sca.py +2722 -0
  92. package/app/routes/settings.py +163 -0
  93. package/app/run_errors.py +151 -0
  94. package/app/sca.py +1662 -0
  95. package/app/sca_contract.py +1289 -0
  96. package/app/sca_research.py +1089 -0
  97. package/app/sca_research_net.py +1007 -0
  98. package/app/sca_text.py +965 -0
  99. package/app/serve.py +70 -0
  100. package/app/settings_store.py +262 -0
  101. package/app/static/app.css +2802 -0
  102. package/app/static/app.js +3772 -0
  103. package/app/static/capec-license.txt +9 -0
  104. package/app/static/favicon.svg +1 -0
  105. package/app/static/fonts/Golos-Text_DemiBold.woff2 +0 -0
  106. package/app/static/fonts/Golos-Text_Regular.woff2 +0 -0
  107. package/app/static/fonts/OFL.txt +90 -0
  108. package/app/static/navigation.js +234 -0
  109. package/app/static/observability.js +121 -0
  110. package/app/static/theme.js +49 -0
  111. package/app/storage/__init__.py +16 -0
  112. package/app/storage/local_state.py +246 -0
  113. package/app/storage/migrate.py +110 -0
  114. package/app/storage/migrations/postgresql/0001_baseline.sql +896 -0
  115. package/app/storage/migrations/postgresql/0002_feeds_and_secrets.sql +55 -0
  116. package/app/storage/migrations/postgresql/0003_project_mask_display.sql +5 -0
  117. package/app/storage/migrations/postgresql/0004_package_identity.sql +36 -0
  118. package/app/storage/postgresql.py +573 -0
  119. package/app/storage/schema.py +619 -0
  120. package/app/storage/sql.py +57 -0
  121. package/app/storage/tools.py +254 -0
  122. package/app/telemetry.py +307 -0
  123. package/app/templates/base.html +91 -0
  124. package/app/templates/capec/context.html +3 -0
  125. package/app/templates/capec/detail.html +27 -0
  126. package/app/templates/capec/index.html +128 -0
  127. package/app/templates/components/_archive.html +11 -0
  128. package/app/templates/components/archived.html +19 -0
  129. package/app/templates/components/batch.html +35 -0
  130. package/app/templates/components/detail.html +332 -0
  131. package/app/templates/components/index.html +338 -0
  132. package/app/templates/components/research_preview.html +80 -0
  133. package/app/templates/components/research_run.html +54 -0
  134. package/app/templates/cwe/bdu.html +56 -0
  135. package/app/templates/cwe/detail.html +233 -0
  136. package/app/templates/cwe/index.html +97 -0
  137. package/app/templates/error.html +8 -0
  138. package/app/templates/feeds/index.html +65 -0
  139. package/app/templates/findings/card.html +639 -0
  140. package/app/templates/findings/decision_selected.html +41 -0
  141. package/app/templates/findings/defect_add.html +46 -0
  142. package/app/templates/findings/defect_selected.html +47 -0
  143. package/app/templates/findings/list.html +153 -0
  144. package/app/templates/findings/send_selected.html +53 -0
  145. package/app/templates/findings/trace.html +72 -0
  146. package/app/templates/journal/detail.html +19 -0
  147. package/app/templates/journal/index.html +19 -0
  148. package/app/templates/macros.html +440 -0
  149. package/app/templates/navigation-fields.html +1 -0
  150. package/app/templates/navigation.html +11 -0
  151. package/app/templates/projects/_identity_summary.html +42 -0
  152. package/app/templates/projects/defect_card.html +153 -0
  153. package/app/templates/projects/defect_create_preview.html +17 -0
  154. package/app/templates/projects/defect_fields_diff.html +6 -0
  155. package/app/templates/projects/defect_fields_form.html +40 -0
  156. package/app/templates/projects/defect_references.html +17 -0
  157. package/app/templates/projects/defect_sync_preview.html +28 -0
  158. package/app/templates/projects/defect_update_actions.html +6 -0
  159. package/app/templates/projects/defect_update_preview.html +24 -0
  160. package/app/templates/projects/defects.html +126 -0
  161. package/app/templates/projects/delete.html +31 -0
  162. package/app/templates/projects/external.html +61 -0
  163. package/app/templates/projects/folders.html +64 -0
  164. package/app/templates/projects/hub_accepted.html +10 -0
  165. package/app/templates/projects/hub_assignment.html +50 -0
  166. package/app/templates/projects/hub_pending.html +20 -0
  167. package/app/templates/projects/hub_pending_list.html +17 -0
  168. package/app/templates/projects/hub_state_note.html +23 -0
  169. package/app/templates/projects/hub_step_note.html +5 -0
  170. package/app/templates/projects/hub_sync.html +105 -0
  171. package/app/templates/projects/hub_sync_confirm.html +32 -0
  172. package/app/templates/projects/hub_sync_worker.html +5 -0
  173. package/app/templates/projects/hub_text_rules.html +64 -0
  174. package/app/templates/projects/identity_report.html +74 -0
  175. package/app/templates/projects/list.html +90 -0
  176. package/app/templates/projects/project.html +433 -0
  177. package/app/templates/reference-missing.html +14 -0
  178. package/app/templates/runs/run.html +166 -0
  179. package/app/templates/sca/card.html +476 -0
  180. package/app/templates/sca/index.html +321 -0
  181. package/app/templates/settings/hub_url.html +31 -0
  182. package/app/templates/settings/index.html +216 -0
  183. package/app/templates/settings/provider.html +229 -0
  184. package/app/templates/settings/providers.html +37 -0
  185. package/app/templates/worklists.html +52 -0
  186. package/app/textsafe.py +117 -0
  187. package/app/timing.py +245 -0
  188. package/app/triage.py +1743 -0
  189. package/app/view.py +430 -0
  190. package/app/worklists.py +204 -0
  191. package/examples/demo/demo-hub-report-v2.xlsx +0 -0
  192. package/examples/demo/demo-hub-report.xlsx +0 -0
  193. package/examples/demo/repos/billing-core/pom.xml +30 -0
  194. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/Invoice.java +9 -0
  195. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceRepository.java +51 -0
  196. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceStatus.java +11 -0
  197. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/config/DatabaseSettings.java +18 -0
  198. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/payment/PaymentTokenService.java +35 -0
  199. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/web/InvoiceExportController.java +57 -0
  200. package/examples/demo/repos/catalog-api/catalog_api/__init__.py +1 -0
  201. package/examples/demo/repos/catalog-api/catalog_api/products.py +24 -0
  202. package/examples/demo/repos/catalog-api/catalog_api/tasks.py +24 -0
  203. package/examples/demo/repos/catalog-api/catalog_api/views.py +17 -0
  204. package/examples/demo/repos/catalog-api/requirements.txt +3 -0
  205. package/npm/build.json +5 -0
  206. package/npm/cli.js +346 -0
  207. package/npm/files.manifest +224 -0
  208. package/npm/lib/binding.js +64 -0
  209. package/npm/lib/cluster.js +330 -0
  210. package/npm/lib/env.js +88 -0
  211. package/npm/lib/fsx.js +125 -0
  212. package/npm/lib/http.js +53 -0
  213. package/npm/lib/metrics.js +73 -0
  214. package/npm/lib/paths.js +150 -0
  215. package/npm/lib/pg.js +351 -0
  216. package/npm/lib/proc.js +101 -0
  217. package/npm/lib/python.js +133 -0
  218. package/npm/lib/stand.js +46 -0
  219. package/npm/lib/supervisor.js +1141 -0
  220. package/npm/lib/version.js +21 -0
  221. package/npm/requirements.txt +476 -0
  222. package/npm-shrinkwrap.json +111 -0
  223. package/package.json +37 -4
@@ -0,0 +1,363 @@
1
+ """HTML-карточка логического дефекта; физические операции остаются в hub_defect_routes."""
2
+
3
+ from difflib import unified_diff
4
+ from urllib.parse import urlencode
5
+
6
+ from fastapi import APIRouter, HTTPException, Request
7
+ from starlette.concurrency import run_in_threadpool
8
+
9
+ from app import defect_drafts, defect_fields, defect_form, defect_local_text, defect_references, defect_where, hub_defects
10
+ from app.db import dumps, loads
11
+ from app.routes.common import register_messages
12
+
13
+ register_messages({"number_released": "Номер снят с находок вне дефекта: «Push в Hub» больше не считает его занятым."})
14
+ from app.routes import hub_defect_routes as flow
15
+ from app.routes.common import db_of, project_or_404, redirect, render, settings_of
16
+ from app.routes.hub_status_routes import send_blocker
17
+ from app.view import DECISION_LABELS, VERDICT_LABELS
18
+
19
+ router = APIRouter()
20
+
21
+ # Статусы находок так, как их показывает интерфейс Hub (вкладка «Связанные уязвимости» в Hub, в приложении – «Связанные находки»)
22
+ HUB_STATUS_RU = {"To verify": "Не подтверждено", "Open": "Открыто", "Confirmed": "Подтверждено",
23
+ "False Positive": "Ложное срабатывание", "Accepted risk": "Риск принят", "Fixed": "Исправлено"}
24
+
25
+
26
+ _scan_date = defect_where.scan_date
27
+
28
+
29
+ def linked_rows(db, project_id: int, owner: dict, hub_obj: dict | None, targets: list[dict]) -> list[dict]:
30
+ """Состав дефекта для вкладки «Связанные находки»: связи из объекта Hub; до создания – находки состава."""
31
+ base = str(owner.get("hub_url") or "").rstrip("/")
32
+ app_id = owner.get("app_id")
33
+ rows = []
34
+ issues = (hub_obj or {}).get("linkedIssues") if isinstance(hub_obj, dict) else None
35
+ if isinstance(issues, list) and issues:
36
+ for item in issues:
37
+ if not isinstance(item, dict):
38
+ continue
39
+ hub_id, kind = str(item.get("id") or ""), str(item.get("type") or "")
40
+ scan = item.get("scanObject") if isinstance(item.get("scanObject"), dict) else {}
41
+ rows.append({"hub_id": hub_id, "type": kind, "source": str(item.get("source") or ""),
42
+ "status": HUB_STATUS_RU.get(str(item.get("status") or ""), str(item.get("status") or "")),
43
+ "scan_task": str(item.get("lastScanTaskId") or ""), "scan_date": _scan_date(item.get("lastScanTs")),
44
+ "scan_object": str(scan.get("name") or ""),
45
+ "url": flow._card_url_of(db, project_id, hub_id),
46
+ "hub_url": f"{base}/#/appprofile/{app_id}/issues/{kind}/{hub_id}" if base and app_id and kind else ""})
47
+ return rows
48
+ for t in targets:
49
+ rows.append({"hub_id": t["hub_id"], "type": owner.get("kind") or "", "source": "", "status": "",
50
+ "scan_task": "", "scan_date": "", "scan_object": "", "url": t.get("url") or "", "hub_url": "",
51
+ "decision": t.get("decision", "")})
52
+ return rows
53
+
54
+
55
+ CATALOG_KEYS = ("page", "q", "sort", "kind", "state", "origin", "page_size") # отборы вкладки «Дефекты»
56
+
57
+
58
+ def page_context(request, project_id, defect_id):
59
+ project = project_or_404(request, project_id)
60
+ db = db_of(request)
61
+ row = db.hub_defect(defect_id)
62
+ if row is None or row["project_id"] != project_id:
63
+ raise HTTPException(404, "Дефект не найден.")
64
+ family = db.on_connection(lambda c: defect_drafts.family_in(c, row))
65
+ for physical in family or [row]:
66
+ hub_defects.sync(db, physical, flow.update_preparer(request))
67
+ owner = db.on_connection(lambda c: defect_drafts.owner_in(c, row))
68
+ family = db.on_connection(lambda c: defect_drafts.family_in(c, owner))
69
+ defect_references.sync(db, project_id)
70
+ problem = db.on_connection(lambda c: defect_drafts.edit_problem(c, owner))
71
+ targets = {}
72
+ for physical in family:
73
+ for t in loads(physical["targets_json"], []):
74
+ hub_id = str(t.get("hub_id") or "")
75
+ review = db.get_review(project_id, hub_id) or {}
76
+ targets[(hub_id, t.get("issue_type"))] = {
77
+ "hub_id": hub_id, "url": flow._card_url_of(db, project_id, hub_id),
78
+ "decision": review.get("final_verdict") or review.get("decision") or "решение не сохранено",
79
+ "revision": review.get("revision", 0), "sent_revision": t.get("revision", 0),
80
+ }
81
+ settings = settings_of(request)
82
+ single = db.on_connection(lambda c: defect_drafts.family_single_in(c, owner))
83
+ can_read = (not send_blocker(settings, project)
84
+ and flow._same_hub(owner, settings.hub_url, project.get("hub_app_id")) and single)
85
+ sync_preview = bool(loads(owner["sync_json"], {}).get("read"))
86
+ upd = flow.update_context(db, owner, can_read, sync_preview)
87
+ if loads(owner["conflicts_json"], []):
88
+ upd["can_prepare"] = False
89
+ upd["can_put"] = False
90
+ decisions = defect_local_text.generate(request, owner) if single else {}
91
+ confirmed = loads(owner["confirmed_object_json"], None)
92
+ observed = loads(owner["import_json"], {})
93
+ base = hub_defects._read_of(confirmed) if confirmed else None
94
+ basis = defect_fields.basis_of(owner)
95
+ reference_rows = db._all("SELECT * FROM hub_defect_reference_loads WHERE project_id = ? AND hub_url = ?"
96
+ " AND app_id = ? ORDER BY id DESC", (project_id, owner["hub_url"], owner["app_id"]))
97
+ reference_rows = [r for r in reference_rows if r["state"] != "preview"
98
+ or loads(r["load_json"], {}).get("defect_id") == owner["id"]]
99
+ latest = next((r for r in reference_rows if r["state"] == "done"), None)
100
+ choices = loads(latest["load_json"], {}).get("projection", {}) if latest else {}
101
+ groups = db.on_connection(lambda c: defect_local_text.groups_in(c, owner)) if owner["kind"] == "SCA" else []
102
+ sync_seen = loads(owner["sync_json"], {}).get("read")
103
+ basis_seen = sync_seen or observed
104
+ draft = {"summary": owner["draft_summary"], "command_text": owner["draft_command_text"]}
105
+ comparisons = []
106
+ for title, before, after in [("Подтверждённая база → черновик", base, draft),
107
+ ("Черновик → текущие решения", draft, decisions if not decisions.get("refusals") else None),
108
+ ("Подтверждённая база → наблюдение Hub", base, observed)]:
109
+ if before is not None and after and "command_text" in after and not after.get("text_note"):
110
+ left = (before.get("summary", "") + "\n" + before.get("command_text", "")).splitlines()
111
+ right = (after.get("summary", "") + "\n" + after.get("command_text", "")).splitlines()
112
+ comparisons.append({"title": title, "diff": "\n".join(unified_diff(left, right, lineterm=""))})
113
+ catalog_query = {k: request.query_params[k] for k in CATALOG_KEYS if k in request.query_params}
114
+ # действия форм карточки несут и адрес возврата к списку: он переживает сохранение черновика (ревью dev28)
115
+ form_query = {k: request.query_params[k] for k in (*CATALOG_KEYS, "back") if k in request.query_params}
116
+ hub_obj = confirmed if isinstance(confirmed, dict) else (observed.get("object") if isinstance(observed, dict) else None)
117
+ # «Описание в Hub» – текстовая часть; служебный блок Hub показывается отдельно, очищенный до безопасной разметки
118
+ # (dev30): у дефекта в Hub – его блок, у ещё не созданного – блок заготовки
119
+ hub_block_html, hub_block_source = hub_defects.block_for_display(owner, hub_obj if isinstance(hub_obj, dict) else None)
120
+ # блок Hub выделен – «Описание в Hub» показывает текстовую часть; иначе (блок склеен с текстом или его нет) – все
121
+ # строки описания Hub как есть (ревью dev30, круг 2)
122
+ hub_lines = ((hub_defects.split_description(hub_obj.get("description"))[0].splitlines()
123
+ if hub_block_source == "hub" else hub_defects.description_lines(hub_obj.get("description")))
124
+ if isinstance(hub_obj, dict) else [])
125
+ # SCA: текст и «Push в Hub» берутся из «Дефекта по шаблону команды» в карточке опорной находки –
126
+ # при отказе карточка дефекта ведёт туда, где ставятся отметки и сохраняется объяснение
127
+ sca_anchor = None
128
+ if owner["kind"] == "SCA":
129
+ hub_ids = [t["hub_id"] for t in targets.values()]
130
+ anchor = str(owner.get("anchor_hub_id") or "")
131
+ anchor = anchor if anchor in hub_ids else (hub_ids[0] if hub_ids else "")
132
+ url = flow._card_url_of(db, project_id, anchor) if anchor else ""
133
+ sca_anchor = {"hub_id": anchor, "url": url + "#sca-set-title"} if url else None
134
+ from app import worklists
135
+ # «К списку» – туда, откуда пришли (back из заготовки: список SCA или общий список находок, по строгому образцу
136
+ # пути, как у карточки SCA), иначе к списку своего вида (ревью dev28)
137
+ back_param = str(request.query_params.get("back") or "")[:2000]
138
+ labels = {f"/projects/{project_id}/findings": "К списку находок"}
139
+ if owner["kind"] == "SCA":
140
+ labels[f"/projects/{project_id}/sca"] = "К списку SCA"
141
+ back_path = back_param.split("?", 1)[0].split("#", 1)[0]
142
+ back_fallback = back_path if back_path in labels else (
143
+ f"/projects/{project_id}/sca" if owner["kind"] == "SCA" else f"/projects/{project_id}/findings")
144
+ back_url = worklists.list_anchor(worklists.return_url(request, back_fallback))
145
+ return {"project": project, "row": owner, "family": family, "targets": list(targets.values()),
146
+ "unmerged": db.on_connection(lambda c: hub_defects.family_unmerged_in(c, owner)),
147
+ "back_url": back_url, "back_label": labels[back_fallback], "back_param": back_param,
148
+ "linked": linked_rows(db, project_id, owner, hub_obj, list(targets.values())),
149
+ "hub_lines": hub_lines, "hub_block_html": hub_block_html, "hub_block_source": hub_block_source,
150
+ "dropped": db.dropped_findings(project_id, int(owner["id"])),
151
+ "foreign_keys": hub_defects.foreign_number_keys(db, owner) if owner.get("hub_defect_id") else [],
152
+ "number_releases": db.on_connection(lambda c: hub_defects.number_releases_in(c, owner)),
153
+ "sca_anchor": sca_anchor,
154
+ "catalog_url": f"/projects/{project_id}/defects" + ("?" + urlencode(catalog_query) if catalog_query else ""),
155
+ "catalog_qs": "?" + urlencode(form_query) if form_query else "",
156
+ "problem": problem, "local_edit_problem": problem,
157
+ # «Push в Hub» – главная кнопка только при неотправленной правке; основа полей неизвестна – Push всё равно откажет
158
+ "push_main": bool(basis["known"] and defect_fields.unsent_edit(owner)),
159
+ "draft_unsent": defect_drafts.local_edit(owner)["edited"],
160
+ "update_problem": db.on_connection(lambda c: hub_defects._update_idle_problem(c, owner)),
161
+ "view": hub_defects.view(owner), "upd": upd, "retry": flow.retry_context(db, project_id, owner),
162
+ "create_preview": hub_defects.preview(db, owner, lambda h: flow._card_url_of(db, project_id, h)),
163
+ "confirmation_rows": [{"row": physical, "view": hub_defects.view(physical)} for physical in family
164
+ if hub_defects.view(physical).get("diff") or hub_defects.view(physical).get("verify")],
165
+ "imp": flow.import_context(db, settings, project, owner) or {"hub_update": upd},
166
+ "draft_summary": owner["draft_summary"], "draft_command_text": owner["draft_command_text"],
167
+ "confirmed": confirmed, "comparisons": comparisons,
168
+ "draft_fields": loads(owner["draft_fields_json"], {}),
169
+ "basis": basis, "basis_seen": basis_seen, "basis_source": "sync" if sync_seen else "observation",
170
+ "basis_shown": defect_references.signature(basis_seen),
171
+ "controls": defect_form.controls(loads(owner["draft_fields_json"], {}), basis, choices),
172
+ "form_values": {}, "reference_load": latest["id"] if latest else "", "reference_rows": reference_rows,
173
+ "reference_latest": latest, "can_read": can_read,
174
+ "reference_labels": {"preview": "ожидает подтверждения", "loading": "загружается", "done": "получена",
175
+ "failed": "ошибка", "cancelled": "отменена"},
176
+ "conflict_groups": groups, "conflict_explanation": defect_local_text.explanation(groups),
177
+ "observed": loads(owner["import_json"], {}), "attempt": hub_defects.update_state(owner),
178
+ "conflicts": loads(owner["conflicts_json"], []),
179
+ "decisions": decisions,
180
+ "history": db._all("SELECT * FROM hub_defect_history WHERE defect_id = ? ORDER BY id DESC", (owner["id"],)),
181
+ "state_labels": hub_defects.STATE_LABELS,
182
+ "decision_labels": {**VERDICT_LABELS, **DECISION_LABELS},
183
+ "history_labels": {"migration": "обновление схемы", "create": "создание черновика",
184
+ "edit": "правка черновика", "hub_confirm": "подтверждение в Hub",
185
+ "hub_sync": "принятие версии Hub"},
186
+ "defect_card": True, "error": ""}
187
+
188
+
189
+ @router.get("/projects/{project_id}/defects/{defect_id}")
190
+ def card(request: Request, project_id: int, defect_id: int):
191
+ return render(request, "projects/defect_card.html", page_context(request, project_id, defect_id))
192
+
193
+
194
+ async def save(request: Request, project_id: int, defect_id: int, generate: bool):
195
+ form = await request.form(max_fields=1000, max_files=0)
196
+ values = {"draft_summary": str(form.get("summary") or ""), "draft_command_text": str(form.get("command_text") or "")}
197
+
198
+ def apply():
199
+ project_or_404(request, project_id)
200
+ db = db_of(request)
201
+ row = db.hub_defect(defect_id)
202
+ if row is None or row["project_id"] != project_id:
203
+ raise HTTPException(404, "Дефект не найден.")
204
+ owner = db.on_connection(lambda c: defect_drafts.owner_in(c, row))
205
+ ref_id = str(form.get("reference_load") or "")
206
+ if ref_id and not ref_id.isdigit():
207
+ raise defect_fields.FieldError("Неверный идентификатор снимка справочников.")
208
+ choices, _ = db.on_connection(lambda c: defect_references.choices_in(c, owner, int(ref_id) if ref_id else None))
209
+ operations = defect_form.parse(form, loads(owner["draft_fields_json"], {}), choices) if not generate else None
210
+ return defect_drafts.save(db, row, str(form.get("draft_revision") or ""),
211
+ summary=values["draft_summary"], command=values["draft_command_text"],
212
+ generate=(lambda owner: defect_local_text.generate(request, owner)) if generate else None,
213
+ operations=operations, reference_load=int(ref_id) if ref_id else None)
214
+
215
+ try:
216
+ owner = await run_in_threadpool(apply)
217
+ except ValueError as exc:
218
+ context = await run_in_threadpool(page_context, request, project_id, defect_id)
219
+ # отказ сборки, который карточка и так показывает с подсказкой, второй раз не выводится
220
+ shown = "; ".join((context.get("decisions") or {}).get("refusals") or [])
221
+ context.update(error="" if generate and str(exc) == shown else str(exc))
222
+ if not generate:
223
+ context.update(values, form_values=dict(form), bug_order=form.getlist("bug_order"))
224
+ # При отказе старой формы показываем варианты именно её загрузки, а не более новой из другой вкладки.
225
+ selected = next((r for r in context["reference_rows"] if str(r["id"]) == str(form.get("reference_load"))
226
+ and r["state"] == "done"), None)
227
+ if selected:
228
+ choices = loads(selected["load_json"], {}).get("projection", {})
229
+ context.update(reference_latest=selected,
230
+ controls=defect_form.controls(context["draft_fields"], context["basis"], choices))
231
+ return render(request, "projects/defect_card.html", context,
232
+ status_code=422 if isinstance(exc, defect_fields.FieldError) else 409)
233
+ # отборы каталога (page, q, sort, kind, state, origin, page_size) – дальше в карточку, для «Дефекты» в цепочке
234
+ keep = {k: request.query_params[k] for k in (*CATALOG_KEYS, "back") if k in request.query_params}
235
+ return redirect(f"/projects/{project_id}/defects/{owner['id']}" + ("?" + urlencode(keep) if keep else ""))
236
+
237
+
238
+ @router.post("/projects/{project_id}/defects/{defect_id}/fields")
239
+ async def fields(request: Request, project_id: int, defect_id: int):
240
+ return await save(request, project_id, defect_id, False)
241
+
242
+
243
+ @router.post("/projects/{project_id}/defects/{defect_id}/text-from-decisions")
244
+ async def from_decisions(request: Request, project_id: int, defect_id: int):
245
+ return await save(request, project_id, defect_id, True)
246
+
247
+
248
+ @router.post("/projects/{project_id}/defects/{defect_id}/basis")
249
+ async def use_basis(request: Request, project_id: int, defect_id: int):
250
+ form = await request.form(max_fields=4, max_files=0)
251
+ context = await run_in_threadpool(page_context, request, project_id, defect_id)
252
+ try:
253
+ await run_in_threadpool(defect_drafts.use_basis, db_of(request), context["row"], form.get("draft_revision"),
254
+ form.get("source"), form.get("shown"))
255
+ except ValueError as exc:
256
+ context["error"] = str(exc)
257
+ return render(request, "projects/defect_card.html", context, status_code=409)
258
+ keep = {k: request.query_params[k] for k in (*CATALOG_KEYS, "back") if k in request.query_params}
259
+ return redirect(f"/projects/{project_id}/defects/{context['row']['id']}" + ("?" + urlencode(keep) if keep else ""))
260
+
261
+
262
+ @router.post("/projects/{project_id}/defects/{defect_id}/release-number")
263
+ async def release_number(request: Request, project_id: int, defect_id: int):
264
+ """«Снять номер ID<n> с находок вне дефекта»: номер дефекта остался за ключами находок,
265
+ которых в его составе больше нет. Снимается только показанное (keys), в одной транзакции и с теми же проверками:
266
+ номер тот же, ключ не свой, не числится за другой записью, тот же номер не резервирует другая запись."""
267
+ form = await request.form(max_fields=40, max_files=0)
268
+ context = await run_in_threadpool(page_context, request, project_id, defect_id)
269
+ row = context["row"]
270
+ keys, stamps = [str(k) for k in form.getlist("key")], [str(a) for a in form.getlist("assigned_at")]
271
+ if len(keys) != len(stamps):
272
+ raise HTTPException(400, "Форма снятия номера неполная: обновите страницу.")
273
+ shown = dict(zip(keys, stamps, strict=True))
274
+
275
+ def apply():
276
+ db = db_of(request)
277
+ with db._tx() as c:
278
+ current = dict(c.execute("SELECT * FROM hub_defects WHERE id = ?", (int(row["id"]),)).fetchone())
279
+ if str(current.get("number")) != str(form.get("number") or "") or not shown:
280
+ raise ValueError("Номер дефекта изменился: обновите страницу.")
281
+ if str(hub_defects.number_releases_in(c, current)) != str(form.get("releases") or ""):
282
+ raise ValueError("Номер уже снимали с этой страницы: обновите страницу.")
283
+ for key, stamp in shown.items(): # то же назначение, что показано: повтор старой формы новый номер не снимет
284
+ have = c.execute("SELECT assigned_at FROM defects WHERE project_id = ? AND defect_key = ?",
285
+ (project_id, key)).fetchone()
286
+ if have is None or str(have["assigned_at"]) != stamp:
287
+ raise ValueError("Номер у этих находок выдан заново или уже снят: обновите страницу.")
288
+ own = hub_defects.own_number_keys_in(c, current, hub_defects.family_targets_in(c, current))
289
+ released = hub_defects.release_number_in(c, current, current["number"], shown, own)
290
+ if sorted(released) != sorted(set(shown)):
291
+ raise ValueError("Часть номеров снять нельзя: ключ стал своим, его держит другая запись или номер "
292
+ "сменился. Обновите страницу.")
293
+ # снятый ключ уходит и из ключей номера семьи: отложенное последствие подтверждения не вернёт номер
294
+ owner_id = int(current.get("draft_owner_id") or current["id"])
295
+ for member in c.execute("SELECT id, number_keys_json FROM hub_defects WHERE COALESCE(draft_owner_id, id) = ?",
296
+ (owner_id,)).fetchall():
297
+ keys = loads(member["number_keys_json"], [])
298
+ if set(keys) & set(released):
299
+ c.execute("UPDATE hub_defects SET number_keys_json = ? WHERE id = ?",
300
+ (dumps([k for k in keys if k not in released]), member["id"]))
301
+ defect_drafts.history(c, defect_drafts.owner_in(c, current), "edit",
302
+ details={"released_number": current["number"], "keys": released})
303
+
304
+ try:
305
+ await run_in_threadpool(apply)
306
+ except ValueError as exc:
307
+ context = await run_in_threadpool(page_context, request, project_id, defect_id)
308
+ context["error"] = str(exc)
309
+ return render(request, "projects/defect_card.html", context, status_code=409)
310
+ return redirect(flow._card_url(project_id, row["id"], await request.form(), ok="number_released"))
311
+
312
+
313
+ @router.post("/projects/{project_id}/defects/{defect_id}/references/prepare")
314
+ def references_prepare(request: Request, project_id: int, defect_id: int):
315
+ context = page_context(request, project_id, defect_id)
316
+ if not context["can_read"]:
317
+ raise HTTPException(409, "Загрузка для текущего Hub и приложения недоступна.")
318
+ row, settings = context["row"], settings_of(request)
319
+ try:
320
+ load_id = defect_references.prepare(db_of(request), row, settings.hub_url, context["project"]["hub_app_id"],
321
+ flow._update_target(request, project_id, row))
322
+ except ValueError as exc:
323
+ raise HTTPException(409, str(exc)) from exc
324
+ return redirect(f"/projects/{project_id}/defects/{row['id']}/references/{load_id}")
325
+
326
+
327
+ @router.get("/projects/{project_id}/defects/{defect_id}/references/{load_id}")
328
+ def references_state(request: Request, project_id: int, defect_id: int, load_id: int):
329
+ context = page_context(request, project_id, defect_id)
330
+ row = db_of(request)._one("SELECT * FROM hub_defect_reference_loads WHERE id = ? AND project_id = ?",
331
+ (load_id, project_id))
332
+ if (row is None or row["hub_url"] != context["row"]["hub_url"] or row["app_id"] != context["row"]["app_id"]
333
+ or row["state"] == "preview" and loads(row["load_json"], {}).get("defect_id") != context["row"]["id"]):
334
+ raise HTTPException(404, "Загрузка не найдена.")
335
+ context.update(reference=row, plan=loads(row["load_json"], {}), shown=defect_references.signature(loads(row["load_json"], {})))
336
+ return render(request, "projects/defect_references.html", context)
337
+
338
+
339
+ @router.post("/projects/{project_id}/defects/{defect_id}/references/load")
340
+ async def references_load(request: Request, project_id: int, defect_id: int):
341
+ form = await request.form(max_fields=4, max_files=0)
342
+ context = await run_in_threadpool(page_context, request, project_id, defect_id)
343
+ row, db = context["row"], db_of(request)
344
+ try:
345
+ load_id = int(str(form.get("load_id") or ""))
346
+ if form.get("action") == "cancel":
347
+ with db._tx() as c:
348
+ found = c.execute("SELECT * FROM hub_defect_reference_loads WHERE id = ? AND project_id = ?",
349
+ (load_id, project_id)).fetchone()
350
+ plan = loads(found["load_json"], {}) if found else {}
351
+ if (not found or found["state"] != "preview" or plan.get("defect_id") != row["id"]
352
+ or defect_references.signature(plan) != form.get("shown")):
353
+ raise ValueError("Предпросмотр изменился.")
354
+ c.execute("UPDATE hub_defect_reference_loads SET state = 'cancelled' WHERE id = ?", (load_id,))
355
+ else:
356
+ if not context["can_read"] or form.get("action") != "confirm":
357
+ raise ValueError("Подтверждение загрузки недоступно.")
358
+ await run_in_threadpool(defect_references.load, db, row, load_id, form.get("shown"),
359
+ settings_of(request).hub_url, context["project"]["hub_app_id"],
360
+ flow._update_target(request, project_id, row))
361
+ except ValueError as exc:
362
+ raise HTTPException(409, str(exc)) from exc
363
+ return redirect(f"/projects/{project_id}/defects/{row['id']}/references/{load_id}")