feat: support rejected application status

This commit is contained in:
nyan404 committed 2026-08-25 15:15:48 +03:00
1 parent 08ec58c7e9
commit cd33a382c0
5 files changed
+45 -13

No files matched your search

+12 -5
View File
@@ -227,7 +227,7 @@ class ApplicationStore:
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]: 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("Неизвестный статус заявки") raise ApplicationError("Неизвестный статус заявки")
limit = max(1, min(int(limit), 500)) limit = max(1, min(int(limit), 500))
if self.database_url.startswith(("postgres://", "postgresql://")): if self.database_url.startswith(("postgres://", "postgresql://")):
@@ -253,26 +253,33 @@ class ApplicationStore:
def accept(self, application_id: int) -> dict[str, Any] | None: def accept(self, application_id: int) -> dict[str, Any] | None:
"""Атомарно переводит заявку в accepted и возвращает её снимок.""" """Атомарно переводит заявку в accepted и возвращает её снимок."""
return self.review(application_id, status="accepted")
def review(self, application_id: int, *, status: str) -> dict[str, Any] | None:
"""Атомарно присваивает новой заявке итоговый статус рассмотрения."""
if application_id <= 0: if application_id <= 0:
raise ApplicationError("ID заявки должен быть положительным") raise ApplicationError("ID заявки должен быть положительным")
if status not in ("accepted", "rejected"):
raise ApplicationError("Некорректный статус рассмотрения")
if self.database_url.startswith(("postgres://", "postgresql://")): if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection: 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' 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: else:
with sqlite3.connect(self.sqlite_path) as connection: 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: if not cursor.rowcount:
return None return None
application = next((item for item in self.list(limit=500) if item["id"] == application_id), 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) self.enqueue_export(application_id, "application_accepted", application)
return application return application
if row is None: if row is None:
return None return None
application = {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], 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()} "application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()}
if status == "accepted":
self.enqueue_export(application_id, "application_accepted", application) self.enqueue_export(application_id, "application_accepted", application)
return application return application
+9 -5
View File
@@ -464,23 +464,27 @@ class Handler(BaseHTTPRequestHandler):
self._json(200, {"deleted": calculation_id}) self._json(200, {"deleted": calculation_id})
def do_PATCH(self) -> None: # noqa: N802 def do_PATCH(self) -> None: # noqa: N802
"""Принимает заявку и запускает уведомление через PATCH API.""" """Меняет статус новой заявки через PATCH API."""
parsed = urlparse(self.path) parsed = urlparse(self.path)
prefix = "/api/admin/applications/" 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": "Не найдено"}) self._json(404, {"error": "Не найдено"})
return return
if not self._admin_authorized(): if not self._admin_authorized():
return 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: 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: except (ValueError, ApplicationError) as exc:
self._json(400, {"error": str(exc)}) self._json(400, {"error": str(exc)})
return return
if application is None: if application is None:
self._json(404, {"error": "Заявка не найдена или уже принята"}) self._json(404, {"error": "Заявка не найдена или уже рассмотрена"})
return return
if application["status"] == "accepted":
sync_application_exports() sync_application_exports()
self._json(200, {"item": application}) self._json(200, {"item": application})
@@ -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. **Фактическое поведение:** после применения манифестов `kubectl rollout status deployment/belki-postgres` превышает progress deadline, хотя обновлённые `belki-web`, `belki-bot` и `cwshed` успешно выкатываются. Job завершается с exit code 1.
**Исправление:** CI проверяет готовность pod PostgreSQL, не требуя несуществующего rollout базы; rollout status остаётся для обновляемых deployment приложений. **Исправление:** CI проверяет готовность pod PostgreSQL, не требуя несуществующего rollout базы; rollout status остаётся для обновляемых deployment приложений.
## 16. Админка заявок: слипшиеся действия и нет отклонения
**Статус:** выполнено в текущей очереди исправлений.
**Источник:** сообщение пользователя со скриншотами от 25.08.2026.
**Исправление:** добавлен отступ между скриншотами и действиями; новая заявка может быть принята или отклонена. Заявка сохраняется и отображается в одном из статусов: новая, принята или отклонена.
+13
View File
@@ -93,6 +93,19 @@ class ApplicationTests(unittest.TestCase):
self.assertEqual(exporter.sync_pending(), 0) self.assertEqual(exporter.sync_pending(), 0)
self.assertEqual(len(store.pending_exports()), 2) 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: def test_google_export_refuses_an_insecure_endpoint_even_when_enabled(self) -> None:
with tempfile.TemporaryDirectory() as directory: with tempfile.TemporaryDirectory() as directory:
store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3") store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3")
+3 -3
View File
@@ -59,7 +59,7 @@
.admin-section { padding-top: 28px; } .admin-section { padding-top: 28px; }
.applications { padding-top: 4px; } .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-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 { 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; } dialog::backdrop { background: #211b1877; }
.gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; } .gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; }
@@ -112,7 +112,7 @@
<p class="error" id="error" role="alert"></p> <p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div> <div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
</section> </section>
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button></nav><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section> <section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="rejected" aria-selected="false">Отклонённые</button></nav><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
</section> </section>
</main> </main>
@@ -179,7 +179,7 @@
// Extracts display fields from one application for the detail panel. // 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; } 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. // 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. // 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; } } 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. // Opens the authenticated admin view and starts both data loaders.