From 6235368baf5e83a7d1351c7602410468f9bbf030 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Mon, 21 Sep 2026 22:31:28 +0300 Subject: [PATCH] feat(admin): show inspection score breakdown --- app/belki/domain.py | 10 +++++----- tests/test_belki.py | 9 +++++++++ web/admin.html | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/app/belki/domain.py b/app/belki/domain.py index 3506efb..6cc0d67 100644 --- a/app/belki/domain.py +++ b/app/belki/domain.py @@ -298,8 +298,8 @@ def _inspection_resource_value(name: str) -> int: - Дичь = 1 балл - Любая разновидность змеи = 1 балл - Паук/паутинная нить = 7 баллов - - Водяной мох = 2 балла - - Обычный мох = 3 балла + - Водяной/наполненный водой мох = 2 балла + - Мох (обычный, в том числе без уточнения) = 3 балла - Остальные = 1 балл """ normalized = " ".join(name.casefold().replace("ё", "е").split()) @@ -314,10 +314,10 @@ def _inspection_resource_value(name: str) -> int: return 1 if "паутин" in letters or "паутн" in letters: return 7 - if "обычн" in normalized and "мох" in normalized: - return 3 - if "водян" in normalized and "мох" in normalized: + if "мох" in normalized and ("водян" in normalized or "наполнен" in normalized and "вод" in normalized): return 2 + if "мох" in normalized: + return 3 return 1 diff --git a/tests/test_belki.py b/tests/test_belki.py index 7e76152..7578672 100644 --- a/tests/test_belki.py +++ b/tests/test_belki.py @@ -267,6 +267,15 @@ class ReportTests(unittest.TestCase): ) self.assertEqual(calculate_inspection(report).points, 7 + 3 + 2 + 1 + 1 + 1 + 1 + 1 + 1 + 1) + def test_inspection_resource_aliases_cover_plain_and_water_filled_moss(self): + report = InspectionReport( + "Белка", 1, "дупло", 0, + (("мох", 1), ("наполненный водой мох", 2)), + ) + result = calculate_inspection(report) + self.assertEqual(result.points, 7) + self.assertEqual([item["points"] for item in result.resource_points], [3, 4]) + if __name__ == "__main__": unittest.main() diff --git a/web/admin.html b/web/admin.html index 2f6824f..b61ed97 100644 --- a/web/admin.html +++ b/web/admin.html @@ -217,7 +217,7 @@ function filteredItems() { return items.sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); } // Rebuilds cat and kitten filter options from loaded records. function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; } - function pointsCell(item) { const cell = document.createElement('td'); cell.className = 'points-cell'; const result = item.result || {}; if (item.mode !== 'inspection' || result.points === undefined) { cell.textContent = '—'; return cell; } const details = document.createElement('div'); details.className = 'points-details'; if (result.inspection_points !== undefined) { const base = document.createElement('span'); base.textContent = `Осмотры: ${result.inspection_points}`; details.append(base); } (result.resource_points || []).forEach(resource => { const line = document.createElement('span'); const name = resource.name || resource[0] || 'Ресурс'; const amount = resource.amount ?? resource[1] ?? 0; const points = resource.points ?? resource[2] ?? 0; line.textContent = `${amount > 0 ? '+' : ''}${amount} ${name}: ${points}`; details.append(line); }); const total = document.createElement('strong'); total.textContent = `Итого: ${result.points}`; details.append(total); cell.append(details); return cell; } + function pointsCell(item) { const cell = document.createElement('td'); cell.className = 'points-cell'; const result = item.result || {}; if (item.mode !== 'inspection' || result.points === undefined) { cell.textContent = '—'; return cell; } const details = document.createElement('div'); details.className = 'points-details'; const grouped = new Map(); (result.resource_points || []).forEach(resource => { const name = resource.name || resource[0] || 'Ресурс'; const amount = Number(resource.amount ?? resource[1] ?? 0); const points = Number(resource.points ?? resource[2] ?? 0); const key = name.trim().replace(/\s+/g, ' ').toLocaleLowerCase('ru-RU'); const current = grouped.get(key) || {name, amount: 0, points: 0}; current.amount += amount; current.points += points; grouped.set(key, current); }); const resourceTotal = [...grouped.values()].reduce((sum, resource) => sum + resource.points, 0); const resourceHeader = document.createElement('strong'); resourceHeader.textContent = `Итого по ресурсам: ${resourceTotal}`; details.append(resourceHeader); grouped.forEach(resource => { const perItem = resource.amount ? resource.points / resource.amount : 0; const line = document.createElement('span'); line.textContent = `${resource.name} ×${resource.amount}: ${resource.points} (по ${perItem} за ед.)`; details.append(line); }); if (result.inspection_points !== undefined) { const base = document.createElement('span'); base.textContent = `Баллы осмотра: ${result.inspection_points}`; details.append(base); } const total = document.createElement('strong'); total.textContent = `Всего: ${result.points}`; details.append(total); cell.append(details); return cell; } // Re-renders the report table, including empty and filtered states. function render() { syncReportsExport(); rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 9; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = displayDate(item.created_at); return cell; })(), pointsCell(item)); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); } async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = queryFor(reportPeriod, reportDateFrom, reportDateTo, {sort: 'escort_name', direction: 'asc', limit: '500', category: activeCategory, cat: catFilter.value, kitten: kittenFilter.value}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }