Files
sasheg 47c7f17c90 RPU v2, promo/bank система, админка, оптимизации
— RPU v2: бюджет удачи, потолок (ceiling), комбек после
  проигрышей, hot/cold анализ, интеграция с promo-фазами
— Bank API: mock-банк для карты (депозит/вывод с балансом 1000₽)
— Promo-сервис: автогенерация промокодов каждый час, типы
  (card_to_site, luck_boost, ceiling_boost, free_case, reset_streak)
— Promo-фазы: LUCKY/NEUTRAL/UNLUCKY, переключение каждые 1-6ч
— Admin: история транзакций (user_history), управление промокодами,
  управление promo-фазами, API фильтров/коллекций, RPU info
— Database: WAL mode, новые поля RPU v2, TransactionLog,
  карточный баланс, статистики (streaks, ceiling, budget)
— Frontend: /deposit, /promo/activate, /withdraw, /card-balance,
  /online-count, /rpu-info, lifespan вместо startup event
— UI: user_history.html, улучшения профиля, кейсов, навигации
— Cases: обновление cases.json (1892 строки новых данных)
— Achievements: кэш коллекций, оптимизация is_custom проверок
— Sounds: дополнительные звуковые эффекты
— Upgrade: интеграция с RPU (множители, streaks)
— .gitignore: исключены .db, .bak, __pycache__
2026-07-25 13:11:08 +00:00

