Создан компонет счетчика сайта
This commit is contained in:
parent
54b92c3015
commit
95c7b64d4c
11 changed files with 425 additions and 31 deletions
|
|
@ -7,6 +7,7 @@
|
|||
- Все изменения должны быть предварительно объяснены пользователю
|
||||
- Перед решением конкретной задачи всегда составлять план
|
||||
- После внесения изменений в код - проводить проверку - только после этого приступать к дальнейшему решению задачи
|
||||
- **НЕ производить сборку проекта (`bun run build`) без явного разрешения пользователя**
|
||||
|
||||
2. **Прозрачность действий**
|
||||
- Ассистент должен объяснить, какие изменения планируется внести
|
||||
|
|
@ -36,14 +37,14 @@
|
|||
|
||||
8 **Проверка типов данных**
|
||||
- Проверять проект на ошибки типизации через команду `bun run tsc --noEmit -p frontend/tsconfig.json`
|
||||
- Не производить сборку проекта без моего разрешения
|
||||
- НЕ производить сборку проекта (`bun run build`) без явного разрешения пользователя
|
||||
- В проекте не должно быть типов any
|
||||
- Все интерфейсы компонентов прописывать в файле globalInterfaces.ts
|
||||
- При работе с PocketBase использовать актуальные сигнатуры методов из файла `D:\Verstka\production\astro_minivan\frontend\node_modules\pocketbase\dist\pocketbase.es.d.ts`
|
||||
|
||||
9 **Плагин @astrojs/sitemap**
|
||||
- Обязательно к установке в проект пакета @astrojs/sitemap
|
||||
- Обязательно к созданию в проекте файла .nvmrc
|
||||
- Обязательно к созданию в проекте файл .nvmrc
|
||||
|
||||
|
||||
## Технические правила (Astro)
|
||||
|
|
|
|||
103
backend/pb_migrations/1777466303_created_site_visitors.js
Normal file
103
backend/pb_migrations/1777466303_created_site_visitors.js
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
migrate((app) => {
|
||||
const collection = new Collection({
|
||||
"createRule": null,
|
||||
"deleteRule": null,
|
||||
"fields": [
|
||||
{
|
||||
"autogeneratePattern": "[a-z0-9]{15}",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3208210256",
|
||||
"max": 15,
|
||||
"min": 15,
|
||||
"name": "id",
|
||||
"pattern": "^[a-z0-9]+$",
|
||||
"presentable": false,
|
||||
"primaryKey": true,
|
||||
"required": true,
|
||||
"system": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text791980464",
|
||||
"max": 0,
|
||||
"min": 0,
|
||||
"name": "visitor_hash",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text2783163181",
|
||||
"max": 0,
|
||||
"min": 0,
|
||||
"name": "ip",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3293145029",
|
||||
"max": 0,
|
||||
"min": 0,
|
||||
"name": "user_agent",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate2990389176",
|
||||
"name": "created",
|
||||
"onCreate": true,
|
||||
"onUpdate": false,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate3332085495",
|
||||
"name": "updated",
|
||||
"onCreate": true,
|
||||
"onUpdate": true,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
}
|
||||
],
|
||||
"id": "pbc_2651661972",
|
||||
"indexes": [],
|
||||
"listRule": null,
|
||||
"name": "site_visitors",
|
||||
"system": false,
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
});
|
||||
|
||||
return app.save(collection);
|
||||
}, (app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972");
|
||||
|
||||
return app.delete(collection);
|
||||
})
|
||||
28
backend/pb_migrations/1777466913_updated_site_visitors.js
Normal file
28
backend/pb_migrations/1777466913_updated_site_visitors.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
migrate((app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": "",
|
||||
"deleteRule": "@request.auth.id != \"\"",
|
||||
"listRule": "@request.auth.id != \"\"",
|
||||
"updateRule": "@request.auth.id != \"\"",
|
||||
"viewRule": "@request.auth.id != \"\" "
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
}, (app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": null,
|
||||
"deleteRule": null,
|
||||
"listRule": null,
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
})
|
||||
20
backend/pb_migrations/1777466930_updated_site_visitors.js
Normal file
20
backend/pb_migrations/1777466930_updated_site_visitors.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
migrate((app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": "@request.method = \"POST\""
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
}, (app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": ""
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
})
|
||||
20
backend/pb_migrations/1777468200_updated_site_visitors.js
Normal file
20
backend/pb_migrations/1777468200_updated_site_visitors.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
migrate((app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": ""
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
}, (app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"createRule": "@request.method = \"POST\""
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
})
|
||||
22
backend/pb_migrations/1777472256_updated_site_visitors.js
Normal file
22
backend/pb_migrations/1777472256_updated_site_visitors.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
migrate((app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"listRule": "",
|
||||
"viewRule": ""
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
}, (app) => {
|
||||
const collection = app.findCollectionByNameOrId("pbc_2651661972")
|
||||
|
||||
// update collection data
|
||||
unmarshal({
|
||||
"listRule": "@request.auth.id != \"\"",
|
||||
"viewRule": "@request.auth.id != \"\" "
|
||||
}, collection)
|
||||
|
||||
return app.save(collection)
|
||||
})
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
---
|
||||
import { COMPANY } from '@constants';
|
||||
import VisitorCounter from './VisitorCounter.astro';
|
||||
|
||||
const sectionsLinks = [
|
||||
{ label: 'Услуги', href: '/services' },
|
||||
|
|
@ -25,10 +26,8 @@ const currentYear = new Date().getFullYear().toString();
|
|||
<footer class="footer">
|
||||
<div class="site-container footer-container">
|
||||
|
||||
<!-- Верхняя часть футера (Колонки) -->
|
||||
<div class="footer-top">
|
||||
|
||||
<!-- Колонка 1: Бренд и описание -->
|
||||
<div class="footer-col brand-col">
|
||||
<a href="/" class="footer-logo">Автоюрист086</a>
|
||||
<p class="brand-desc">
|
||||
|
|
@ -38,7 +37,6 @@ const currentYear = new Date().getFullYear().toString();
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Колонка 2: Разделы и Разное -->
|
||||
<div class="footer-col links-cols">
|
||||
<div class="footer-links-group">
|
||||
<h4 class="col-title">Разделы</h4>
|
||||
|
|
@ -58,13 +56,11 @@ const currentYear = new Date().getFullYear().toString();
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Колонка 3: Контакты -->
|
||||
<div class="footer-col">
|
||||
<h4 class="col-title">Связь с нами</h4>
|
||||
<p class="address">{COMPANY.address}</p>
|
||||
<a href={`tel:${COMPANY.phoneClean}`} class="footer-phone">{COMPANY.phone}</a>
|
||||
|
||||
<!-- Иконка "Поделиться" -->
|
||||
<button class="share-btn" aria-label="Share">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="18" cy="5" r="3"></circle>
|
||||
|
|
@ -78,9 +74,9 @@ const currentYear = new Date().getFullYear().toString();
|
|||
|
||||
</div>
|
||||
|
||||
<!-- Нижняя часть футера (Копирайт) -->
|
||||
<div class="footer-bottom">
|
||||
<p class="copyright">© {currentYear} Автоюрист086.ru Все права защищены.</p>
|
||||
<VisitorCounter client:load today={0} total={0} />
|
||||
<ul class="footer-bottom-links">
|
||||
{legalLinks.map(link => (
|
||||
<li><a href={link.href}>{link.label}</a></li>
|
||||
|
|
@ -92,24 +88,20 @@ const currentYear = new Date().getFullYear().toString();
|
|||
</footer>
|
||||
|
||||
<style>
|
||||
/* Базовые стили футера */
|
||||
.footer {
|
||||
background-color: #031529; /* Темно-синий фон */
|
||||
color: #8c9bb0; /* Приглушенный серо-голубой цвет текста */
|
||||
background-color: #031529;
|
||||
color: #8c9bb0;
|
||||
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
||||
padding: 4rem 0 1.5rem 0;
|
||||
}
|
||||
|
||||
/* Сетка для колонок */
|
||||
.footer-top {
|
||||
display: grid;
|
||||
/* Пропорции колонок: первая чуть шире, остальные равны */
|
||||
grid-template-columns: 1.5fr 1fr 1fr 1fr;
|
||||
gap: 2rem;
|
||||
margin-bottom: 4rem;
|
||||
}
|
||||
|
||||
/* Колонка 1 */
|
||||
.footer-logo {
|
||||
display: inline-block;
|
||||
color: #ffffff;
|
||||
|
|
@ -126,16 +118,14 @@ const currentYear = new Date().getFullYear().toString();
|
|||
margin: 0;
|
||||
}
|
||||
|
||||
/* Заголовки колонок (Золотой цвет) */
|
||||
.col-title {
|
||||
color: #d1b06b; /* Золотистый/бежевый */
|
||||
color: #d1b06b;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
margin: 0 0 1.5rem 0;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
/* Списки ссылок */
|
||||
.footer-links {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
|
|
@ -154,10 +144,9 @@ const currentYear = new Date().getFullYear().toString();
|
|||
}
|
||||
|
||||
.footer-links a:hover {
|
||||
color: #d1b06b; /* При наведении становятся золотыми */
|
||||
color: #d1b06b;
|
||||
}
|
||||
|
||||
/* Колонка Контактов */
|
||||
.address {
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 1rem;
|
||||
|
|
@ -170,10 +159,9 @@ const currentYear = new Date().getFullYear().toString();
|
|||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
margin-bottom: 1.5rem;
|
||||
font-family: system-ui, -apple-system, sans-serif; /* Цифры лучше читаются в sans-serif */
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
|
||||
/* Кнопка "Поделиться" */
|
||||
.share-btn {
|
||||
background: transparent;
|
||||
border: 1px solid #2a3a50;
|
||||
|
|
@ -194,17 +182,16 @@ const currentYear = new Date().getFullYear().toString();
|
|||
background-color: rgba(209, 176, 107, 0.05);
|
||||
}
|
||||
|
||||
/* Нижняя панель (Копирайт) */
|
||||
.footer-bottom {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid rgba(140, 155, 176, 0.1); /* Тонкая полоска разделителя */
|
||||
border-top: 1px solid rgba(140, 155, 176, 0.1);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.copyright, .developer {
|
||||
.copyright {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
|
|
@ -227,19 +214,38 @@ const currentYear = new Date().getFullYear().toString();
|
|||
color: #d1b06b;
|
||||
}
|
||||
|
||||
/* Адаптивность для мобильных устройств */
|
||||
.visitor-counters {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.counter-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.counter-item :global(svg) {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.counter-value {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.footer {
|
||||
padding: 3rem 1.5rem 1rem 1.5rem;
|
||||
}
|
||||
|
||||
.footer-top {
|
||||
grid-template-columns: 1fr; /* 1 колонка */
|
||||
grid-template-columns: 1fr;
|
||||
gap: 2.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Разделы и Разное в одном ряду */
|
||||
.links-cols {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
|
|
@ -250,7 +256,6 @@ const currentYear = new Date().getFullYear().toString();
|
|||
flex: 1;
|
||||
}
|
||||
|
||||
/* Центрируем все элементы */
|
||||
.brand-col {
|
||||
text-align: center;
|
||||
}
|
||||
|
|
@ -277,9 +282,13 @@ const currentYear = new Date().getFullYear().toString();
|
|||
gap: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.visitor-counters {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Планшет - 2 колонки */
|
||||
@media (min-width: 641px) and (max-width: 767px) {
|
||||
.footer-top {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
|
|
@ -291,7 +300,6 @@ const currentYear = new Date().getFullYear().toString();
|
|||
}
|
||||
}
|
||||
|
||||
/* Десктоп (md и выше) - 4 колонки в один ряд: Бренд | Разделы | Разное | Контакты */
|
||||
@media (min-width: 768px) {
|
||||
.footer-top {
|
||||
grid-template-columns: 1.5fr 1fr 1fr 1fr;
|
||||
|
|
@ -299,7 +307,7 @@ const currentYear = new Date().getFullYear().toString();
|
|||
}
|
||||
|
||||
.links-cols {
|
||||
display: contents; /* Дочерние элементы становятся частью грида */
|
||||
display: contents;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
69
frontend/src/components/layout/footer/VisitorCounter.astro
Normal file
69
frontend/src/components/layout/footer/VisitorCounter.astro
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
---
|
||||
import { Icon } from 'astro-icon/components';
|
||||
|
||||
interface Props {
|
||||
today?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
const { today = 0, total = 0 } = Astro.props;
|
||||
---
|
||||
|
||||
<div class="visitor-counters">
|
||||
<div class="counter-item">
|
||||
<Icon name="users-group" />
|
||||
<span class="counter-value">{today} сегодня</span>
|
||||
</div>
|
||||
<div class="counter-item">
|
||||
<Icon name="users-total" />
|
||||
<span class="counter-value">{total} всего</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
const root = document.querySelector('.visitor-counters');
|
||||
if (!root) return;
|
||||
|
||||
const valueEls = root.querySelectorAll('.counter-value');
|
||||
if (valueEls.length < 2) return;
|
||||
|
||||
const todayStr = new Date().toDateString();
|
||||
|
||||
fetch('/api/visitors').then(r => r.json()).then(d => {
|
||||
if (typeof d.todayVisitors === 'number') {
|
||||
if (d.isNewVisitor) {
|
||||
localStorage.setItem('site_visited', todayStr);
|
||||
}
|
||||
if (valueEls[0]) valueEls[0].textContent = d.todayVisitors + ' сегодня';
|
||||
if (valueEls[1]) valueEls[1].textContent = d.totalVisitors + ' всего';
|
||||
}
|
||||
}).catch(() => {});
|
||||
})();
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.visitor-counters {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.counter-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: #8c9bb0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.counter-item :global(svg) {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.counter-value {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
6
frontend/src/icons/users-group.svg
Normal file
6
frontend/src/icons/users-group.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>
|
||||
<circle cx="9" cy="7" r="4"></circle>
|
||||
<line x1="19" y1="8" x2="19" y2="14"></line>
|
||||
<line x1="22" y1="11" x2="16" y2="11"></line>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 385 B |
6
frontend/src/icons/users-total.svg
Normal file
6
frontend/src/icons/users-total.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>
|
||||
<circle cx="9" cy="7" r="4"></circle>
|
||||
<path d="M22 21v-2a4 4 0 0 0-3-3.87"></path>
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 383 B |
111
frontend/src/pages/api/visitors.ts
Normal file
111
frontend/src/pages/api/visitors.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import type { APIRoute } from 'astro';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
|
||||
|
||||
function getClientIp(request: Request): string {
|
||||
const forwarded = request.headers.get('x-forwarded-for');
|
||||
if (forwarded) {
|
||||
return forwarded.split(',')[0].trim();
|
||||
}
|
||||
const realIp = request.headers.get('x-real-ip');
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
const host = request.headers.get('host') || 'localhost';
|
||||
return host.includes('localhost') || host.includes('127.0.0.1') ? 'localhost' : 'unknown';
|
||||
}
|
||||
|
||||
function generateVisitorHash(ip: string, userAgent: string): string {
|
||||
return crypto.createHash('sha256').update(ip + userAgent).digest('hex').slice(0, 32);
|
||||
}
|
||||
|
||||
async function pbRequest(method: string, path: string, body?: object) {
|
||||
const url = `${POCKETBASE_URL}${path}`;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'http://127.0.0.1:4321',
|
||||
},
|
||||
};
|
||||
if (body) options.body = JSON.stringify(body);
|
||||
|
||||
const res = await fetch(url, options);
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`PB ${method} ${path}: ${res.status} - ${err}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function jsonResponse(data: object, status = 200): Response {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
|
||||
});
|
||||
}
|
||||
|
||||
export const GET: APIRoute = async ({ request }) => {
|
||||
try {
|
||||
const ip = getClientIp(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
const visitorHash = generateVisitorHash(ip, userAgent);
|
||||
|
||||
const now = new Date();
|
||||
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const yesterdayStr = yesterday.toISOString().split('T')[0] + ' 00:00:00.000Z';
|
||||
|
||||
// Проверяем был ли посетитель за последние 24 часа
|
||||
const filterLast24h = `visitor_hash="${visitorHash}" && created >= "${yesterdayStr}"`;
|
||||
|
||||
let existingVisitor;
|
||||
try {
|
||||
const res = await pbRequest('GET', `/api/collections/site_visitors/records?filter=${encodeURIComponent(filterLast24h)}&perPage=1`);
|
||||
existingVisitor = { totalItems: res.totalItems || 0 };
|
||||
} catch {
|
||||
existingVisitor = { totalItems: 0 };
|
||||
}
|
||||
|
||||
let isNewVisitor = false;
|
||||
|
||||
// Создаём запись только если НЕ было посещения за последние 24ч
|
||||
if (existingVisitor.totalItems === 0) {
|
||||
isNewVisitor = true;
|
||||
try {
|
||||
await pbRequest('POST', '/api/collections/site_visitors/records', {
|
||||
visitor_hash: visitorHash,
|
||||
ip: ip,
|
||||
user_agent: userAgent,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Получаем статистику за сегодня
|
||||
const filterToday = `created >= "${yesterdayStr}"`;
|
||||
let todayCount = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
try {
|
||||
const resToday = await pbRequest('GET', `/api/collections/site_visitors/records?filter=${encodeURIComponent(filterToday)}&perPage=1`);
|
||||
todayCount = resToday.totalItems || 0;
|
||||
} catch {
|
||||
todayCount = 0;
|
||||
}
|
||||
|
||||
try {
|
||||
const resTotal = await pbRequest('GET', '/api/collections/site_visitors/records?perPage=1');
|
||||
totalCount = resTotal.totalItems || 0;
|
||||
} catch {
|
||||
totalCount = 0;
|
||||
}
|
||||
|
||||
return jsonResponse({ todayVisitors: todayCount, totalVisitors: totalCount, isNewVisitor }, 200);
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Visitors] Error:', error);
|
||||
return jsonResponse({ error: 'Внутренняя ошибка сервера' }, 500);
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue