This commit is contained in:
f4ilji
2024-10-04 12:48:19 +05:00
parent 21a6e9073b
commit cebc584a14
303 changed files with 8224 additions and 2563 deletions
+28 -7
View File
@@ -31,6 +31,18 @@ use Symfony\Component\Finder\Finder;
class PostForm
{
private static function findSeoActive(array $data) : bool
{
$bool = false;
foreach ($data as $item) {
if ($item['data']['seo_active'] === true) {
$bool = true;
break;
}
}
return $bool;
}
public static function getForm(Form $form): Form
{
return $form
@@ -46,14 +58,16 @@ class PostForm
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string|null $state, Forms\Set $set) {
$set('slug', Str::slug($state));
$set('seo.title', $state);
}),
TextInput::make('slug')->label('Slug')->unique(ignoreRecord: true)->readOnly()->required(),
]),
Select::make('status')->options([
'verification' => 'На рассмотрении',
'published' => 'Одобрено',
'rejected' => 'Отказано',
])->label('Статус')->required()->default(PostStatus::VERIFICATION),
Select::make('status')->options(PostStatus::class)
->label('Статус')->required()
->disableOptionWhen(fn (string $value): bool =>
$value == PostStatus::PUBLISHED->value && !auth()->user()->can('publish_post')
)
->default(PostStatus::VERIFICATION),
Select::make('category_id')
->options(Category::all()->pluck('title', 'id'))
->preload()
@@ -64,7 +78,7 @@ class PostForm
]),
Tabs\Tab::make('Содержание новости')
->schema([
\Filament\Forms\Components\Builder::make('content')->label('')->blocks([
Builder::make('content')->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
@@ -76,6 +90,13 @@ class PostForm
]),
Builder\Block::make('paragraph')->label('Текст')
->schema([
Toggle::make('seo_active')->label('Использовать блок как seo')
->live(onBlur: true)
->disabled(function ($state, Forms\Get $get) {
$data = $get('../../');
return self::findSeoActive($data) && !$state;
})
->dehydrated(),
RichEditor::make('content')
->toolbarButtons([
'blockquote',
@@ -90,7 +111,7 @@ class PostForm
'undo',
])
->label(''),
]),
])->live(onBlur: true),
Builder\Block::make('files')->label('Файлы')
->schema([
Forms\Components\Repeater::make('file')->schema([
@@ -2,15 +2,23 @@
namespace App\Filament\Resources;
use App\Enums\CustomFormStatus;
use App\Enums\PostStatus;
use App\Filament\Resources\AcademicJournalResource\Pages;
use App\Filament\Resources\AcademicJournalResource\RelationManagers;
use App\Filament\Resources\AcademicJournalResource\RelationManagers\JournalsRelationManager;
use App\Helpers\ByteConverter;
use App\Models\AcademicJournal;
use App\Models\Category;
use App\Models\CustomForm;
use App\Models\Page;
use App\Models\Post;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Tabs;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
@@ -18,7 +26,9 @@ use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
class AcademicJournalResource extends Resource
@@ -77,9 +87,259 @@ class AcademicJournalResource extends Resource
'underline',
'undo',
])
->label('')
->required(),
->label(''),
])->label('Текст'),
Builder\Block::make('files')
->schema([
Forms\Components\Repeater::make('file')->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
]),
]),
Builder\Block::make('person')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('column')
->required()
->maxLength(255),
TextInput::make('content')
->required()
->maxLength(255),
]),
])->minItems(1),
]),
Builder\Block::make('stepper')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('tabs')
->schema([
Forms\Components\Repeater::make('tab')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
\Filament\Forms\Components\Builder::make('content')->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
]),
Builder\Block::make('paragraph')
->schema([
RichEditor::make('content')
->toolbarButtons([
'blockquote',
'bold',
'bulletList',
'italic',
'link',
'orderedList',
'redo',
'strike',
'underline',
'undo',
])
->label(''),
])->label('Текст'),
Builder\Block::make('files')
->schema([
Forms\Components\Repeater::make('file')->schema([
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->visibility('public')
]),
]),
Builder\Block::make('person')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('column')
->required()
->maxLength(255),
TextInput::make('content')
->required()
->maxLength(255),
]),
])->minItems(1),
]),
Builder\Block::make('stepper')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
Builder\Block::make('video')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->addActionLabel('Добавить новый блок'),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
@@ -95,26 +355,10 @@ class AcademicJournalResource extends Resource
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение(-я)'),
])->label('Изображение'),
Builder\Block::make('video')
->schema([
Hidden::make('mime'),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes(['video/mp4','video/ogg','video/webm'])
->maxSize(512000)
->disk('videos')
->visibility('public')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('files')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
@@ -122,22 +366,58 @@ class AcademicJournalResource extends Resource
FileUpload::make('path')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->visibility('public')
])
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
Builder\Block::make('postItem')
->schema([
Select::make('post')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Новость'),
Builder\Block::make('pageItem')
->schema([
Select::make('page')
->options(Page::query()->where('title', '!=' , null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Страница'),
Builder\Block::make('customForm')
->schema([
Select::make('form')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required(),
])->label('Форма'),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок'),
]),
Tabs\Tab::make('Редакция')
@@ -191,9 +471,259 @@ class AcademicJournalResource extends Resource
'underline',
'undo',
])
->label('')
->required()
->label(''),
])->label('Текст'),
Builder\Block::make('files')
->schema([
Forms\Components\Repeater::make('file')->schema([
Hidden::make('expansion')->required(),
Hidden::make('size')->required(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('expansion', $state?->getClientOriginalExtension());
$set('size', ByteConverter::bytesToHuman($state?->getSize()));
})
->visibility('public')
]),
]),
Builder\Block::make('person')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('column')
->required()
->maxLength(255),
TextInput::make('content')
->required()
->maxLength(255),
]),
])->minItems(1),
]),
Builder\Block::make('stepper')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('tabs')
->schema([
Forms\Components\Repeater::make('tab')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
\Filament\Forms\Components\Builder::make('content')->label('')->blocks([
Builder\Block::make('heading')->label('Заголовок')
->schema([
TextInput::make('id')->hidden()->integer()->default(rand(2335235,324634264263426)),
TextInput::make('content')
->label('')
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set, $get) {
}),
]),
Builder\Block::make('paragraph')
->schema([
RichEditor::make('content')
->toolbarButtons([
'blockquote',
'bold',
'bulletList',
'italic',
'link',
'orderedList',
'redo',
'strike',
'underline',
'undo',
])
->label(''),
])->label('Текст'),
Builder\Block::make('files')
->schema([
Forms\Components\Repeater::make('file')->schema([
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->visibility('public')
]),
]),
Builder\Block::make('person')
->schema([
TextInput::make('name')
->label('Имя')
->required()
->maxLength(255),
FileUpload::make('photo')
->label('Фотография')
->image()
->disk('public')
->directory('images')
->imageEditor(),
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('column')
->required()
->maxLength(255),
TextInput::make('content')
->required()
->maxLength(255),
]),
])->minItems(1),
]),
Builder\Block::make('stepper')
->schema([
TextInput::make('step_name')
->label('Название шага')
->required()
->maxLength(255),
Forms\Components\Repeater::make('steps')->schema([
TextInput::make('title')
->required()
->maxLength(255)->columnSpanFull(),
RichEditor::make('content')->required(),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение'),
Builder\Block::make('video')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes([
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->disk('public')
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->addActionLabel('Добавить новый блок'),
])->minItems(1),
]),
Builder\Block::make('images')
->schema([
FileUpload::make('url')
->label('Изображение(-я)')
->image()
->multiple()
->reorderable()
->maxFiles(5)
->disk('public')
->directory('images')
->imageEditor()
->required(),
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Слайдер изображений'),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
@@ -209,26 +739,10 @@ class AcademicJournalResource extends Resource
TextInput::make('alt')
->label('Описание')
->placeholder('Необязяательно')
])->label('Изображение(-я)'),
])->label('Изображение'),
Builder\Block::make('video')
->schema([
Hidden::make('mime'),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes(['video/mp4','video/ogg','video/webm'])
->maxSize(512000)
->disk('videos')
->visibility('public')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('files')
->schema([
TextInput::make('mime')->readOnly(),
TextInput::make('title')
->required()
->maxLength(255)
@@ -236,22 +750,58 @@ class AcademicJournalResource extends Resource
FileUpload::make('path')
->required()
->acceptedFileTypes([
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip'
'video/mp4',
'video/quicktime',
'video/x-msvideo',
'video/x-ms-wmv',
'video/avi',
'video/webm',
'video/ogg',
'video/3gpp',
'video/3gpp2',
'video/x-m4v',
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->visibility('public')
])
->directory('videos')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
]),
Builder\Block::make('postsList')
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('count')
->label('Количество запией')
->integer(),
Select::make('category')
->options(Category::all()->pluck('title', 'id'))
]),
])->label('Список новостей'),
Builder\Block::make('postItem')
->schema([
Select::make('post')
->options(Post::query()->where('status', PostStatus::PUBLISHED)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Новость'),
Builder\Block::make('pageItem')
->schema([
Select::make('page')
->options(Page::query()->where('title', '!=' , null)->where('is_visible', true)->pluck('title', 'id'))
->searchable()
->required(),
])->label('Страница'),
Builder\Block::make('customForm')
->schema([
Select::make('form')
->options(CustomForm::query()->where('status', CustomFormStatus::PUBLISHED)->pluck('title', 'form_id'))
->searchable()
->required(),
])->label('Форма'),
])
->collapsed()
->blockNumbers(false)
->collapsible()
->blockPickerColumns(3)
->blockPickerWidth('2xl')
->addActionLabel('Добавить новый блок'),
]),
])->columnSpanFull()
@@ -2,9 +2,10 @@
namespace App\Filament\Resources;
use App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource\RelationManagers;
use App\Models\Permission;
use App\Filament\Resources\AcceptedInvitationResource\Pages;
use App\Filament\Resources\AcceptedInvitationResource\RelationManagers;
use App\Models\AcceptedInvitation;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
@@ -13,15 +14,11 @@ use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
class PermissionResource extends Resource
class AcceptedInvitationResource extends Resource implements HasShieldPermissions
{
protected static ?string $model = Permission::class;
protected static ?string $model = AcceptedInvitation::class;
protected static ?string $navigationGroup = 'Settings';
protected static ?string $navigationIcon = 'heroicon-o-cursor-arrow-rays';
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form
{
@@ -60,9 +57,22 @@ class PermissionResource extends Resource
public static function getPages(): array
{
return [
'index' => Pages\ListPermissions::route('/'),
'create' => Pages\CreatePermission::route('/create'),
'edit' => Pages\EditPermission::route('/{record}/edit'),
'index' => Pages\ListAcceptedInvitations::route('/'),
'create' => Pages\CreateAcceptedInvitation::route('/create'),
'edit' => Pages\EditAcceptedInvitation::route('/{record}/edit'),
];
}
public static function getPermissionPrefixes(): array
{
return [
'view',
'view_any',
'create',
'update',
'delete',
'delete_any',
'invite'
];
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Filament\Resources\AcceptedInvitationResource\Pages;
use App\Filament\Resources\AcceptedInvitationResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateAcceptedInvitation extends CreateRecord
{
protected static string $resource = AcceptedInvitationResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\AcceptedInvitationResource\Pages;
use App\Filament\Resources\AcceptedInvitationResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditAcceptedInvitation extends EditRecord
{
protected static string $resource = AcceptedInvitationResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}
@@ -0,0 +1,58 @@
<?php
namespace App\Filament\Resources\AcceptedInvitationResource\Pages;
use App\Filament\Resources\AcceptedInvitationResource;
use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\User;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Actions;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Mail;
class ListAcceptedInvitations extends ListRecords
{
protected static string $resource = AcceptedInvitationResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
Actions\Action::make('inviteUser')->label('Пригласить автора')
->form([
TextInput::make('email')
->email()
->label('Почта для письма')
->required()
])
->action(function ($data) {
$inv = User::query()
->where('email', $data['email'])
->first();
if ($inv) {
Notification::make()
->title('Данный пользователь существует в системе')
->danger()
->send();
} else {
$invitation = Invitation::create([
'email' => $data['email'],
'user_id' => auth()->user()->id,
]);
Mail::to($invitation->email)->send(new InvitationMail($invitation));
Notification::make('invitedSuccess')
->body('Пользователь приглашен')
->success()->send();
}
})->visible(auth()->user()->can('invite_accepted::invitation'))
];
}
}
@@ -39,8 +39,18 @@ class AdmissionCampaignResource extends Resource
Forms\Components\Section::make()->schema([
Forms\Components\Repeater::make('info')->schema([
Forms\Components\Select::make('edu_name')->options(LevelEducational::class),
Forms\Components\Grid::make(2)->schema([
Forms\Components\Section::make()->schema([
TextInput::make('total_programs')->label('Количество программ по набору')->integer()->required(),
]),
Forms\Components\Section::make('Места')->schema([
TextInput::make('och_count')->label('Количество мест (Очная форма)')->integer()->required(),
TextInput::make('zaoch_count')->label('Количество мест (Заочная форма)')->integer()->required(),
TextInput::make('budget_places')->label('Количество бюджетных мест')->integer()->required(),
TextInput::make('non_budget_places')->label('Количество платных мест')->integer()->required(),
]),
]),
])->columnSpanFull(),
]),
]);
}
@@ -22,7 +22,6 @@ class EditMainSection extends EditRecord
//
// protected function mutateFormDataBeforeSave(array $data): array
// {
// $this->subSection_ids = $data['subSection_ids'];
// unset($data['subSection_ids']);
//
// return $data;
@@ -30,6 +29,7 @@ class EditMainSection extends EditRecord
protected function afterSave(): void
{
$this->subSection_ids = SubSection::query()->where('main_section_id', '=', $this->record->id)->pluck('id')->toArray();
SubSection::query()->where('main_section_id', '=', $this->record->id)->update(['main_section_id' => NULL]);
SubSection::whereIn('id', $this->subSection_ids)->update(['main_section_id' => $this->record->id]);
$subSections = SubSection::query()->where('main_section_id', '=', $this->record->id)->get();
@@ -6,16 +6,18 @@ use App\Filament\Resources\PageResource;
use App\Models\SubSection;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Str;
class CreatePage extends CreateRecord
{
protected static string $resource = PageResource::class;
protected array $seoData;
protected function mutateFormDataBeforeCreate(array $data): array
{
$subSection = SubSection::find($data['sub_section_id']);
if ($subSection == null) {
$data['path'] = $data['slug'];
} elseif($subSection->mainSection == null) {
@@ -25,23 +27,50 @@ class CreatePage extends CreateRecord
}
unset($data['sub_section_id']);
$this->seoData = $this->generateSeo($data);
$data['search_data'] = $this->generateSearchData($data['content']);
return $data;
}
protected function afterCreate(): void
{
$this->record->seo()->create($this->seoData);
}
private function generateSeo(array $data) : array
{
$title = $data['title'];
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
$description = strip_tags($rowData['data']['content']);
return [
'title' => $title,
'description' => Str::limit($description, 160),
];
}
private function getFirstBlockByName(string $name, array $content) : array|null
{
$data = null;
foreach ($content as $block) {
$data = ($block['type'] === $name) ? $block : null;
break;
}
return $data;
}
private function generateSearchData(array $data) : string
{
$result = "";
foreach ($data['content'] as $block) {
foreach ($data as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
// Приводим текст к нижнему регистру
$data['search_data'] = strtolower($result);
return $data;
return strtolower($result);
}
private function getDataFromBlocks($block) : string
@@ -5,38 +5,25 @@ namespace App\Filament\Resources\PageResource\Pages;
use App\Filament\Resources\PageResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Str;
class EditPage extends EditRecord
{
protected static string $resource = PageResource::class;
protected array $seoData;
protected function mutateFormDataBeforeSave(array $data): array
{
$this->seoData = $this->generateSeo($data);
$result = "";
foreach ($data['content'] as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
// Приводим текст к нижнему регистру
$data['search_data'] = strtolower($result);
$data['search_data'] = $this->generateSearchData($data['content']);
return $data;
}
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
protected function afterSave(): void
{
if ($this->record->is_registered == false) {
@@ -49,6 +36,52 @@ class EditPage extends EditRecord
}
}
$this->record->seo()->create($this->seoData);
}
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
private function generateSeo(array $data) : array
{
$title = $data['title'];
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
$description = strip_tags($rowData['data']['content']);
return [
'title' => $title,
'description' => Str::limit($description, 160),
];
}
private function getFirstBlockByName(string $name, array $content) : array|null
{
$data = null;
foreach ($content as $block) {
$data = ($block['type'] === $name) ? $block : null;
break;
}
return $data;
}
private function generateSearchData(array $data) : string
{
$result = "";
foreach ($data as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
return strtolower($result);
}
private function getDataFromBlocks($block) : string
@@ -87,7 +120,6 @@ class EditPage extends EditRecord
}
return $data;
}
public function hasCombinedRelationManagerTabsWithContent(): bool
{
return true;
@@ -1,12 +0,0 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreatePermission extends CreateRecord
{
protected static string $resource = PermissionResource::class;
}
@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditPermission extends EditRecord
{
protected static string $resource = PermissionResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}
@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListPermissions extends ListRecords
{
protected static string $resource = PermissionResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}
+16 -1
View File
@@ -8,7 +8,9 @@ use App\Filament\Resources\PostResource\Pages;
use App\Models\Category;
use App\Models\Page;
use App\Models\Post;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Actions\DeleteAction;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Checkbox;
@@ -36,7 +38,7 @@ use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Mohamedsabil83\FilamentFormsTinyeditor\Components\TinyEditor;
class PostResource extends Resource
class PostResource extends Resource implements HasShieldPermissions
{
protected static ?string $model = Post::class;
@@ -92,6 +94,19 @@ class PostResource extends Resource
];
}
public static function getPermissionPrefixes(): array
{
return [
'view',
'view_any',
'create',
'update',
'delete',
'delete_any',
'publish'
];
}
@@ -2,7 +2,11 @@
namespace App\Filament\Resources\PostResource\Pages;
use App\Enums\PostStatus;
use App\Filament\Resources\PostResource;
use App\Models\Post;
use App\Models\User;
use Carbon\Carbon;
use Closure;
use Filament\Actions;
use Filament\Notifications\Actions\Action;
@@ -10,33 +14,94 @@ use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Support\Str;
use PhpParser\Node\Expr\AssignOp\Mod;
class CreatePost extends CreateRecord
{
protected static string $resource = PostResource::class;
protected array $seoData;
protected function mutateFormDataBeforeCreate(array $data): array
{
$this->seoData = $this->generateSeo($data);
$data['preview_text'] = $this->setPreviewText($data);
$data['publish_at'] = $this->setPublishDateTime($data['status']);
$data['search_data'] = $this->generateSearchData($data['content']);
$data['reading_time'] = $this->calculateReadingTime($data['search_data']);
return $data;
}
protected function afterCreate(): void
{
$this->record->seo()->create($this->seoData);
$this->sendNotify($this->record, auth()->user());
}
private function generateSeo(array $data) : array
{
$title = $data['title'];
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
$description = strip_tags($rowData['data']['content']);
$image = ($data['preview'] !== null) ? $data['preview'] : null;
return [
'title' => $title,
'description' => Str::limit($description, 160),
'image' => $image,
];
}
private function setPreviewText(array $data) : string
{
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
$preview_text = strip_tags($rowData['data']['content']);
return Str::limit($preview_text, 160);
}
private function generateSearchData(array $data) : string
{
$result = "";
foreach ($data['content'] as $block) {
foreach ($data as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
// Приводим текст к нижнему регистру
$data['search_data'] = strtolower($result);
return strtolower($result);
}
private function getFirstBlockByName(string $name, array $content) : array|null
{
$data = null;
foreach ($content as $block) {
$data = ($block['type'] === $name) ? $block : null;
break;
}
return $data;
}
protected function afterCreate(): void
{
$recipient = auth()->user();
private function getBlockBySeoActiveState(string $name, array $content) : array|null
{
$data = [];
foreach ($content as $block) {
if ($block['type'] === $name) {
$data[] = $block;
}
}
$block = null;
foreach ($data as $item) {
if ($item['data']['seo_active'] === true) {
$block = $item;
}
}
return $block;
}
private function sendNotify($post, $recipient) : void
{
Notification::make()
->title('Новость на проверку')
->body('Новая запись была создана!')
@@ -45,13 +110,17 @@ class CreatePost extends CreateRecord
->label('Проверить')
->button()
->markAsRead()
->url(PostResource::getUrl('edit', ['record' => $this->record])),
->url(PostResource::getUrl('edit', ['record' => $post])),
])
->sendToDatabase($recipient);
])->sendToDatabase($recipient);
}
private function setPublishDateTime(PostStatus $status) : Carbon|null
{
if ($status !== PostStatus::PUBLISHED) {
return null;
}
return Carbon::now();
}
private function calculateReadingTime(string $text): int
{
@@ -73,7 +142,6 @@ class CreatePost extends CreateRecord
return $readingTime;
}
protected function convertDataToHtml($blocks) {
$convertedHtml = "";
foreach ($blocks as $block) {
@@ -126,7 +194,6 @@ class CreatePost extends CreateRecord
}
return $convertedHtml;
}
private function getDataFromBlocks($block) : string
{
$data = "";
@@ -2,32 +2,83 @@
namespace App\Filament\Resources\PostResource\Pages;
use App\Enums\PostStatus;
use App\Filament\Resources\PostResource;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Str;
class EditPost extends EditRecord
{
protected static string $resource = PostResource::class;
protected array $seoData;
protected function mutateFormDataBeforeSave(array $data): array
{
$result = "";
foreach ($data['content'] as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
// Приводим текст к нижнему регистру
$data['search_data'] = strtolower($result);
$this->seoData = $this->generateSeo($data);
$data['preview_text'] = $this->setPreviewText($data);
$data['publish_at'] = $this->setPublishDateTime($data['status'], $this->record->publish_at);
$data['search_data'] = $this->generateSearchData($data['content']);
$data['reading_time'] = $this->calculateReadingTime($data['search_data']);
return $data;
}
protected function afterSave(): void
{
$this->record->seo()->update($this->seoData);
}
private function setPreviewText(array $data) : string
{
$rowData = $this->getBlockBySeoActiveState('paragraph', $data['content']);
$preview_text = strip_tags($rowData['data']['content']);
return Str::limit($preview_text, 160);
}
private function getBlockBySeoActiveState(string $name, array $content) : array|null
{
$data = [];
foreach ($content as $block) {
if ($block['type'] === $name) {
$data[] = $block;
}
}
$block = null;
foreach ($data as $item) {
if ($item['data']['seo_active'] === true) {
$block = $item;
}
}
return $block;
}
private function generateSeo(array $data) : array
{
$title = $data['title'];
$rowData = $this->getFirstBlockByName('paragraph', $data['content']);
$description = strip_tags($rowData['data']['content']);
$image = ($this->record->preview !== null) ? $this->record->preview : null;
return [
'title' => $title,
'description' => Str::limit($description, 160),
'image' => $image,
];
}
private function setPublishDateTime($status, $publish_at)
{
if ($publish_at !== null) {
return $publish_at;
}
return PostStatus::tryFrom($status) === PostStatus::PUBLISHED ? Carbon::now() : null;
}
private function getDataFromBlocks($block) : string
{
$data = "";
@@ -65,6 +116,51 @@ class EditPost extends EditRecord
return $data;
}
private function calculateReadingTime(string $text): int
{
// Calculate the number of words in the text
$wordCount = str_word_count($text,0,"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя");
// Calculate the average reading speed in words per minute
$wordsPerMinute = 120; // You can adjust this value based on your desired reading speed
// Calculate the reading time in minutes
$readingTime = $wordCount / $wordsPerMinute;
// Round the reading time to the nearest integer
$readingTime = round($readingTime);
return $readingTime;
}
private function generateSearchData(array $data) : string
{
$result = "";
foreach ($data as $block) {
$result .= $this->getDataFromBlocks($block);
}
// Удаляем лишние пробелы и переносы строк
$result = preg_replace('/\s+/', ' ', $result);
$result = trim($result);
return strtolower($result);
}
private function getFirstBlockByName(string $name, array $content) : array|null
{
$data = null;
foreach ($content as $block) {
$data = ($block['type'] === $name) ? $block : null;
break;
}
return $data;
}
protected function getHeaderActions(): array
@@ -1,164 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\RedactorPostResource\Pages;
use App\Models\Category;
use App\Models\Post;
use Filament\Actions\DeleteAction;
use Filament\Forms;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\SpatieTagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Infolists\Components\Card;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Str;
class RedactorPostResource extends Resource
{
protected static ?string $model = Post::class;
protected static ?string $navigationGroup = "Для редактора";
protected static ?string $pluralLabel = 'Новости';
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form
{
return $form
->schema([
Section::make()
->schema([
Forms\Components\Grid::make(2)->schema([
TextInput::make('title')->label('Заголовок')->required()
->live(onBlur: true)
->afterStateUpdated(function (string $operation, string $state, Forms\Set $set) {
$set('slug', Str::slug($state));
}),
TextInput::make('slug')->label('Slug')->unique(ignoreRecord: true)->readOnly()->required(),
]),
Section::make()->schema([
\Filament\Forms\Components\Builder::make('content')->label('Контент')->blocks([
Builder\Block::make('heading')
->schema([
TextInput::make('content')
->label('Heading')
->required(),
Select::make('level')
->options([
'h1' => 'Heading 1',
'h2' => 'Heading 2',
'h3' => 'Heading 3',
'h4' => 'Heading 4',
'h5' => 'Heading 5',
'h6' => 'Heading 6',
])
->required(),
])
->columns(2),
Builder\Block::make('paragraph')
->schema([
RichEditor::make('content')
->label('Paragraph')
->required()
]),
Builder\Block::make('image')
->schema([
FileUpload::make('url')
->label('Image')
->image()
->required(),
TextInput::make('alt')
->label('Alt text')
->required(),
]),
Builder\Block::make('video')
->schema([
Hidden::make('mime'),
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->acceptedFileTypes(['video/mp4','video/ogg','video/webm'])
->maxSize(512000)
->disk('videos')
->visibility('public')
->afterStateUpdated(fn (callable $set, $state) => $set('mime', $state?->getMimeType())),
])
]),
]),
Select::make('status')->options([
'verification' => 'На рассмотрении',
'published' => 'Одобрено',
'rejected' => 'Отказано',
])->label('Статус')->required()->default('verification'),
Forms\Components\TagsInput::make('authors')
->label('Авторы')->placeholder('Добавить автора'),
SpatieTagsInput::make('tags')
->label('Тэги'),
Select::make('category_id')
->options(Category::all()->pluck('title', 'id'))
->preload()
->label('Категория'),
FileUpload::make('preview')->label('Превью новости')->image()->imageEditor(),
TextInput::make('search_data')->hidden(),
])
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id'),
Tables\Columns\TextColumn::make('title')->label('Заголовок')
->searchable(),
Tables\Columns\TextColumn::make('status')->label('Статус')->badge()
])->defaultSort('created_at', 'desc')
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListRedactorPosts::route('/'),
'create' => Pages\CreateRedactorPost::route('/create'),
'edit' => Pages\EditRedactorPost::route('/{record}/edit'),
];
}
}
@@ -1,12 +0,0 @@
<?php
namespace App\Filament\Resources\RedactorPostResource\Pages;
use App\Filament\Resources\RedactorPostResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateRedactorPost extends CreateRecord
{
protected static string $resource = RedactorPostResource::class;
}
@@ -1,24 +0,0 @@
<?php
namespace App\Filament\Resources\RedactorPostResource\Pages;
use App\Filament\Resources\RedactorPostResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditRedactorPost extends EditRecord
{
protected static string $resource = RedactorPostResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('index');
}
}
@@ -1,46 +0,0 @@
<?php
namespace App\Filament\Resources\RedactorPostResource\Pages;
use App\Enums\PostStatus;
use App\Filament\Resources\PostResource;
use App\Filament\Resources\RedactorPostResource;
use App\Models\Post;
use Filament\Actions;
use Filament\Resources\Components\Tab;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class ListRedactorPosts extends ListRecords
{
protected static string $resource = RedactorPostResource::class;
public \Illuminate\Support\Collection $postsByStatuses;
public function __construct()
{
$this->postsByStatuses = Post::select('status', DB::raw('count(*) as post_count'))
->groupBy('status')
->pluck('post_count', 'status');
}
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
public function getTabs(): array
{
return [
'status' => Tab::make('Новости на рассмотрении')->modifyQueryUsing(function (Builder $query) {
$query->where('status', '=', PostStatus::VERIFICATION->value);
})->badge($this->postsByStatuses[PostStatus::VERIFICATION->value] ?? '0'),
'All' => Tab::make('Все новости'),
];
}
}
-66
View File
@@ -1,66 +0,0 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource\RelationManagers;
use App\Models\Role;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static ?string $navigationGroup = 'Settings';
protected static ?string $navigationIcon = 'heroicon-o-shield-check';
public static function form(Form $form): Form
{
return $form
->schema([
//
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
//
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListRoles::route('/'),
'create' => Pages\CreateRole::route('/create'),
'edit' => Pages\EditRole::route('/{record}/edit'),
];
}
}
@@ -1,12 +0,0 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateRole extends CreateRecord
{
protected static string $resource = RoleResource::class;
}
@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditRole extends EditRecord
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}
@@ -1,19 +0,0 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListRoles extends ListRecords
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}
+84 -60
View File
@@ -4,6 +4,7 @@ namespace App\Filament\Resources;
use App\Filament\Resources\ScheduleResource\Pages;
use App\Filament\Resources\ScheduleResource\RelationManagers;
use App\Helpers\ByteConverter;
use App\Models\Category;
use App\Models\EducationalGroup;
use App\Models\Schedule;
@@ -26,8 +27,10 @@ use Filament\Tables;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\Livewire;
class ScheduleResource extends Resource
@@ -58,72 +61,93 @@ class ScheduleResource extends Resource
Select::make('educational_group_id')->options(EducationalGroup::all()->pluck('title', 'id'))
->live()
->label('Выбрать группу')
->afterStateUpdated(function (string|null $state, Forms\Set $set, Get $get) {
if (!empty($state)) {
$set('title', EducationalGroup::query()->where('id', $get('educational_group_id'))->first()->title);
}
})
->required(),
TextInput::make('title')
->live()
// TextInput::make('title')
// ->live()
// ->label('Заголовок')->required(),
->label('Заголовок')->required(),
Select::make('type')->options([
'schedule' => 'Обычное расписание',
'interval' => 'Временное расписание',
'exam' => 'Промежуточная аттестация',
])->label('Тип расписания')->required()->live(),
// Select::make('type')->options([
// 'schedule' => 'Обычное расписание',
// 'interval' => 'Временное расписание',
// 'exam' => 'Промежуточная аттестация',
// ])->label('Тип расписания')->required()->live(),
Forms\Components\Toggle::make('is_zaoch')->label('Очная|Заочная')->inline(false),
]),
Forms\Components\Repeater::make('days')->label('')->schema([
Forms\Components\Repeater::make('form')->label('')->schema([
Forms\Components\Repeater::make('weeks')->label('')->schema([
Forms\Components\Repeater::make('lesson_info')->label('')->schema([
TextInput::make('title')->label('Название-пары'),
TextInput::make('teacher')->label('Преподаватель'),
TextInput::make('studyRoom')->label('Кабинет')
])->live()->maxItems(2)->collapsed()->addActionLabel('Добавить подгруппу')->columns(3)
->itemLabel(function (Get $get, $state) {
static $count = 1;
if (count($get('lesson_info')) === 1) {
return "Общая группа";
} else {
$nmb = $count++ % 2 == 0 ? 2 : 1;
return "Подгруппа " . $nmb; }
}),
])->maxItems(2)->addActionLabel('Добавить четную/нечетную неделю')
->itemLabel(function (Get $get) {
static $position = 0;
if (count($get('weeks')) === 1) {
return "Общая неделя";
} else {
$nmb = $position++ % 2 == 0 ? 0 : 1;
return self::$typeWeek[$nmb] . " неделя";
}
// Forms\Components\Repeater::make('days')->label('')->schema([
// Forms\Components\Repeater::make('form')->label('')->schema([
// Forms\Components\Repeater::make('weeks')->label('')->schema([
// Forms\Components\Repeater::make('lesson_info')->label('')->schema([
// TextInput::make('title')->label('Название-пары'),
// TextInput::make('teacher')->label('Преподаватель'),
// TextInput::make('studyRoom')->label('Кабинет')
// ])->live()->maxItems(2)->collapsed()->addActionLabel('Добавить подгруппу')->columns(3)
// ->itemLabel(function (Get $get, $state) {
// static $count = 1;
// if (count($get('lesson_info')) === 1) {
// return "Общая группа";
// } else {
// $nmb = $count++ % 2 == 0 ? 2 : 1;
// return "Подгруппа " . $nmb; }
// }),
// ])->maxItems(2)->addActionLabel('Добавить четную/нечетную неделю')
// ->itemLabel(function (Get $get) {
// static $position = 0;
// if (count($get('weeks')) === 1) {
// return "Общая неделя";
// } else {
// $nmb = $position++ % 2 == 0 ? 0 : 1;
// return self::$typeWeek[$nmb] . " неделя";
// }
// })
// ->collapsed()
// ])
// ->maxItems(5)
// ->itemLabel(function (Get $get) {
// static $count = 0;
// $maxCount = count($get('form'));
// $count = ($count++ <= $maxCount) ? $count : 1;
// return "Пара #" . $count;
// })
// ->addActionLabel('Добавить пару'),
// ])->maxItems(6)->minItems(1)->itemLabel(function ($state) {
// static $position = 0;
// return self::$weekDays[$position++];
// })->addActionLabel('Добавить день недели')->collapsed()->defaultItems(6)->hidden(function (callable $get) {
// if ($get('type') === 'schedule' || $get('type') === 'interval') {
// return false;
// } else {
// return true;
// }
// }),
]),
Section::make()
->schema([
Forms\Components\Repeater::make('file')->schema([
TextInput::make('title')
->required()
->maxLength(255)
->autofocus(),
FileUpload::make('path')
->required()
->getUploadedFileNameForStorageUsing(
fn (TemporaryUploadedFile $file): string =>
str(Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . '-' . Carbon::now()->timestamp ) . '.' . $file->getClientOriginalExtension())
)
->acceptedFileTypes([
'application/pdf',
])
->maxSize(512000)
->disk('public')
->directory('files')
->downloadable()
->afterStateUpdated(function ($set, $state) {
$set('title', pathinfo($state?->getClientOriginalName(), PATHINFO_FILENAME));
})
->collapsed()
])
->maxItems(5)
->itemLabel(function (Get $get) {
static $count = 0;
$maxCount = count($get('form'));
$count = ($count++ <= $maxCount) ? $count : 1;
return "Пара #" . $count;
})
->addActionLabel('Добавить пару'),
])->maxItems(6)->minItems(1)->itemLabel(function ($state) {
static $position = 0;
return self::$weekDays[$position++];
})->addActionLabel('Добавить день недели')->collapsed()->defaultItems(6)->hidden(function (callable $get) {
if ($get('type') === 'schedule' || $get('type') === 'interval') {
return false;
} else {
return true;
}
}),
])
->visibility('public')
]),
])
]);
}
@@ -12,7 +12,6 @@ class CreateSchedule extends CreateRecord
protected function mutateFormDataBeforeCreate(array $data): array
{
dd($data);
return $data;
}
@@ -12,37 +12,4 @@ use Filament\Resources\Pages\CreateRecord;
class CreateSubSection extends CreateRecord
{
protected static string $resource = SubSectionResource::class;
protected array $page_ids;
protected function mutateFormDataBeforeCreate(array $data): array
{
$this->page_ids = $data['page_ids'];
unset($data['page_ids']);
return $data;
}
protected function afterCreate(): void
{
if ($this->page_ids != null) {
Page::whereIn('id', $this->page_ids)->update(['sub_section_id' => $this->record->id]);
$pages = Page::where('is_url', '=', false)->where('sub_section_id', '=', $this->record->id)->get();
if (!$pages->isEmpty()) {
$mainSectionSlug = ($pages[0]->section->mainSection) ? $pages[0]->section->mainSection->slug : '';
foreach ($pages as $page) {
if ($page->is_registered != true) {
$page->update(['path' => $page->path = $mainSectionSlug . '/' . $this->record->slug . '/' . $page->slug]);
}
}
}
}
}
}
+15 -2
View File
@@ -5,6 +5,7 @@ namespace App\Filament\Resources;
use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Models\User;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
@@ -13,7 +14,7 @@ use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
class UserResource extends Resource
class UserResource extends Resource implements HasShieldPermissions
{
protected static ?string $model = User::class;
@@ -40,7 +41,6 @@ class UserResource extends Resource
->password()
->required(fn (string $context): bool => $context === 'create')
->dehydrated(fn ($state) => filled($state))
->maxLength(255),
]);
}
@@ -93,4 +93,17 @@ class UserResource extends Resource
'edit' => Pages\EditUser::route('/{record}/edit'),
];
}
public static function getPermissionPrefixes(): array
{
return [
'view',
'view_any',
'create',
'update',
'delete',
'delete_any',
'invite'
];
}
}
@@ -3,8 +3,14 @@
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\User;
use Filament\Actions;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Mail;
class ListUsers extends ListRecords
{
@@ -14,6 +20,38 @@ class ListUsers extends ListRecords
{
return [
Actions\CreateAction::make(),
Actions\Action::make('inviteUser')->label('Пригласить автора')
->form([
TextInput::make('email')
->email()
->label('Почта для письма')
->required()
])
->action(function ($data) {
$inv = User::query()
->where('email', $data['email'])
->first();
if ($inv) {
Notification::make()
->title('Данный пользователь существует в системе')
->danger()
->send();
} else {
$invitation = Invitation::create([
'email' => $data['email'],
'user_id' => auth()->user()->id,
]);
Mail::to($invitation->email)->send(new InvitationMail($invitation));
Notification::make('invitedSuccess')
->body('Пользователь приглашен')
->success()->send();
}
})->visible(auth()->user()->can('invite_user'))
];
}
}