Migrate backend to Porto architecture and fix minor bugs

- Fully transitioned the backend to the Porto architectural pattern
- Improved code organization and maintainability
- Fixed minor bugs and inconsistencies
This commit is contained in:
F4ilji
2025-05-12 08:47:43 +05:00
parent 76deaf75f3
commit c01016a154
620 changed files with 16218 additions and 6073 deletions
@@ -0,0 +1,11 @@
<?php
namespace App\Containers\Event\Loaders;
class AliasesLoader
{
/**
* @var array
*/
public array $aliases = [];
}
@@ -0,0 +1,26 @@
<?php
namespace App\Containers\Event\Loaders;
class MiddlewareLoader
{
/**
* @var array
*/
public array $middleware = [];
/**
* @var array
*/
public array $middlewareGroups = [];
/**
* @var array
*/
public array $routeMiddleware = [];
/**
* @var array
*/
public array $middlewarePriority = [];
}
@@ -0,0 +1,11 @@
<?php
namespace App\Containers\Event\Loaders;
class ProvidersLoader
{
/**
* @var array
*/
public array $providers = [];
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Containers\Event\Models;
use App\Ship\Models\Model;
use App\Ship\Traits\HasSeo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Tags\HasTags;
class Event extends Model
{
use HasFactory, HasTags, HasSeo;
protected $guarded = false;
protected $casts = [
'content' => 'array',
];
public function category() : BelongsTo
{
return $this->belongsTo(EventCategory::class);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Containers\Event\Models;
use App\Ship\Models\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
class EventCategory extends Model
{
use HasFactory;
protected $guarded = false;
public function events() : HasMany
{
return $this->hasMany(Event::class, 'category_id', 'id');
}
}
@@ -0,0 +1,108 @@
<?php
namespace App\Containers\Event\Policies;
use App\Containers\User\Models\User;
use App\Containers\Event\Models\EventCategory;
use Illuminate\Auth\Access\HandlesAuthorization;
class EventCategoryPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->can('view_any_event::category');
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, EventCategory $eventCategory): bool
{
return $user->can('view_event::category');
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->can('create_event::category');
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, EventCategory $eventCategory): bool
{
return $user->can('update_event::category');
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, EventCategory $eventCategory): bool
{
return $user->can('delete_event::category');
}
/**
* Determine whether the user can bulk delete.
*/
public function deleteAny(User $user): bool
{
return $user->can('delete_any_event::category');
}
/**
* Determine whether the user can permanently delete.
*/
public function forceDelete(User $user, EventCategory $eventCategory): bool
{
return $user->can('force_delete_event::category');
}
/**
* Determine whether the user can permanently bulk delete.
*/
public function forceDeleteAny(User $user): bool
{
return $user->can('force_delete_any_event::category');
}
/**
* Determine whether the user can restore.
*/
public function restore(User $user, EventCategory $eventCategory): bool
{
return $user->can('restore_event::category');
}
/**
* Determine whether the user can bulk restore.
*/
public function restoreAny(User $user): bool
{
return $user->can('restore_any_event::category');
}
/**
* Determine whether the user can replicate.
*/
public function replicate(User $user, EventCategory $eventCategory): bool
{
return $user->can('replicate_event::category');
}
/**
* Determine whether the user can reorder.
*/
public function reorder(User $user): bool
{
return $user->can('reorder_event::category');
}
}
@@ -0,0 +1,108 @@
<?php
namespace App\Containers\Event\Policies;
use App\Containers\User\Models\User;
use App\Containers\Event\Models\Event;
use Illuminate\Auth\Access\HandlesAuthorization;
class EventPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->can('view_any_event');
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Event $event): bool
{
return $user->can('view_event');
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return $user->can('create_event');
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Event $event): bool
{
return $user->can('update_event');
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Event $event): bool
{
return $user->can('delete_event');
}
/**
* Determine whether the user can bulk delete.
*/
public function deleteAny(User $user): bool
{
return $user->can('delete_any_event');
}
/**
* Determine whether the user can permanently delete.
*/
public function forceDelete(User $user, Event $event): bool
{
return $user->can('force_delete_event');
}
/**
* Determine whether the user can permanently bulk delete.
*/
public function forceDeleteAny(User $user): bool
{
return $user->can('force_delete_any_event');
}
/**
* Determine whether the user can restore.
*/
public function restore(User $user, Event $event): bool
{
return $user->can('restore_event');
}
/**
* Determine whether the user can bulk restore.
*/
public function restoreAny(User $user): bool
{
return $user->can('restore_any_event');
}
/**
* Determine whether the user can replicate.
*/
public function replicate(User $user, Event $event): bool
{
return $user->can('replicate_event');
}
/**
* Determine whether the user can reorder.
*/
public function reorder(User $user): bool
{
return $user->can('reorder_event');
}
}
@@ -0,0 +1,320 @@
<?php
namespace App\Containers\Event\UI\WEB\Controllers;
use App\Containers\Event\Models\Event;
use App\Containers\Event\Models\EventCategory;
use App\Containers\Event\UI\WEB\Transformers\EventCategoryResource;
use App\Containers\Event\UI\WEB\Transformers\EventPreviewResource;
use App\Containers\Event\UI\WEB\Transformers\EventResource;
use App\Ship\Contracts\SeoServiceInterface;
use App\Ship\Controllers\Controller;
use App\Ship\Enums\CacheKeys;
use App\Ship\Requests\Request;
use Carbon\Carbon;
use DateTime;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
class ClientEventController extends Controller
{
public function __construct(readonly SeoServiceInterface $seoPageProvider){}
public function index(Request $request): \Inertia\Response
{
$currentDate = $this->getCurrentDate($request);
$cacheKey = md5(serialize([$currentDate, $request->all()]));
$events = Cache::remember(
CacheKeys::EVENTS_PREFIX->value . $cacheKey,
now()->addHours(12),
fn() => $this->getEvents($currentDate)
);
$eventDates = Cache::remember(
CacheKeys::EVENTS_PREFIX->value . 'dates_' . $cacheKey,
now()->addHours(12),
fn() => $this->getEventDates($this->getFilters())
);
$categories = Cache::remember(
CacheKeys::EVENTS_PREFIX->value . 'categories',
now()->addDay(),
fn() => EventCategoryResource::collection(EventCategory::has('events')->get())
);
$filters = $this->getFilters();
$seo = $this->seoPageProvider->getSeoForCurrentPage();
return Inertia::render('Client/Events/Index', compact(
'eventDates',
'events',
'currentDate',
'filters',
'categories',
'seo'
));
}
public function show(string $slug): \Inertia\Response
{
$eventModel = Cache::remember(
CacheKeys::EVENT_PREFIX->value . $slug,
now()->addDay(),
function () use ($slug) {
return Event::where('slug', $slug)
->with(['category', 'seo'])
->firstOrFail();
}
);
$seo = Cache::remember(
CacheKeys::EVENT_PREFIX->value . 'seo_' . $slug,
now()->addDay(),
function () use ($eventModel) {
return $this->seoPageProvider->getSeoForModel($eventModel);
}
);
$event = new EventResource($eventModel);
return Inertia::render('Client/Events/Show', compact(
'event',
'seo'
));
}
public function archive(Request $request): \Inertia\Response
{
$cacheKey = md5(serialize($request->all()));
$events = Cache::remember(
CacheKeys::EVENTS_PREFIX->value . 'archive_' . $cacheKey,
now()->addDay(),
fn() => $this->getEventsArchive()
);
$categories = Cache::remember(
CacheKeys::EVENTS_PREFIX->value . 'categories',
now()->addDay(),
fn() => EventCategoryResource::collection(EventCategory::has('events')->get())
);
$filters = $this->getFilters();
$seo = $this->seoPageProvider->getSeoForCurrentPage();
return Inertia::render('Client/Events/Archive', compact(
'events',
'filters',
'categories',
'seo'
));
}
private function getCurrentDate(Request $request): array
{
$dateInput = $request->input('date');
// Если дата введена, создаем объект Carbon, иначе получаем ближайшую дату события
if ($dateInput) {
$date = new Carbon($dateInput);
} else {
$nearestEvent = Event::whereDate('event_date_start', '>=', now())
->orderBy('event_date_start', 'asc')
->first();
// Проверяем, найдено ли событие
if ($nearestEvent) {
$date = new Carbon($nearestEvent->event_date_start);
} else {
// Если событий нет, устанавливаем текущую дату
$date = Carbon::now();
}
}
return [
'fullDate' => $date->format('Y-m-j'),
'day' => $date->format('j'),
'month' => $date->getTranslatedMonthName('Do MMMM'),
];
}
private function getEvents(array $currentDate)
{
return EventPreviewResource::collection(Event::select('title', 'slug', 'event_date_start', 'event_time_start', 'address', 'is_online', 'category_id')
->whereDate('event_date_start', '=', $currentDate['fullDate'])
->with('category')
->when(request()->input('is_online'), function ($query, $value) {
$this->applyOnlineFilter($query, $value);
})
->when(request()->input('search'), function ($query, $search) {
$query->whereRaw('LOWER(title) like ?', ["%".strtolower($search)."%"]);
})
->when(request()->input('category'), function ($query) {
$slugs = request()->input('category');
if (is_array($slugs)) {
$query->whereHas('category', function ($query) use ($slugs) {
$query->whereIn('slug', $slugs);
});
}
})
->orderBy('event_time_start', 'asc')
->get());
}
private function getEventsArchive()
{
return EventPreviewResource::collection(Event::select('title', 'slug', 'event_date_start', 'event_time_start', 'address', 'is_online', 'category_id')
->whereDate('event_date_start', '<', now())
->with('category')
->when(request()->input('is_online'), function ($query, $value) {
$this->applyOnlineFilter($query, $value);
})
->when(request()->input('search'), function ($query, $search) {
$query->whereRaw('LOWER(title) like ?', ["%".strtolower($search)."%"]);
})
->when(request()->input('category'), function ($query) {
$slugs = request()->input('category');
if (is_array($slugs)) {
$query->whereHas('category', function ($query) use ($slugs) {
$query->whereIn('slug', $slugs);
});
}
})
->when(request()->input('sort', 'desc'), function ($query, $sort) {
$query->orderBy('event_date_start', $sort);
})
->orderBy('event_time_start', 'asc')
->paginate(6)
->withQueryString());
}
private function getEventDates(array $filters): \Illuminate\Support\Collection
{
// Получаем события с учетом фильтров
$events = Event::select('event_date_start')
->distinct()
->where('event_date_start', '>=', date('Y-m-d'))
->when($filters['is_online_filter']['value'], function ($query, $value) {
if ($value === 'online') {
$query->where('is_online', true);
} elseif ($value === 'offline') {
$query->where('is_online', false);
}
})
->when($filters['category_filter']['value'], function ($query) {
$slugs = request()->input('category');
if (is_array($slugs)) {
$query->whereHas('category', function ($query) use ($slugs) {
$query->whereIn('slug', $slugs);
});
}
})
->orderBy('event_date_start')
->get();
// Получаем массив без ключей
// Извлекаем уникальные даты из событий
return $events->map(function ($event) {
$date = new DateTime($event->event_date_start);
return [
'day' => $date->format('j'),
'dayOfWeek' => $this->getDayOfWeekRussian($date->format('l')),
'date' => $date->format('Y-m-j')
];
})
->groupBy(function ($item) {
return (new DateTime($item['date']))->format('m');
})
->map(function ($group, $month) {
return [
"month" => $this->getMonthNameRussian((int)$month),
"events" => $group->toArray()
];
})
->sortKeys() // Сортируем ключи по возрастанию
->values();
}
private function getFilters(): array
{
$categoriesContent = [];
if (request()->input('category')) {
foreach (request()->input('category') as $item) {
$categoriesContent[$item] = new EventCategoryResource(EventCategory::where('slug', $item)->first());
}
}
return [
'search_filter' => [
'type' => 'search',
'value' => request()->input('search'),
'param' => 'search'
],
'category_filter' => [
'type' => 'category',
'value' => request()->input('category'),
'param' => 'category',
'content' => $categoriesContent,
],
'sortingBy_filter' => [
'type' => 'sort',
'value' => request()->input('sort'),
'param' => 'sort',
],
'is_online_filter' => [
'type' => 'is_online',
'value' => request()->input('is_online'),
'param' => 'is_online',
],
];
}
private function getDayOfWeekRussian(string $dayOfWeek): string
{
$russianDays = [
'Monday' => 'пн',
'Tuesday' => 'вт',
'Wednesday' => 'ср',
'Thursday' => 'чт',
'Friday' => 'пт',
'Saturday' => 'сб',
'Sunday' => 'вс'
];
return $russianDays[$dayOfWeek] ?? '';
}
private function getMonthNameRussian(int $month): string
{
$russianMonths = [
1 => 'Январь',
2 => 'Февраль',
3 => 'Март',
4 => 'Апрель',
5 => 'Май',
6 => 'Июнь',
7 => 'Июль',
8 => 'Август',
9 => 'Сентябрь',
10 => 'Октябрь',
11 => 'Ноябрь',
12 => 'Декабрь'
];
return $russianMonths[$month] ?? '';
}
private function applyOnlineFilter($query, $isOnline): void
{
if ($isOnline === 'online') {
$query->where('is_online', true);
} elseif ($isOnline === 'offline') {
$query->where('is_online', false);
}
}
}
@@ -0,0 +1,13 @@
<?php
use App\Containers\Event\UI\WEB\Controllers\ClientEventController;
use Illuminate\Support\Facades\Route;
Route::middleware('access-check')->group(function () {
Route::get('/events', [ClientEventController::class, 'index'])->name('client.event.index');
Route::get('/events/archive', [ClientEventController::class, 'archive'])->name('client.event.archive'); // Доделать builder
Route::get('/events/{slug}', [ClientEventController::class, 'show'])->name('client.event.show');
});
@@ -0,0 +1,19 @@
<?php
namespace App\Containers\Event\UI\WEB\Transformers;
use App\Ship\Resources\JsonResource;
class EventCategoryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return parent::toArray($request);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Containers\Event\UI\WEB\Transformers;
use App\Ship\Resources\JsonResource;
use Illuminate\Support\Carbon;
class EventPreviewResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'event_date_start' => $this->event_date_start,
'event_time_start' => Carbon::parse($this->event_time_start)->format('H:i'),
'address' => $this->address,
'is_online' => $this->is_online,
'category' => $this->category ?? null,
];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Containers\Event\UI\WEB\Transformers;
use App\Ship\Resources\JsonResource;
use Illuminate\Support\Carbon;
class EventResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'content' => $this->content,
'event_date_start' => $this->event_date_start,
'event_time_start' => Carbon::parse($this->event_time_start)->format('H:i'),
'address' => $this->address,
'is_online' => $this->is_online,
'category' => $this->category ?? null,
];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Containers\Event\UI\WEB\Transformers;
use App\Ship\Resources\JsonResource;
use Carbon\Carbon;
class EventThumbnailResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'is_online' => $this->is_online,
'address' => $this->address,
'event_date_start' => [
'day' => Carbon::parse($this->event_date_start)->format('d'),
'month' => Carbon::parse($this->event_date_start)->getTranslatedMonthName('Do MMMM'),
'time' => Carbon::parse($this->event_time_start)->format('H:i'),
],
];
}
}