diff --git a/app/belki/applications.py b/app/belki/applications.py index e5c1f16..966d036 100644 --- a/app/belki/applications.py +++ b/app/belki/applications.py @@ -227,7 +227,7 @@ class ApplicationStore: def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]: """Возвращает заявки, ограничивая выборку и опционально фильтруя статус.""" - if status not in (None, "pending", "accepted"): + if status not in (None, "pending", "accepted", "rejected"): raise ApplicationError("Неизвестный статус заявки") limit = max(1, min(int(limit), 500)) if self.database_url.startswith(("postgres://", "postgresql://")): @@ -253,27 +253,34 @@ class ApplicationStore: def accept(self, application_id: int) -> dict[str, Any] | None: """Атомарно переводит заявку в accepted и возвращает её снимок.""" + return self.review(application_id, status="accepted") + + def review(self, application_id: int, *, status: str) -> dict[str, Any] | None: + """Атомарно присваивает новой заявке итоговый статус рассмотрения.""" if application_id <= 0: raise ApplicationError("ID заявки должен быть положительным") + if status not in ("accepted", "rejected"): + raise ApplicationError("Некорректный статус рассмотрения") if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: - row = connection.execute("""UPDATE belki_applications SET status = 'accepted', reviewed_at = NOW() + row = connection.execute("""UPDATE belki_applications SET status = %s, reviewed_at = NOW() WHERE id = %s AND status = 'pending' - RETURNING id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at""", (application_id,)).fetchone() + RETURNING id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at""", (status, application_id)).fetchone() else: with sqlite3.connect(self.sqlite_path) as connection: - cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,)) + cursor = connection.execute("UPDATE applications SET status = ?, reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (status, application_id)) if not cursor.rowcount: return None application = next((item for item in self.list(limit=500) if item["id"] == application_id), None) - if application: + if application and status == "accepted": self.enqueue_export(application_id, "application_accepted", application) return application if row is None: return None application = {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], "application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()} - self.enqueue_export(application_id, "application_accepted", application) + if status == "accepted": + self.enqueue_export(application_id, "application_accepted", application) return application def enqueue_export(self, application_id: int, event_type: str, snapshot: dict[str, Any]) -> int: diff --git a/app/main.py b/app/main.py index 5f19f71..62c3ca3 100644 --- a/app/main.py +++ b/app/main.py @@ -464,24 +464,28 @@ class Handler(BaseHTTPRequestHandler): self._json(200, {"deleted": calculation_id}) def do_PATCH(self) -> None: # noqa: N802 - """Принимает заявку и запускает уведомление через PATCH API.""" + """Меняет статус новой заявки через PATCH API.""" parsed = urlparse(self.path) prefix = "/api/admin/applications/" - if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"): + if not parsed.path.startswith(prefix): self._json(404, {"error": "Не найдено"}) return if not self._admin_authorized(): return - raw_id = parsed.path[len(prefix):-len("/accept")].strip("/") + raw_id, separator, action = parsed.path[len(prefix):].strip("/").partition("/") + if not separator or action not in {"accept", "reject"}: + self._json(404, {"error": "Не найдено"}) + return try: - application = application_store().accept(int(raw_id)) + application = application_store().review(int(raw_id), status="accepted" if action == "accept" else "rejected") except (ValueError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) return if application is None: - self._json(404, {"error": "Заявка не найдена или уже принята"}) + self._json(404, {"error": "Заявка не найдена или уже рассмотрена"}) return - sync_application_exports() + if application["status"] == "accepted": + sync_application_exports() self._json(200, {"item": application}) def log_message(self, format: str, *args: object) -> None: diff --git a/docs/staging/bugs/2026-08-25-belki-bugs.md b/docs/staging/bugs/2026-08-25-belki-bugs.md index 063f76a..cd379f5 100644 --- a/docs/staging/bugs/2026-08-25-belki-bugs.md +++ b/docs/staging/bugs/2026-08-25-belki-bugs.md @@ -310,3 +310,11 @@ Proudly made by Nyan404 | GitLab Page **Фактическое поведение:** после применения манифестов `kubectl rollout status deployment/belki-postgres` превышает progress deadline, хотя обновлённые `belki-web`, `belki-bot` и `cwshed` успешно выкатываются. Job завершается с exit code 1. **Исправление:** CI проверяет готовность pod PostgreSQL, не требуя несуществующего rollout базы; rollout status остаётся для обновляемых deployment приложений. + +## 16. Админка заявок: слипшиеся действия и нет отклонения + +**Статус:** выполнено в текущей очереди исправлений. + +**Источник:** сообщение пользователя со скриншотами от 25.08.2026. + +**Исправление:** добавлен отступ между скриншотами и действиями; новая заявка может быть принята или отклонена. Заявка сохраняется и отображается в одном из статусов: новая, принята или отклонена. diff --git a/tests/test_applications.py b/tests/test_applications.py index eef1ac1..3d4851c 100644 --- a/tests/test_applications.py +++ b/tests/test_applications.py @@ -93,6 +93,19 @@ class ApplicationTests(unittest.TestCase): self.assertEqual(exporter.sync_pending(), 0) self.assertEqual(len(store.pending_exports()), 2) + def test_rejected_application_is_retained_without_acceptance_side_effects(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3") + application_id = store.create(application=validate_application({ + "type": "feather_donation", "name": "Белка", "character_id": 58775, + "feathers": [{"amount": 1, "color": "красное", "source": "личные запасы"}], + }), actor_id=10, reply_peer_id=10, source="vk") + rejected = store.review(application_id, status="rejected") + self.assertEqual(rejected["status"], "rejected") + self.assertEqual(store.list(status="rejected")[0]["id"], application_id) + self.assertEqual(store.pending_notifications(), []) + self.assertEqual([event["event_type"] for event in store.pending_exports()], ["application_created"]) + def test_google_export_refuses_an_insecure_endpoint_even_when_enabled(self) -> None: with tempfile.TemporaryDirectory() as directory: store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3") diff --git a/web/admin.html b/web/admin.html index 9e9fcec..75b7970 100644 --- a/web/admin.html +++ b/web/admin.html @@ -59,7 +59,7 @@ .admin-section { padding-top: 28px; } .applications { padding-top: 4px; } .application-layout { display: grid; grid-template-columns: minmax(260px, .8fr) minmax(380px, 1.2fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; background: var(--paper); } - .application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-selected="true"] { background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; }.application-detail .photos button { width:120px; height:90px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; } + .application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-selected="true"] { background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; margin:0 0 18px; }.application-detail .photos button { width:120px; height:90px; }.application-actions { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; }.reject { border-color:#a23d35; background:transparent; color:#8e3630; }.reject:hover { background:#fff1ef; } dialog { width: min(900px, calc(100% - 32px)); padding: 0; border: 1px solid #5a524b; border-radius: 10px; background: #24211f; color: #fffdfa; box-shadow: 0 24px 80px #211b18aa; } dialog::backdrop { background: #211b1877; } .gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; } @@ -112,7 +112,7 @@
КотКотятаФотоДатаСообщениеАвторID
Загрузка истории…
- + @@ -179,7 +179,7 @@ // Extracts display fields from one application for the detail panel. function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; } // Renders pending or accepted applications and their actions. - function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH'});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} } + function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${({pending:'новых', accepted:'принятых', rejected:'отклонённых'}[activeApplicationStatus])} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const actions=document.createElement('div');actions.className='application-actions';const review=async(action,button)=>{button.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/${action}`,{method:'PATCH'}),data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось изменить статус заявки');await loadApplications()}catch(err){error.textContent=err.message;button.disabled=false}};const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=()=>review('accept',accept);const reject=document.createElement('button');reject.className='reject';reject.type='button';reject.textContent='Отклонить';reject.onclick=()=>review('reject',reject);actions.append(accept,reject);detail.append(actions)} } // Loads applications from the admin API and renders the selected status. async function loadApplications() { try { const response=await fetch('/api/admin/applications'), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } } // Opens the authenticated admin view and starts both data loaders.