535 lines
26 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{% extends "admin/base.html" %}
{% block title %}Кейсы — Админ-панель{% endblock %}
{% block nav_cases %}active{% endblock %}
{% block page_title %}📦 Управление кейсами{% endblock %}
{% block top_actions %}
<button class="a-btn a-btn-primary" onclick="openCreateCaseModal()"> Создать кейс</button>
{% endblock %}
{% block content %}
<div class="a-card">
<div class="a-card-header">📂 Секции главной страницы</div>
<div id="mainpageSections">
{% for section in mainpage %}
<div class="a-card" style="margin-bottom:0.75rem;padding:1rem" data-tab="{{ section.tab }}">
<div class="a-flex" style="justify-content:space-between">
<strong style="font-size:0.9rem">{{ section.tab }}</strong>
<div class="td-actions">
<button class="a-btn a-btn-sm" onclick="openAddCaseModal('{{ section.tab }}')"> Добавить кейс</button>
<button class="a-btn a-btn-danger a-btn-sm" onclick="deleteSection('{{ section.tab }}')"></button>
</div>
</div>
<div class="a-flex" style="flex-wrap:wrap;gap:0.5rem;margin-top:0.5rem">
{% for case_name in section.cases %}
<span style="background:rgba(255,255,255,0.04);border-radius:6px;padding:0.2rem 0.5rem;font-size:0.78rem;display:flex;align-items:center;gap:0.3rem">
🎲 {{ case_name }}
<span onclick="removeCaseFromSection('{{ section.tab }}','{{ case_name }}')" style="cursor:pointer;color:#ef4444;font-size:0.7rem"></span>
</span>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<button class="a-btn a-mt" onclick="openAddSectionModal()"> Добавить секцию</button>
</div>
<div class="a-card">
<div class="a-card-header">🎲 Все кейсы</div>
<div class="a-table-wrap">
<table class="a-table">
<thead><tr><th>Название</th><th>Цена</th><th>Тип</th><th>Предметов</th><th></th></tr></thead>
<tbody>
{% for c in cases %}
<tr>
<td><strong>{{ c.name }}</strong></td>
<td>{{ c.price_open }} ₽</td>
<td style="font-size:0.75rem">{{ c.display_name|default('') }}</td>
<td>{{ c.items_count }}</td>
<td class="td-actions">
<button class="a-btn a-btn-sm" onclick="openEditCaseModal('{{ c.name }}')">✏️</button>
<button class="a-btn a-btn-danger a-btn-sm" onclick="deleteCase('{{ c.name }}')">🗑️</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="a-table-card-view">
{% for c in cases %}
<div class="a-table-card">
<div class="tc-row">
<span class="tc-label">Название</span>
<span class="tc-value"><strong>{{ c.name }}</strong></span>
</div>
<div class="tc-row">
<span class="tc-label">Цена</span>
<span class="tc-value">{{ c.price_open }} ₽</span>
</div>
<div class="tc-row">
<span class="tc-label">Тип</span>
<span class="tc-value">{{ c.display_name|default('') }}</span>
</div>
<div class="tc-row">
<span class="tc-label">Предметов</span>
<span class="tc-value">{{ c.items_count }}</span>
</div>
<div class="tc-actions">
<button class="a-btn a-btn-sm" onclick="openEditCaseModal('{{ c.name }}')">✏️ Редактировать</button>
<button class="a-btn a-btn-danger a-btn-sm" onclick="deleteCase('{{ c.name }}')">🗑️</button>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
{% block modals %}
<!-- Create/Edit Case Modal -->
<div class="a-overlay" id="caseModal">
<div class="a-modal a-modal-wide" style="max-height:95vh;display:flex;flex-direction:column">
<div class="a-modal-title" id="caseModalTitle">🎲 Создать кейс</div>
<input type="hidden" id="editCaseName">
<div style="padding:0 1.5rem;flex:1;overflow-y:auto">
<div class="a-row a-gap-sm">
<div class="a-mb" style="flex:1">
<label class="a-label">Название кейса (ID)</label>
<input type="text" id="caseNameInput" class="a-input" placeholder="my_case">
</div>
<div class="a-mb" style="flex:1">
<label class="a-label">Отображаемое название</label>
<input type="text" id="caseDisplayName" class="a-input" placeholder="Мой кейс">
</div>
</div>
<div class="a-row a-gap-sm">
<div class="a-mb" style="flex:1">
<label class="a-label">Цена открытия</label>
<input type="number" id="casePrice" class="a-input" value="250">
</div>
<div class="a-mb" style="flex:1">
<label class="a-label">Ссылка на изображение</label>
<input type="text" id="caseImage" class="a-input" placeholder="/static/cases/default.png">
</div>
</div>
<div class="a-mb">
<label class="a-label">Описание (необязательно)</label>
<input type="text" id="caseDescription" class="a-input" placeholder="Описание кейса...">
</div>
<!-- Item browser section -->
<div class="a-card" style="background:rgba(0,0,0,0.2);padding:0.75rem;margin-bottom:1rem">
<div class="a-card-header" style="margin-bottom:0.5rem">📋 Предметы кейса <span id="itemCount" style="font-size:0.75rem;color:rgba(255,255,255,0.4)">(0)</span></div>
<!-- Selected items list -->
<div id="caseItemsList" style="max-height:200px;overflow-y:auto;margin-bottom:0.75rem"></div>
<!-- Search + filters + add controls -->
<div class="a-row a-gap-sm" style="margin-bottom:0.5rem">
<input type="text" id="caseItemSearch" class="a-input a-input-sm" style="flex:2;min-width:120px" placeholder="🔍 Поиск..." oninput="searchCaseItems()">
<select id="rarityFilter" class="a-input a-input-sm" style="flex:1;min-width:90px" onchange="searchCaseItems()">
<option value="">Редкость</option>
<option value="Consumer Grade">Consumer</option>
<option value="Industrial Grade">Industrial</option>
<option value="Mil-Spec">Mil-Spec</option>
<option value="Restricted">Restricted</option>
<option value="Classified">Classified</option>
<option value="Covert">Covert</option>
<option value="Rare Special Item">Rare Special</option>
<option value="Contraband">Contraband</option>
</select>
<select id="collectionFilter" class="a-input a-input-sm" style="flex:1.2;min-width:100px" onchange="searchCaseItems()">
<option value="">Коллекция</option>
</select>
<select id="sortBy" class="a-input a-input-sm" style="flex:0.7;min-width:80px" onchange="searchCaseItems()">
<option value="">Сортировка</option>
<option value="price_rub">Цена ↑</option>
<option value="price_rub&desc">Цена ↓</option>
<option value="name">Имя ↑</option>
<option value="rarity">Редкость ↑</option>
<option value="rarity&desc">Редкость ↓</option>
</select>
</div>
<div class="a-row a-gap-sm" style="margin-bottom:0.5rem">
<select id="typeFilter" class="a-input a-input-sm" style="flex:1;min-width:70px" onchange="searchCaseItems()">
<option value="">Тип</option>
</select>
<select id="weaponFilter" class="a-input a-input-sm" style="flex:1;min-width:80px" onchange="searchCaseItems()">
<option value="">Оружие</option>
</select>
<input type="number" id="minPrice" class="a-input a-input-sm" style="flex:0.6;min-width:60px" placeholder="Цена от" oninput="searchCaseItems()" value="0">
<input type="number" id="maxPrice" class="a-input a-input-sm" style="flex:0.6;min-width:60px" placeholder="Цена до" oninput="searchCaseItems()" value="0">
</div>
<!-- Search results -->
<div id="caseItemResults" style="max-height:220px;overflow-y:auto;border:1px solid rgba(255,255,255,0.06);border-radius:6px;padding:0.25rem"></div>
</div>
</div>
<div class="a-modal-actions" style="padding:0.75rem 1.5rem;border-top:1px solid rgba(255,255,255,0.06)">
<button class="a-btn" onclick="closeModal('caseModal')">Отмена</button>
<button class="a-btn a-btn-primary" id="saveCaseBtn" onclick="saveCase()">💾 Сохранить</button>
</div>
</div>
</div>
<!-- Add case to section modal -->
<div class="a-overlay" id="addCaseModal">
<div class="a-modal" style="max-width:400px">
<div class="a-modal-title">➕ Добавить кейс в секцию</div>
<p style="font-size:0.82rem;color:rgba(255,255,255,0.5);margin-bottom:0.75rem">Секция: <strong id="addCaseSectionName"></strong></p>
<div class="a-mb">
<label class="a-label">Выберите кейс</label>
<select id="addCaseSelect" class="a-input"></select>
</div>
<div class="a-modal-actions">
<button class="a-btn" onclick="closeModal('addCaseModal')">Отмена</button>
<button class="a-btn a-btn-primary" onclick="confirmAddCase()">Добавить</button>
</div>
</div>
</div>
<!-- Add section modal -->
<div class="a-overlay" id="addSectionModal">
<div class="a-modal" style="max-width:400px">
<div class="a-modal-title"> Новая секция</div>
<div class="a-mb">
<label class="a-label">Название вкладки</label>
<input type="text" id="newSectionName" class="a-input" placeholder="Новая коллекция">
</div>
<div class="a-modal-actions">
<button class="a-btn" onclick="closeModal('addSectionModal')">Отмена</button>
<button class="a-btn a-btn-primary" onclick="confirmAddSection()">Создать</button>
</div>
</div>
</div>
{% endblock %}
{% block extra_styles %}
<style>
.ci-item {
display:flex; align-items:center; gap:0.5rem;
padding:0.3rem 0.5rem; border-bottom:1px solid rgba(255,255,255,0.04);
font-size:0.78rem; transition:background 0.15s;
}
.ci-item:hover { background:rgba(255,255,255,0.03); }
.ci-item img { width:36px; height:28px; object-fit:contain; border-radius:3px; }
.ci-item .ci-info { flex:1; line-height:1.3; }
.ci-item .ci-rarity { font-size:0.65rem; color:rgba(255,255,255,0.35); }
.ci-result {
display:flex; align-items:center; gap:0.5rem;
padding:0.3rem 0.5rem; cursor:pointer;
border-bottom:1px solid rgba(255,255,255,0.03);
font-size:0.78rem; transition:all 0.12s; border-radius:3px;
}
.ci-result:hover { background:rgba(245,158,11,0.08); }
.ci-result img { width:36px; height:28px; object-fit:contain; border-radius:3px; }
.ci-result .ci-info { flex:1; line-height:1.3; }
.ci-result .ci-meta { font-size:0.65rem; color:rgba(255,255,255,0.35); }
.ci-result .ci-add { font-size:0.7rem; color:#f59e0b; }
</style>
{% endblock %}
{% block scripts %}
<script>
let currentCaseItems = [];
let editingCaseName = null;
let searchDebounce = null;
// ─── Modals ──────────────────────────────────────────────────────────────────
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
function openModal(id) { document.getElementById(id).classList.add('open'); }
// ─── Load filter options ─────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
const r = await fetch('/admin/api/cases/list');
allCasesList = await r.json();
// Load collections
const cr = await fetch('/admin/api/collections');
const cd = await cr.json();
const colSel = document.getElementById('collectionFilter');
(cd.collections || []).forEach(c => {
const o = document.createElement('option');
o.value = c; o.textContent = c;
colSel.appendChild(o);
});
// Load weapons + types
const fr = await fetch('/admin/api/items/filters');
const fd = await fr.json();
const typeSel = document.getElementById('typeFilter');
(fd.types || []).forEach(t => {
const o = document.createElement('option');
o.value = t; o.textContent = t;
typeSel.appendChild(o);
});
const weaponSel = document.getElementById('weaponFilter');
(fd.weapons || []).forEach(w => {
const o = document.createElement('option');
o.value = w; o.textContent = w;
weaponSel.appendChild(o);
});
});
// ─── Create / Edit Case ──────────────────────────────────────────────────────
function openCreateCaseModal() {
editingCaseName = null;
document.getElementById('caseModalTitle').textContent = '🎲 Создать кейс';
document.getElementById('saveCaseBtn').textContent = '💾 Создать';
document.getElementById('editCaseName').value = '';
document.getElementById('caseNameInput').value = '';
document.getElementById('caseDisplayName').value = '';
document.getElementById('casePrice').value = '250';
document.getElementById('caseImage').value = '';
document.getElementById('caseDescription').value = '';
currentCaseItems = [];
renderCaseItems();
document.getElementById('caseItemSearch').value = '';
document.getElementById('caseItemResults').innerHTML = '';
openModal('caseModal');
}
function openEditCaseModal(caseName) {
editingCaseName = caseName;
document.getElementById('caseModalTitle').textContent = '✏️ Редактировать кейс';
document.getElementById('saveCaseBtn').textContent = '💾 Сохранить';
document.getElementById('editCaseName').value = caseName;
const cfg = {{ cases_config|tojson }};
const c = cfg[caseName] || {};
document.getElementById('caseNameInput').value = caseName;
document.getElementById('caseDisplayName').value = c.display_name || '';
document.getElementById('casePrice').value = c.price_open || 250;
document.getElementById('caseImage').value = c.image_url || '';
document.getElementById('caseDescription').value = c.description || '';
currentCaseItems = (c.items || []).filter(i => typeof i === 'object').map(i => {
if (typeof i.id === 'number' && !i.market_hash_name) {
return { id: i.id, name: i.name || 'Item #' + i.id, market_hash_name: i.name || '' };
}
return i;
});
renderCaseItems();
document.getElementById('caseItemSearch').value = '';
document.getElementById('caseItemResults').innerHTML = '';
openModal('caseModal');
}
function renderCaseItems() {
const div = document.getElementById('caseItemsList');
const count = currentCaseItems.length;
document.getElementById('itemCount').textContent = `(${count})`;
if (count === 0) {
div.innerHTML = '<div style="font-size:0.75rem;color:rgba(255,255,255,0.3);padding:0.5rem 0">Нет предметов — добавьте через поиск выше</div>';
return;
}
div.innerHTML = currentCaseItems.map((item, i) => `
<div class="ci-item" onclick="removeCaseItem(${i})" style="cursor:pointer">
<img src="${item.image_url || '/static/placeholder.png'}" onerror="this.src='/static/placeholder.png'">
<div class="ci-info">
<div>${item.market_hash_name || item.name || '???'}</div>
<div class="ci-rarity">${item.rarity || ''}${item.collection ? ' • ' + item.collection : ''}</div>
</div>
<span style="font-size:0.65rem;color:#ef4444;opacity:0.6">✕</span>
</div>
`).join('');
}
function removeCaseItem(idx) {
currentCaseItems.splice(idx, 1);
renderCaseItems();
}
function addCaseItem(item) {
const key = (item.market_hash_name || item.name || '');
if (currentCaseItems.some(i => (i.market_hash_name || i.name) === key)) return;
currentCaseItems.push(item);
renderCaseItems();
}
function addAllFromCollection() {
const sel = document.getElementById('collectionFilter');
const coll = sel.value;
if (!coll) { Notify.error('Выберите коллекцию'); return; }
const rarity = document.getElementById('rarityFilter').value;
const typeF = document.getElementById('typeFilter').value;
const weaponF = document.getElementById('weaponFilter').value;
let url = `/admin/api/items/by-collection?collection=${encodeURIComponent(coll)}`;
if (rarity) url += `&rarity_filter=${encodeURIComponent(rarity)}`;
if (typeF) url += `&type_filter=${encodeURIComponent(typeF)}`;
if (weaponF) url += `&weapon_filter=${encodeURIComponent(weaponF)}`;
fetch(url)
.then(r => r.json())
.then(items => {
let added = 0;
let skipped = 0;
const alreadyIds = new Set(currentCaseItems.map(i => i.id));
items.forEach(item => {
if (alreadyIds.has(item.id)) {
skipped++;
return;
}
const key = (item.name || '');
if (!currentCaseItems.some(i => (i.market_hash_name || i.name) === key)) {
currentCaseItems.push(item);
added++;
}
});
renderCaseItems();
let msg = `Добавлено ${added} предметов из "${coll}"`;
if (skipped) msg += ` (${skipped} уже были в кейсе)`;
Notify.success(msg);
});
}
async function searchCaseItems() {
const q = document.getElementById('caseItemSearch').value;
const rarity = document.getElementById('rarityFilter').value;
const collection = document.getElementById('collectionFilter').value;
const typeF = document.getElementById('typeFilter').value;
const weaponF = document.getElementById('weaponFilter').value;
const minP = document.getElementById('minPrice').value;
const maxP = document.getElementById('maxPrice').value;
const sortV = document.getElementById('sortBy').value;
clearTimeout(searchDebounce);
searchDebounce = setTimeout(async () => {
const params = new URLSearchParams();
if (q.length >= 2) params.set('q', q);
if (rarity) params.set('rarity_filter', rarity);
if (collection) params.set('collection_filter', collection);
if (typeF) params.set('type_filter', typeF);
if (weaponF) params.set('weapon_filter', weaponF);
if (minP > 0) params.set('min_price', minP);
if (maxP > 0) params.set('max_price', maxP);
if (sortV) {
const [field, order] = sortV.split('&');
params.set('sort_by', field);
if (order) params.set('sort_order', 'desc');
}
params.set('limit', '100');
const r = await fetch(`/admin/api/items/search?${params.toString()}`);
const items = await r.json();
const div = document.getElementById('caseItemResults');
if (items.length === 0) {
div.innerHTML = '<div style="font-size:0.75rem;color:rgba(255,255,255,0.3);padding:0.5rem">Ничего не найдено</div>';
return;
}
let html = '';
if (collection) {
html += `<div style="padding:0.3rem 0.5rem;font-size:0.7rem;color:rgba(255,255,255,0.4);display:flex;justify-content:space-between">
<span>Найдено: ${items.length} предметов</span>
<span onclick="addAllFromCollection()" style="cursor:pointer;color:#f59e0b"> Добавить все из коллекции</span>
</div>`;
}
const alreadyIds = new Set(currentCaseItems.map(i => i.id));
html += items.filter(item => !alreadyIds.has(item.id)).map(item => {
const priceStr = item.price_rub > 0 ? item.price_rub.toLocaleString('ru') + '₽' : '';
return `
<div class="ci-result" onclick="addCaseItem(${JSON.stringify(item).replace(/"/g,'&quot;')})">
<img src="${item.image_url || '/static/placeholder.png'}" onerror="this.src='/static/placeholder.png'">
<div class="ci-info">
<div>${item.name}</div>
<div class="ci-meta">${item.rarity}${item.weapon ? ' • ' + item.weapon : ''}${priceStr ? ' • ' + priceStr : ''}</div>
</div>
<div class="ci-add">+</div>
</div>`;
}).join('');
const hidden = items.filter(item => alreadyIds.has(item.id)).length;
if (hidden > 0) {
html += `<div style="font-size:0.65rem;color:rgba(255,255,255,0.25);padding:0.3rem 0.5rem">${hidden} предмет(ов) уже в кейсе</div>`;
}
div.innerHTML = html;
}, q.length >= 2 ? 200 : 300);
}
async function saveCase() {
const name = document.getElementById('caseNameInput').value.trim();
if (!name) { Notify.error('Введите название кейса'); return; }
const fd = new FormData();
fd.append('case_name', name);
fd.append('display_name', document.getElementById('caseDisplayName').value);
fd.append('price_open', document.getElementById('casePrice').value);
fd.append('image_url', document.getElementById('caseImage').value);
fd.append('description', document.getElementById('caseDescription').value);
fd.append('items_json', JSON.stringify(currentCaseItems));
const isEdit = editingCaseName !== null;
const url = isEdit
? `/admin/api/cases/update/${encodeURIComponent(editingCaseName)}`
: '/admin/api/cases/create';
if (isEdit && editingCaseName !== name) {
fd.append('new_name', name);
}
const r = await fetch(url, { method:'POST', body:fd });
const d = await r.json();
if (d.success) { window.location.reload(); }
else Notify.error(d.error || 'Ошибка');
}
async function deleteCase(name) {
Notify.confirm(`Удалить кейс "${name}"?`, 'Подтверждение', async function(ok) {
if (!ok) return;
const fd = new FormData(); fd.append('case_name', name);
const r = await fetch(`/admin/api/cases/delete/${encodeURIComponent(name)}`, { method:'POST', body:fd });
const d = await r.json();
if (d.success) window.location.reload();
else Notify.error(d.error);
});
}
// ─── Mainpage Sections ───────────────────────────────────────────────────────
function openAddSectionModal() {
document.getElementById('newSectionName').value = '';
openModal('addSectionModal');
}
async function confirmAddSection() {
const name = document.getElementById('newSectionName').value.trim();
if (!name) return;
const fd = new FormData(); fd.append('tab', name);
const r = await fetch('/admin/api/mainpage/section/add', { method:'POST', body:fd });
const d = await r.json();
if (d.success) window.location.reload();
else Notify.error(d.error);
}
async function deleteSection(tab) {
Notify.confirm(`Удалить секцию "${tab}"?`, 'Подтверждение', async function(ok) {
if (!ok) return;
const fd = new FormData(); fd.append('tab', tab);
const r = await fetch('/admin/api/mainpage/section/delete', { method:'POST', body:fd });
const d = await r.json();
if (d.success) window.location.reload();
else Notify.error(d.error);
});
}
function openAddCaseModal(tab) {
document.getElementById('addCaseSectionName').textContent = tab;
const sel = document.getElementById('addCaseSelect');
sel.innerHTML = allCasesList.map(c => `<option value="${c.name}">${c.display_name || c.name}</option>`).join('');
sel.dataset.tab = tab;
openModal('addCaseModal');
}
async function confirmAddCase() {
const tab = document.getElementById('addCaseSelect').dataset.tab;
const caseName = document.getElementById('addCaseSelect').value;
const fd = new FormData();
fd.append('tab', tab);
fd.append('case_name', caseName);
const r = await fetch('/admin/api/mainpage/section/add-case', { method:'POST', body:fd });
const d = await r.json();
if (d.success) window.location.reload();
else Notify.error(d.error);
}
async function removeCaseFromSection(tab, caseName) {
Notify.confirm(`Убрать "${caseName}" из "${tab}"?`, 'Подтверждение', async function(ok) {
if (!ok) return;
const fd = new FormData();
fd.append('tab', tab);
fd.append('case_name', caseName);
const r = await fetch('/admin/api/mainpage/section/remove-case', { method:'POST', body:fd });
const d = await r.json();
if (d.success) window.location.reload();
else Notify.error(d.error);
});
}
</script>
{% endblock %}