Rework admin panel and other

This commit is contained in:
F4ilji
2025-04-02 18:37:20 +05:00
parent 49072e50c7
commit 5cd6ff11b5
198 changed files with 9715 additions and 6664 deletions
@@ -5,6 +5,7 @@ namespace App\Services\Filament\Domain\Posts;
use App\Dto\MainSliderDTO;
use App\Models\MainSlider;
use App\Models\Post;
use App\Models\Slide;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
@@ -23,7 +24,8 @@ class PostSliderService
public function create(): void
{
try {
$this->post->mainSlider()->create([
$post = Post::find($this->post->id);
$slide = new Slide([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
@@ -33,11 +35,13 @@ class PostSliderService
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
'slider_id' => $this->dto->slider_id,
]);
$post->slide()->save($slide);
Log::info('MainSlider created successfully', ['postTitle' => $this->post->title]);
Log::info('Slide created successfully', ['postTitle' => $this->post->title]);
} catch (\Exception $e) {
Log::error('Failed to create MainSlider', [
Log::error('Failed to create slide', [
'postTitle' => $this->post->title,
'error' => $e->getMessage(),
]);
@@ -53,31 +57,20 @@ class PostSliderService
public function update(): void
{
try {
// Retrieve the MainSlider instance
$mainSlider = $this->post->mainSlider;
$post = Post::find($this->post->id);
$post->slide()->update([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
'link' => $this->generatePostLink(),
'settings' => $this->dto->settings,
'color_theme' => $this->dto->color_theme,
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
'slider_id' => $this->dto->slider_id,
]);
if ($mainSlider) {
// Update properties and save to trigger model events
$mainSlider->fill([
'title' => $this->dto->title,
'content' => $this->dto->content,
'image' => $this->dto->image,
'link' => $this->generatePostLink(),
'settings' => $this->dto->settings,
'color_theme' => $this->dto->color_theme,
'is_active' => $this->dto->is_active,
'start_time' => $this->dto->start_time,
'end_time' => $this->dto->end_time,
]);
$mainSlider->save(); // This will trigger updating and updated observer events
Log::info('MainSlider updated successfully', ['postTitle' => $this->post->title]);
} else {
Log::warning('MainSlider not found for update', ['postTitle' => $this->post->title]);
}
} catch (\Exception $e) {
Log::error('Failed to update MainSlider', [
'postTitle' => $this->post->title,
@@ -0,0 +1,95 @@
<?php
namespace App\Services\Filament\Domain\Seo;
use Illuminate\Support\Str;
class SeoGeneratorService
{
/**
*
* @param array $data
* @return array
*/
public function generate(array $data): array
{
return [
'title' => $this->extractSeoTitle($data),
'description' => $this->extractSeoDescription($data['content']),
'image' => $this->extractSeoImage($data),
];
}
/**
* Извлекает SEO-заголовок.
*
* @param array $data
* @return string
*/
private function extractSeoTitle(array $data): string
{
return $data['title'];
}
/**
* Извлекает SEO-описание.
*
* @param array $content
* @return string
*/
private function extractSeoDescription(array $content): string
{
$rowData = $this->getBlockBySeoActiveState('paragraph', $content);
if ($rowData === null) {
$rowData = $this->getFirstBlockByName('paragraph', $content);
}
$description = $rowData ? html_entity_decode(strip_tags($rowData['data']['content'])) : '';
return Str::limit(htmlspecialchars($description, ENT_QUOTES, 'UTF-8'), 160);
}
/**
* Извлекает SEO-изображение.
*
* @param array $data
* @return string|null
*/
private function extractSeoImage(array $data): ?string
{
return $data['preview'] ?? null;
}
/**
* Находит первый блок по имени.
*
* @param string $name
* @param array $content
* @return array|null
*/
private function getFirstBlockByName(string $name, array $content): ?array
{
foreach ($content as $block) {
if ($block['type'] === $name) {
return $block;
}
}
return null;
}
/**
* Находит блок по SEO-активности.
*
* @param string $name
* @param array $content
* @return array|null
*/
private function getBlockBySeoActiveState(string $name, array $content): ?array
{
foreach ($content as $block) {
if ($block['type'] === $name && ($block['data']['seo_active'] ?? false)) {
return $block;
}
}
return null;
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Services\Filament\Services;
use DiDom\Document;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class BreadcrumbFinderService
{
const FILES_DIR = 'sveden';
public function isSameCategory($html)
{
return $this->getBreadcrumb($html);
}
private function getBreadcrumb(string $html): ?string
{
$document = new Document($html);
$breadcrumbs = $document->first('ol.breadcrumb')?->find('li') ?? [];
foreach ($breadcrumbs as $index => $breadcrumb) {
if ($index === 2) { // Индексация с 0 → третий элемент = 2
return $breadcrumb->text();
}
}
return null;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Services\Filament\Services;
use DiDom\Document;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class CategoryFinderService
{
const FILES_DIR = 'sveden';
public function getCategories()
{
$file = public_path(self::FILES_DIR . '/' . 'index.html');
$html = file_get_contents($file);
$document = new Document($html);
$dropdownMenu = $document->first('ul.dropdown-menu');
$links = $dropdownMenu->find('a');
$categories = [];
foreach ($links as $link) {
$category = trim($link->text());
$categories[] = $category;
}
return $categories;
}
}
@@ -0,0 +1,198 @@
<?php
namespace App\Services\Filament\Services;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class StaticFileSearch
{
const CACHE_KEY = 'static_html_index_v2';
const FILES_DIR = 'sveden';
const CACHE_TTL = 86400; // 24 часа
const PER_PAGE = 10; // Количество результатов на страницу
public function search(string $query): array
{
if ($query === null) {
return [
'data' => null
];
}
$page = request()->input('page', 1);
try {
$index = $this->getIndex();
$results = [];
$normalizedQuery = $this->normalizeText(Str::lower($query));
foreach ($index as $filePath => $content) {
if (stripos($content['content'], $normalizedQuery) !== false) {
$relativePath = str_replace(public_path() . '/', '', $filePath);
$results[] = [
'file' => $relativePath,
'content' => $content['title'],
'category' => trim($content['category']),
];
}
}
return $this->paginateResults($results, $page);
} catch (\Exception $e) {
Log::error('Search error: ' . $e->getMessage());
return [
'data' => [],
'meta' => [
'current_page' => 1,
'total' => 0,
'per_page' => self::PER_PAGE,
'last_page' => 1
]
];
}
}
protected function paginateResults(array $results, int $page): array
{
$total = count($results);
$lastPage = max(1, ceil($total / self::PER_PAGE));
$page = max(1, min($page, $lastPage));
$offset = ($page - 1) * self::PER_PAGE;
$paginatedResults = array_slice($results, $offset, self::PER_PAGE);
return [
'data' => $paginatedResults,
'meta' => [
'current_page' => $page,
'total' => $total,
'per_page' => self::PER_PAGE,
'last_page' => $lastPage
]
];
}
protected function getIndex(): array
{
return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function() {
try {
$index = [];
$directory = public_path(self::FILES_DIR);
if (!is_dir($directory)) {
Log::error("Directory not found: {$directory}");
return [];
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $this->isHtmlFile($file)) {
$content = file_get_contents($file->getPathname());
if ($content !== false) {
$breadcrumb = app(BreadcrumbFinderService::class)->isSameCategory($content);
$text = $this->normalizeText(strip_tags($content));
$index[$file->getPathname()] = [
'title' => $this->getFirstH1Content($content),
'content' => $text,
'category' => $breadcrumb ?? null,
];
}
}
}
return $index;
} catch (\Exception $e) {
Log::error('Index creation error: ' . $e->getMessage());
return [];
}
});
}
protected function isHtmlFile(\SplFileInfo $file): bool
{
$extension = strtolower($file->getExtension());
return in_array($extension, ['html', 'htm']);
}
protected function normalizeText(string $text): string
{
$text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = preg_replace('/\s+/u', ' ', $text);
$text = trim($text);
return Str::lower($text);
}
protected function findMatches(string $content, string $query): array
{
$matches = [];
$offset = 0;
$query = Str::lower($query);
$content = Str::lower($content);
$queryLength = mb_strlen($query, 'UTF-8');
while (($offset = mb_strpos($content, $query, $offset, 'UTF-8')) !== false) {
$start = max(0, $offset - 50);
$length = min(150, mb_strlen($content) - $start);
$excerpt = mb_substr($content, $start, $length, 'UTF-8');
$matches[] = str_replace(
$query,
'[[HIGHLIGHT]]'.$query.'[[/HIGHLIGHT]]',
$excerpt
);
$offset += $queryLength;
}
return $matches;
}
public function clearCache(): bool
{
try {
Cache::forget(self::CACHE_KEY);
return true;
} catch (\Exception $e) {
Log::error('Cache clear error: ' . $e->getMessage());
return false;
}
}
public function rebuildIndex(): array
{
$this->clearCache();
return $this->getIndex();
}
public function getCacheStatus(): array
{
return [
'exists' => Cache::has(self::CACHE_KEY),
'ttl' => Cache::get(self::CACHE_KEY.'_ttl', null),
'driver' => config('cache.default'),
'path' => public_path(self::FILES_DIR),
'directory_exists' => is_dir(public_path(self::FILES_DIR))
];
}
public function getFirstH1Content(string $content): ?string
{
try {
if (preg_match('/<h1[^>]*>(.*?)<\/h1>/is', $content, $matches)) {
return $this->normalizeText($matches[1]);
}
return null;
} catch (\Exception $e) {
Log::error('Failed to get H1: ' . $e->getMessage());
return null;
}
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Services\Filament\Traits;
use App\Services\App\Seo\SeoDescriptionInterface;
use App\Services\Filament\Domain\Seo\SeoGeneratorService;
trait SeoGenerate
{
public function createSeo($record): void
{
$record->seo()->create($this->generateSeo($record));
}
public function updateSeo($record): void
{
if ($record->seo()->exists()) {
$record->seo()->update($this->generateSeo($record));
} else {
$this->createSeo($record);
}
}
private function generateSeo($record) {
return app(SeoGeneratorService::class)->generate([
'title' => $record->title,
'content' => $record instanceof SeoDescriptionInterface
? $record->getSeoDescription()
: $record->content,
'preview' => $record->preview,
]);
}
}