This commit is contained in:
Meghdad committed 2026-11-26 12:29:14 +03:30
commit 647c8a8cab
236 files changed
+24692

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
<?php
namespace App\Filament\Pages;
use App\Models\Setting;
use BackedEnum;
use Filament\Facades\Filament;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
class SiteFooter extends Page
{
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingStorefront;
protected static ?int $navigationSort = 40;
protected string $view = 'filament.pages.site-footer';
public ?array $data = [];
public function getTitle(): string
{
return __('admin.footer.title');
}
public static function getNavigationLabel(): string
{
return __('admin.footer.title');
}
public static function canAccess(): bool
{
return Filament::auth()->user()?->canAccessPanel(Filament::getCurrentOrDefaultPanel()) ?? false;
}
public function mount(): void
{
$this->form->fill(Setting::read(Setting::STUDIO_PUBLIC_INFORMATION, []));
}
public function form(Schema $schema): Schema
{
return $schema->components([
Section::make(__('admin.footer.contact'))
->description(__('admin.footer.contact_hint'))
->schema([
TextInput::make('email')->label(__('admin.footer.email'))->email()->trim()->maxLength(254)
->extraInputAttributes(['dir' => 'ltr']),
TextInput::make('postal_code')->label(__('admin.footer.postal_code'))->trim()->maxLength(32)
->extraInputAttributes(['dir' => 'ltr']),
Repeater::make('phone_numbers')
->label(__('admin.footer.phone_numbers'))
->simple(TextInput::make('number')->label(__('admin.footer.phone_number'))->tel()->trim()->required()->maxLength(40)
->telRegex('/\A\+?[\p{Nd}(). -]*\p{Nd}[\p{Nd}(). -]*\z/u')
->extraInputAttributes(['dir' => 'ltr']))
->defaultItems(0)
->addActionLabel(__('admin.footer.add_phone_number'))
->columnSpanFull(),
])->columns(2),
Tabs::make(__('admin.footer.languages'))->tabs([
Tab::make(__('admin.languages.fa'))->schema($this->localizedFields('fa', 'rtl')),
Tab::make(__('admin.languages.en'))->schema($this->localizedFields('en', 'ltr')),
]),
])->statePath('data');
}
public function save(): void
{
Setting::write(Setting::STUDIO_PUBLIC_INFORMATION, $this->form->getState());
Notification::make()->title(__('admin.footer.saved'))->success()->send();
}
private function localizedFields(string $locale, string $direction): array
{
$attributes = ['lang' => $locale, 'dir' => $direction];
return [
Textarea::make("address_$locale")->label(__('admin.footer.address'))->trim()->rows(2)->maxLength(500)
->extraInputAttributes($attributes),
Textarea::make("contact_note_$locale")->label(__('admin.footer.contact_note'))->trim()->rows(2)->maxLength(500)
->helperText(__('admin.footer.contact_note_hint'))
->extraInputAttributes($attributes),
Textarea::make("licensing_$locale")->label(__('admin.footer.licensing'))->trim()->rows(3)->maxLength(3000)
->extraInputAttributes($attributes),
];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Filament\Resources;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Section;
class CatalogCopy
{
public static function fields(): array
{
return [
self::fieldsFor('fa', 'rtl', 'regex:/^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$/u'),
self::fieldsFor('en', 'ltr', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'),
];
}
private static function fieldsFor(string $locale, string $direction, string $slugRule): Section
{
$attributes = ['lang' => $locale, 'dir' => $direction];
return Section::make(__("admin.languages.$locale"))->schema([
TextInput::make("name_$locale")->label(__('admin.catalog.name'))->required()->maxLength(120)
->extraInputAttributes($attributes),
TextInput::make("slug_$locale")->label(__('admin.catalog.slug'))->required()->maxLength(120)
->rule($slugRule)->unique(ignoreRecord: true)->extraInputAttributes($attributes),
Textarea::make("description_$locale")->label(__('admin.catalog.description'))->required()->maxLength(1200)
->extraInputAttributes($attributes)->columnSpanFull(),
])->columns(2)->columnSpanFull();
}
public static function entries(): array
{
return array_map(fn (string $locale): Section => Section::make(__("admin.languages.$locale"))->schema([
TextEntry::make("name_$locale")->label(__('admin.catalog.name')),
TextEntry::make("slug_$locale")->label(__('admin.catalog.slug')),
TextEntry::make("description_$locale")->label(__('admin.catalog.description'))->columnSpanFull(),
])->columns(2)->columnSpanFull(), ['fa', 'en']);
}
}
@@ -0,0 +1,154 @@
<?php
namespace App\Filament\Resources\Collections;
use App\Filament\Resources\CatalogCopy;
use App\Filament\Resources\Collections\Pages\CreateCollection;
use App\Filament\Resources\Collections\Pages\EditCollection;
use App\Filament\Resources\Collections\Pages\ListCollections;
use App\Filament\Resources\Collections\Pages\ViewCollection;
use App\Filament\Resources\Collections\RelationManagers\DesignsRelationManager;
use App\Models\Collection;
use App\Support\CatalogImage;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\ImageEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\ForeignKeyConstraintViolationException;
class CollectionResource extends Resource
{
protected static ?string $model = Collection::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedRectangleStack;
protected static ?int $navigationSort = 20;
protected static ?string $recordTitleAttribute = 'name_fa';
public static function getModelLabel(): string
{
return __('admin.collections.singular');
}
public static function getPluralModelLabel(): string
{
return __('admin.collections.plural');
}
public static function form(Schema $schema): Schema
{
return $schema->components([
...CatalogCopy::fields(),
Section::make(__('admin.collections.cover'))->schema([
FileUpload::make('cover_upload')->label(__('admin.collections.cover'))
->disk('local')->directory('collection-originals')->visibility('private')->preventFilePathTampering()
->acceptedFileTypes(CatalogImage::MIME_TYPES)->maxSize(12288)
->helperText(fn (?Collection $record) => $record?->cover ? __('admin.collections.keep_cover') : null),
Toggle::make('remove_cover')->label(__('admin.collections.remove_cover'))
->visible(fn (?Collection $record): bool => filled($record?->cover)),
])->columnSpanFull(),
]);
}
public static function infolist(Schema $schema): Schema
{
return $schema->components([
Section::make(__('admin.collections.singular'))->schema([
ImageEntry::make('cover')->label(__('admin.collections.cover'))->imageHeight(180)
->state(fn (Collection $record) => $record->coverUrl(preview: true)),
TextEntry::make('published_at')->label(__('admin.designs.published_at'))->dateTime()->placeholder(__('admin.designs.draft')),
])->columns(2)->columnSpanFull()
->description(fn (Collection $record) => $record->designs()->exists() ? __('admin.collections.delete_blocked') : null),
...CatalogCopy::entries(),
]);
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name_fa')->label(__('admin.languages.fa'))->searchable(),
TextColumn::make('name_en')->label(__('admin.languages.en'))->searchable(),
TextColumn::make('designs_count')->counts('designs')->label(__('admin.collections.design_count')),
TextColumn::make('published_at')->label(__('admin.designs.published_at'))->dateTime()->placeholder(__('admin.designs.draft')),
])->recordUrl(fn (Collection $record) => self::getUrl('view', ['record' => $record]))->recordActions([
ViewAction::make(),
EditAction::make(),
ActionGroup::make(self::managementActions()),
]);
}
public static function managementActions(): array
{
return [
Action::make('publish')->label(__('admin.designs.publish'))->icon(Heroicon::OutlinedArrowUpTray)->color('success')
->requiresConfirmation()
->visible(fn (Collection $record) => ! $record->published_at)
->action(function (Collection $record): void {
$record->update(['published_at' => now()]);
Notification::make()->title(__('admin.collections.published'))->success()->send();
}),
Action::make('unpublish')->label(__('admin.designs.unpublish'))->icon(Heroicon::OutlinedArchiveBoxArrowDown)->color('warning')
->requiresConfirmation()->modalDescription(__('admin.collections.unpublish_description'))
->visible(fn (Collection $record) => (bool) $record->published_at)
->action(fn (Collection $record) => $record->update(['published_at' => null])),
DeleteAction::make()
->authorize(fn (Collection $record): bool => self::canDelete($record))
->failureNotificationTitle(__('admin.collections.delete_blocked'))
->using(function (Collection $record): bool {
try {
return (bool) $record->delete();
} catch (ForeignKeyConstraintViolationException) {
return false;
}
}),
];
}
public static function canDelete(Model $record): bool
{
return parent::canDelete($record) && ! $record->designs()->exists();
}
public static function prepareCover(array $data): array
{
if (filled($data['cover_upload'] ?? null)) {
$data['cover'] = app(CatalogImage::class)->prepare($data['cover_upload'], Collection::COVER_DIRECTORY, 'data.cover_upload')['path'];
} elseif ($data['remove_cover'] ?? false) {
$data['cover'] = null;
}
unset($data['cover_upload'], $data['remove_cover']);
return $data;
}
public static function getRelations(): array
{
return [DesignsRelationManager::class];
}
public static function getPages(): array
{
return [
'index' => ListCollections::route('/'),
'create' => CreateCollection::route('/create'),
'view' => ViewCollection::route('/{record}'),
'edit' => EditCollection::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Filament\Resources\Collections\Pages;
use App\Filament\Resources\Collections\CollectionResource;
use Filament\Resources\Pages\CreateRecord;
class CreateCollection extends CreateRecord
{
protected static string $resource = CollectionResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
return CollectionResource::prepareCover($data);
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\Collections\Pages;
use App\Filament\Resources\Collections\CollectionResource;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
class EditCollection extends EditRecord
{
protected static string $resource = CollectionResource::class;
protected function getHeaderActions(): array
{
return [ViewAction::make()];
}
protected function mutateFormDataBeforeSave(array $data): array
{
return CollectionResource::prepareCover($data);
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Collections\Pages;
use App\Filament\Resources\Collections\CollectionResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListCollections extends ListRecords
{
protected static string $resource = CollectionResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()];
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Collections\Pages;
use App\Filament\Resources\Collections\CollectionResource;
use Filament\Actions\EditAction;
use Filament\Resources\Pages\ViewRecord;
class ViewCollection extends ViewRecord
{
protected static string $resource = CollectionResource::class;
protected function getHeaderActions(): array
{
return [EditAction::make(), ...CollectionResource::managementActions()];
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Filament\Resources\Collections\RelationManagers;
use App\Filament\Resources\Designs\DesignResource;
use App\Models\Design;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
class DesignsRelationManager extends RelationManager
{
protected static string $relationship = 'designs';
public static function getTitle(Model $ownerRecord, string $pageClass): string
{
return __('admin.designs.plural');
}
public function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name_fa')->label(__('admin.languages.fa'))->searchable(),
TextColumn::make('name_en')->label(__('admin.languages.en'))->searchable(),
TextColumn::make('published_at')->label(__('admin.designs.published_at'))->dateTime()->placeholder(__('admin.designs.draft')),
])->recordUrl(fn (Design $record) => DesignResource::getUrl('view', ['record' => $record]));
}
}
@@ -0,0 +1,142 @@
<?php
namespace App\Filament\Resources\Designs;
use App\Filament\Resources\CatalogCopy;
use App\Filament\Resources\Designs\Pages\CreateDesign;
use App\Filament\Resources\Designs\Pages\EditDesign;
use App\Filament\Resources\Designs\Pages\ListDesigns;
use App\Filament\Resources\Designs\Pages\ViewDesign;
use App\Models\Design;
use App\Support\GarmentPreview;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\ImageEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;
class DesignResource extends Resource
{
protected static ?string $model = Design::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
protected static ?int $navigationSort = 10;
protected static ?string $recordTitleAttribute = 'name_fa';
public static function getModelLabel(): string
{
return __('admin.designs.singular');
}
public static function getPluralModelLabel(): string
{
return __('admin.designs.plural');
}
public static function form(Schema $schema): Schema
{
return $schema->components([
...CatalogCopy::fields(),
Section::make(__('admin.designs.print'))->schema([
Select::make('collection_id')->label(__('admin.designs.collection'))->relationship('collection', 'name_fa')->required(),
TextInput::make('width_cm')->label(__('admin.designs.width'))->required()->numeric()->minValue(0.1)->maxValue(100),
TextInput::make('height_cm')->label(__('admin.designs.height'))->required()->numeric()->minValue(0.1)->maxValue(100),
FileUpload::make('original_path')->label(__('admin.designs.artwork'))->required()
->disk('local')->directory('originals')->visibility('private')->preventFilePathTampering()
->acceptedFileTypes(['image/png'])->maxSize(12288)->columnSpanFull(),
Toggle::make('illustrative')->label(__('admin.catalog.illustrative')),
])->columns(2)->columnSpanFull(),
]);
}
public static function infolist(Schema $schema): Schema
{
return $schema->components([
Section::make(__('admin.designs.print'))->schema([
ImageEntry::make('artwork_path')->label(__('admin.designs.artwork'))->imageHeight(180)
->state(fn (Design $record) => $record->artwork_path
? route('studio.preview-art', ['id' => $record->id, 'file' => basename($record->artwork_path)]) : null)
->alt(fn (Design $record) => $record->name_fa)
->url(fn (?string $state) => $state, shouldOpenInNewTab: true)
->columnSpanFull(),
TextEntry::make('collection.name_fa')->label(__('admin.designs.collection')),
TextEntry::make('published_at')->label(__('admin.designs.published_at'))->dateTime()->placeholder(__('admin.designs.draft')),
TextEntry::make('width_cm')->label(__('admin.designs.width')),
TextEntry::make('height_cm')->label(__('admin.designs.height')),
TextEntry::make('page_views')->label(__('admin.dashboard.total_page_views'))
->state(fn (Design $record) => $record->dailyViews()->sum('views'))->numeric(locale: 'fa'),
IconEntry::make('illustrative')->label(__('admin.catalog.illustrative'))->boolean(),
])->columns(2)->columnSpanFull(),
...CatalogCopy::entries(),
]);
}
public static function table(Table $table): Table
{
return $table->modifyQueryUsing(fn (Builder $query) => $query->withSum('dailyViews as page_views', 'views'))->columns([
TextColumn::make('name_fa')->label(__('admin.languages.fa'))->searchable(),
TextColumn::make('name_en')->label(__('admin.languages.en'))->searchable(),
TextColumn::make('collection.name_fa')->label(__('admin.designs.collection')),
TextColumn::make('published_at')->label(__('admin.designs.published_at'))->dateTime()->placeholder(__('admin.designs.draft')),
TextColumn::make('page_views')->label(__('admin.dashboard.total_page_views'))->default(0)->numeric(locale: 'fa')->sortable(),
])->recordUrl(fn (Design $record) => self::getUrl('view', ['record' => $record]))->recordActions([
ViewAction::make(),
EditAction::make(),
ActionGroup::make(self::managementActions()),
]);
}
public static function managementActions(): array
{
return [
Action::make('preview')->label(__('admin.designs.preview'))->icon(Heroicon::OutlinedPhoto)
->url(fn (Design $record) => route('studio.preview', ['id' => $record->id, 'locale' => 'fa']))->openUrlInNewTab(),
Action::make('publish')->label(__('admin.designs.publish'))->icon(Heroicon::OutlinedArrowUpTray)->color('success')->requiresConfirmation()
->visible(fn (Design $record) => ! $record->published_at)
->action(function (Design $record): void {
if (! $record->artwork_path || ! Storage::disk('local')->exists($record->artwork_path)
|| $record->collection->published_at?->lte(now()) !== true || app(GarmentPreview::class)->options($record) === []) {
Notification::make()->title(__('admin.designs.publish_requirements'))->danger()->send();
return;
}
$record->update(['published_at' => now()]);
Notification::make()->title(__('admin.designs.published'))->success()->send();
}),
Action::make('unpublish')->label(__('admin.designs.unpublish'))->icon(Heroicon::OutlinedArchiveBoxArrowDown)->requiresConfirmation()->color('warning')
->visible(fn (Design $record) => (bool) $record->published_at)
->action(fn (Design $record) => $record->update(['published_at' => null])),
DeleteAction::make(),
];
}
public static function getPages(): array
{
return [
'index' => ListDesigns::route('/'),
'create' => CreateDesign::route('/create'),
'view' => ViewDesign::route('/{record}'),
'edit' => EditDesign::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Designs\Pages;
use App\Filament\Resources\Designs\DesignResource;
use App\Support\Artwork;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
class CreateDesign extends CreateRecord
{
protected static string $resource = DesignResource::class;
protected function handleRecordCreation(array $data): Model
{
$data['artwork_path'] = app(Artwork::class)->prepare($data['original_path']);
return parent::handleRecordCreation($data);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Filament\Resources\Designs\Pages;
use App\Filament\Resources\Designs\DesignResource;
use App\Models\Collection;
use App\Models\Design;
use App\Support\Artwork;
use App\Support\GarmentPreview;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\ValidationException;
class EditDesign extends EditRecord
{
protected static string $resource = DesignResource::class;
protected function getHeaderActions(): array
{
return [ViewAction::make()];
}
public function getSubheading(): ?string
{
return $this->getRecord()->published_at ? __('admin.designs.live_edit') : null;
}
protected function handleRecordUpdate(Model $record, array $data): Model
{
if ($record->published_at && (int) $data['collection_id'] !== (int) $record->collection_id
&& ! Collection::published()->whereKey($data['collection_id'])->exists()) {
throw ValidationException::withMessages(['data.collection_id' => __('admin.designs.choose_published_collection')]);
}
if ($record->published_at
&& ((float) $data['width_cm'] !== (float) $record->width_cm || (float) $data['height_cm'] !== (float) $record->height_cm)
&& app(GarmentPreview::class)->options(new Design($data)) === []) {
throw ValidationException::withMessages(['data.width_cm' => __('admin.designs.no_compatible_placement')]);
}
if ($data['original_path'] !== $record->original_path) {
$data['artwork_path'] = app(Artwork::class)->prepare($data['original_path']);
}
return parent::handleRecordUpdate($record, $data);
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Designs\Pages;
use App\Filament\Resources\Designs\DesignResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListDesigns extends ListRecords
{
protected static string $resource = DesignResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label(__('admin.designs.add'))];
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Designs\Pages;
use App\Filament\Resources\Designs\DesignResource;
use Filament\Actions\EditAction;
use Filament\Resources\Pages\ViewRecord;
class ViewDesign extends ViewRecord
{
protected static string $resource = DesignResource::class;
protected function getHeaderActions(): array
{
return [EditAction::make(), ...DesignResource::managementActions()];
}
}
@@ -0,0 +1,187 @@
<?php
namespace App\Filament\Resources\GarmentTemplates;
use App\Filament\Resources\GarmentTemplates\Pages\CreateGarmentTemplate;
use App\Filament\Resources\GarmentTemplates\Pages\EditGarmentTemplate;
use App\Filament\Resources\GarmentTemplates\Pages\ListGarmentTemplates;
use App\Filament\Resources\GarmentTemplates\Pages\ViewGarmentTemplate;
use App\Models\GarmentTemplate;
use App\Support\CatalogImage;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\ImageEntry;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Validation\ValidationException;
class GarmentTemplateResource extends Resource
{
protected static ?string $model = GarmentTemplate::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPhoto;
protected static ?int $navigationSort = 30;
protected static ?string $recordTitleAttribute = 'name_fa';
public static function getModelLabel(): string
{
return __('admin.garments.singular');
}
public static function getPluralModelLabel(): string
{
return __('admin.garments.plural');
}
public static function form(Schema $schema): Schema
{
return $schema->components([
Section::make(__('admin.garments.singular'))->schema([
TextInput::make('name_fa')->label(__('admin.catalog.name_fa'))->required()->maxLength(120),
TextInput::make('name_en')->label(__('admin.catalog.name_en'))->required()->maxLength(120)
->extraInputAttributes(['lang' => 'en', 'dir' => 'ltr']),
Select::make('garment')->label(__('admin.garments.garment'))->options(__('studio.garment_labels'))->required(),
Select::make('color')->label(__('admin.garments.color'))->options(__('studio.color_labels'))->required(),
Select::make('side')->label(__('admin.garments.side'))->options(__('admin.garments.sides'))->default('front')->live()->required()
->rule(fn (Get $get, ?GarmentTemplate $record): Unique => Rule::unique('garment_templates', 'side')
->where('garment', $get('garment'))->where('color', $get('color'))->ignore($record?->getKey()))
->validationMessages(['unique' => __('admin.garments.duplicate_variant')]),
Toggle::make('illustrative')->label(__('admin.catalog.illustrative'))->default(true),
FileUpload::make('photo_upload')->label(__('admin.garments.photo'))->helperText(__('admin.garments.photo_hint'))
->required(fn (?GarmentTemplate $record): bool => $record === null)->disk('local')->directory('garment-originals')
->visibility('private')->preventFilePathTampering()->acceptedFileTypes(CatalogImage::MIME_TYPES)->maxSize(12288)
->columnSpanFull(),
])->columns(2)->columnSpanFull(),
Section::make(__('admin.garments.calibration'))->schema([
TextInput::make('pixels_per_cm')->label(__('admin.garments.pixels_per_cm'))->helperText(__('admin.garments.calibration_hint'))
->required()->numeric()->minValue(0.001)->maxValue(99999.999),
Repeater::make('placements')->label(__('admin.garments.placements'))->required()->minItems(1)
->addActionLabel(__('admin.garments.add_placement'))->schema([
Select::make('placement')->label(__('admin.garments.placement'))
->options(fn (Get $get): array => self::placementOptions($get('../../side')))
->distinct()->required()->columnSpanFull(),
TextInput::make('x')->label(__('admin.garments.x'))->required()->numeric()->minValue(0)->maxValue(100),
TextInput::make('y')->label(__('admin.garments.y'))->required()->numeric()->minValue(0)->maxValue(100),
TextInput::make('max_width_cm')->label(__('admin.garments.max_width'))->required()->numeric()->minValue(0.1)->maxValue(100),
TextInput::make('max_height_cm')->label(__('admin.garments.max_height'))->required()->numeric()->minValue(0.1)->maxValue(100),
])->columns(2),
])->columnSpanFull(),
]);
}
private static function placementOptions(?string $side): array
{
$back = ['back', 'upper-back', 'lower-back'];
$labels = __('studio.placement_labels');
return $side === 'back' ? array_intersect_key($labels, array_flip($back)) : array_diff_key($labels, array_flip($back));
}
public static function infolist(Schema $schema): Schema
{
return $schema->components([
Section::make(__('admin.garments.singular'))->schema([
ImageEntry::make('photo')->label(__('admin.garments.photo'))->imageHeight(180)
->state(fn (GarmentTemplate $record) => $record->photoUrl())->columnSpanFull(),
TextEntry::make('name_fa')->label(__('admin.catalog.name_fa')),
TextEntry::make('name_en')->label(__('admin.catalog.name_en')),
TextEntry::make('garment')->label(__('admin.garments.garment'))->formatStateUsing(fn (string $state) => __("studio.garment_labels.$state")),
TextEntry::make('color')->label(__('admin.garments.color'))->formatStateUsing(fn (string $state) => __("studio.color_labels.$state")),
TextEntry::make('side')->label(__('admin.garments.side'))->formatStateUsing(fn (string $state) => __("admin.garments.sides.$state")),
IconEntry::make('illustrative')->label(__('admin.catalog.illustrative'))->boolean(),
TextEntry::make('photo_width_px')->label(__('admin.garments.photo_width')),
TextEntry::make('pixels_per_cm')->label(__('admin.garments.pixels_per_cm')),
])->columns(2)->columnSpanFull(),
RepeatableEntry::make('placements')->label(__('admin.garments.placements'))
->state(fn (GarmentTemplate $record) => self::placementRows($record->placements))
->schema([
TextEntry::make('placement')->label(__('admin.garments.placement'))
->formatStateUsing(fn (string $state) => __("studio.placement_labels.$state")),
TextEntry::make('x')->label(__('admin.garments.x')),
TextEntry::make('y')->label(__('admin.garments.y')),
TextEntry::make('max_width_cm')->label(__('admin.garments.max_width')),
TextEntry::make('max_height_cm')->label(__('admin.garments.max_height')),
])->columns(5)->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name_fa')->label(__('admin.catalog.name_fa'))->searchable(),
TextColumn::make('side')->label(__('admin.garments.side'))->formatStateUsing(fn (string $state) => __("admin.garments.sides.$state")),
TextColumn::make('pixels_per_cm')->label(__('admin.garments.pixels_per_cm')),
])->recordUrl(fn (GarmentTemplate $record) => self::getUrl('view', ['record' => $record]))
->recordActions([ViewAction::make(), EditAction::make(), DeleteAction::make()]);
}
public static function placementRows(array $placements): array
{
$rows = [];
foreach ($placements as $name => $placement) {
$rows[] = ['placement' => $name, ...$placement];
}
return $rows;
}
public static function prepareCalibration(array $data, ?GarmentTemplate $record = null): array
{
$photoWidth = $record?->photo_width_px;
$upload = $data['photo_upload'] ?? null;
if ($upload) {
$photo = app(CatalogImage::class)->prepare($upload, GarmentTemplate::PHOTO_DIRECTORY, 'data.photo_upload', square: true);
$data['photo'] = $photo['path'];
$data['photo_width_px'] = $photoWidth = $photo['width'];
}
$placements = [];
foreach ($data['placements'] as $placement) {
$anchor = $placement['placement'];
unset($placement['placement']);
foreach (['x' => 'max_width_cm', 'y' => 'max_height_cm'] as $axis => $limit) {
$availablePixels = 2 * min($placement[$axis], 100 - $placement[$axis]) * $photoWidth / 100;
if ($availablePixels < $placement[$limit] * $data['pixels_per_cm']) {
throw ValidationException::withMessages(['data.placements' => __('admin.garments.placement_outside_photo')]);
}
}
$placements[$anchor] = $placement;
}
$data['placements'] = $placements;
unset($data['photo_upload']);
return $data;
}
public static function getPages(): array
{
return [
'index' => ListGarmentTemplates::route('/'),
'create' => CreateGarmentTemplate::route('/create'),
'view' => ViewGarmentTemplate::route('/{record}'),
'edit' => EditGarmentTemplate::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Filament\Resources\GarmentTemplates\Pages;
use App\Filament\Resources\GarmentTemplates\GarmentTemplateResource;
use Filament\Resources\Pages\CreateRecord;
class CreateGarmentTemplate extends CreateRecord
{
protected static string $resource = GarmentTemplateResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
return GarmentTemplateResource::prepareCalibration($data);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Filament\Resources\GarmentTemplates\Pages;
use App\Filament\Resources\GarmentTemplates\GarmentTemplateResource;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
class EditGarmentTemplate extends EditRecord
{
protected static string $resource = GarmentTemplateResource::class;
protected function getHeaderActions(): array
{
return [ViewAction::make()];
}
protected function mutateFormDataBeforeFill(array $data): array
{
$data['placements'] = GarmentTemplateResource::placementRows($data['placements']);
return $data;
}
protected function mutateFormDataBeforeSave(array $data): array
{
return GarmentTemplateResource::prepareCalibration($data, $this->getRecord());
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\GarmentTemplates\Pages;
use App\Filament\Resources\GarmentTemplates\GarmentTemplateResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListGarmentTemplates extends ListRecords
{
protected static string $resource = GarmentTemplateResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()];
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Filament\Resources\GarmentTemplates\Pages;
use App\Filament\Resources\GarmentTemplates\GarmentTemplateResource;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Resources\Pages\ViewRecord;
class ViewGarmentTemplate extends ViewRecord
{
protected static string $resource = GarmentTemplateResource::class;
protected function getHeaderActions(): array
{
return [EditAction::make(), DeleteAction::make()];
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Filament\Widgets;
use App\Filament\Resources\Collections\CollectionResource;
use App\Filament\Resources\Designs\DesignResource;
use App\Filament\Resources\GarmentTemplates\GarmentTemplateResource;
use App\Models\Collection;
use App\Models\Design;
use App\Models\GarmentTemplate;
use Filament\Support\Icons\Heroicon;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Number;
class CatalogOverview extends StatsOverviewWidget
{
protected static ?int $sort = 10;
protected static ?bool $isLazyLoaded = false;
protected ?string $pollingInterval = null;
protected int|array|null $columns = ['default' => 2, '@xl' => 3];
protected function getHeading(): string
{
return __('admin.dashboard.overview');
}
protected function getStats(): array
{
$designs = Design::query()
->selectRaw('count(*) as total, count(*) - count(published_at) as drafts')
->selectSub(Design::visible()->selectRaw('count(*)'), 'visible')
->toBase()
->first();
return [
Stat::make(__('admin.dashboard.total_designs'), Number::format($designs->total, locale: 'fa'))
->icon(Heroicon::OutlinedSwatch)->url(DesignResource::getUrl('index')),
Stat::make(__('admin.dashboard.visible_designs'), Number::format($designs->visible, locale: 'fa'))
->icon(Heroicon::OutlinedGlobeAlt),
Stat::make(__('admin.dashboard.drafts'), Number::format($designs->drafts, locale: 'fa'))
->icon(Heroicon::OutlinedPencilSquare),
Stat::make(__('admin.dashboard.hidden_designs'), Number::format($designs->total - $designs->visible - $designs->drafts, locale: 'fa'))
->icon(Heroicon::OutlinedEyeSlash)
->description(__('admin.dashboard.hidden_description')),
Stat::make(__('admin.collections.plural'), Number::format(Collection::count(), locale: 'fa'))
->icon(Heroicon::OutlinedRectangleStack)->url(CollectionResource::getUrl('index')),
Stat::make(__('admin.garments.plural'), Number::format(GarmentTemplate::count(), locale: 'fa'))
->icon(Heroicon::OutlinedPhoto)->url(GarmentTemplateResource::getUrl('index')),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Filament\Widgets;
use App\Models\Collection;
use Filament\Widgets\BarChartWidget;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as Models;
use Illuminate\Support\Number;
use Illuminate\Support\Str;
class CollectionDesignChart extends BarChartWidget
{
private const LIMIT = 8;
protected static ?int $sort = 20;
protected static ?bool $isLazyLoaded = false;
protected ?string $pollingInterval = null;
protected ?string $maxHeight = '20rem';
/** @var Models<int, Collection>|null */
private ?Models $collections = null;
public function getHeading(): string
{
return __('admin.dashboard.collection_chart');
}
public function getDescription(): string
{
return __('admin.dashboard.chart_description', ['limit' => Number::format(self::LIMIT, locale: 'fa')]);
}
public function getEmptyStateHeading(): string
{
return __('admin.dashboard.empty_chart');
}
protected function getData(): array
{
$collections = $this->collections();
if (! $collections->max('designs_count')) {
return [];
}
return [
'labels' => $collections->map(fn (Collection $collection): string => Str::limit($collection->name_fa, 22))->all(),
'datasets' => [
[
'label' => __('admin.dashboard.on_site'),
'data' => $collections->pluck('visible_count')->all(),
'backgroundColor' => '#ad263f',
'maxBarThickness' => 24,
],
[
'label' => __('admin.dashboard.off_site'),
'data' => $collections->map(fn (Collection $collection): int => $collection->designs_count - $collection->visible_count)->all(),
'backgroundColor' => '#90827b',
'maxBarThickness' => 24,
],
],
];
}
public function getChartAssistiveContent(): string
{
return $this->collections()->map(fn (Collection $collection): string => __('admin.dashboard.chart_row', [
'name' => $collection->name_fa,
'visible' => Number::format($collection->visible_count, locale: 'fa'),
'hidden' => Number::format($collection->designs_count - $collection->visible_count, locale: 'fa'),
]))->implode(' ');
}
protected function getOptions(): array
{
return [
'indexAxis' => 'y',
'locale' => 'fa-IR',
'scales' => [
'x' => ['stacked' => true, 'reverse' => true, 'beginAtZero' => true, 'ticks' => ['precision' => 0]],
'y' => ['stacked' => true, 'position' => 'right', 'ticks' => ['autoSkip' => false]],
],
'plugins' => [
'legend' => ['rtl' => true, 'textDirection' => 'rtl'],
'tooltip' => ['rtl' => true, 'textDirection' => 'rtl'],
],
];
}
/** @return Models<int, Collection> */
private function collections(): Models
{
return $this->collections ??= Collection::query()
->withCount(['designs', 'designs as visible_count' => fn (Builder $query) => $query->visible()])
->orderByDesc('designs_count')
->orderBy('id')
->limit(self::LIMIT)
->get();
}
}
@@ -0,0 +1,88 @@
<?php
namespace App\Filament\Widgets;
use App\Models\DesignDailyView;
use Filament\Widgets\LineChartWidget;
use Illuminate\Support\Number;
use IntlDateFormatter;
class DesignTrafficChart extends LineChartWidget
{
private const DAYS = 14;
protected static ?int $sort = 25;
protected static ?bool $isLazyLoaded = false;
protected ?string $pollingInterval = null;
protected ?string $maxHeight = '20rem';
public function getHeading(): string
{
return __('admin.dashboard.traffic');
}
public function getDescription(): string
{
return __('admin.dashboard.traffic_summary', [
'views' => Number::format(array_sum($this->getCachedData()['datasets'][0]['data']), locale: 'fa'),
'days' => Number::format(self::DAYS, locale: 'fa'),
]);
}
public function getChartAssistiveContent(): string
{
$chart = $this->getCachedData();
return collect($chart['labels'])->map(fn (string $date, int $index): string => __('admin.dashboard.traffic_row', [
'date' => $date,
'views' => Number::format($chart['datasets'][0]['data'][$index], locale: 'fa'),
]))->implode(' ');
}
protected function getData(): array
{
$today = DesignDailyView::today();
$start = $today->subDays(self::DAYS - 1);
$dailyViews = DesignDailyView::query()
->whereBetween('viewed_on', [$start->toDateString(), $today->toDateString()])
->groupBy('viewed_on')
->selectRaw('viewed_on, sum(views) as total')
->pluck('total', 'viewed_on');
$formatter = new IntlDateFormatter('fa_IR@calendar=persian', IntlDateFormatter::NONE, IntlDateFormatter::NONE,
DesignDailyView::TIMEZONE, IntlDateFormatter::TRADITIONAL, 'd MMM');
$labels = [];
$counts = [];
for ($date = $start; $date <= $today; $date = $date->addDay()) {
$labels[] = $formatter->format($date);
$counts[] = (int) $dailyViews->get($date->toDateString(), 0);
}
return [
'labels' => $labels,
'datasets' => [[
'label' => __('admin.dashboard.daily_views'),
'data' => $counts,
'fill' => true,
]],
];
}
protected function getOptions(): array
{
return [
'locale' => 'fa-IR',
'scales' => [
'x' => ['reverse' => true, 'ticks' => ['maxTicksLimit' => 5, 'maxRotation' => 0]],
'y' => ['position' => 'right', 'beginAtZero' => true, 'suggestedMax' => 1, 'ticks' => ['precision' => 0]],
],
'plugins' => [
'legend' => ['display' => false],
'tooltip' => ['rtl' => true, 'textDirection' => 'rtl'],
],
];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Filament\Widgets;
use App\Filament\Resources\Designs\DesignResource;
use App\Models\Design;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
class RecentDesigns extends TableWidget
{
protected static ?int $sort = 30;
protected static ?bool $isLazyLoaded = false;
protected int|string|array $columnSpan = 'full';
public function table(Table $table): Table
{
return $table
->heading(__('admin.dashboard.recent_designs'))
->query(Design::query()->with('collection')->withSum('dailyViews as page_views', 'views')
->latest('updated_at')->orderByDesc('id')->limit(6))
->paginated(false)
->columns([
TextColumn::make('name_fa')->label(__('admin.designs.singular'))
->description(fn (Design $record): string => $record->collection->name_fa)
->wrap(),
TextColumn::make('updated_at')->label(__('admin.dashboard.last_updated'))
->since()->dateTimeTooltip(),
TextColumn::make('page_views')->label(__('admin.dashboard.total_page_views'))->default(0)->numeric(locale: 'fa'),
])
->recordUrl(fn (Design $record) => DesignResource::getUrl('view', ['record' => $record]))
->emptyStateHeading(__('admin.dashboard.no_designs'));
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
+193
View File
@@ -0,0 +1,193 @@
<?php
namespace App\Http\Controllers;
use App\Models\Collection;
use App\Models\Design;
use App\Models\DesignDailyView;
use App\Models\GarmentTemplate;
use App\Models\LocalizedContent;
use App\Support\GarmentPreview;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Storage;
use XMLWriter;
class StudioController extends Controller
{
public function home()
{
$collections = Collection::published()->orderBy('id')->get();
$featured = Design::visible()->orderBy('id')->first();
return $this->page('home', 'home', compact('collections', 'featured'));
}
public function catalog()
{
$collections = Collection::published()->orderBy('id')->get();
return $this->page('catalog', 'catalog', compact('collections'));
}
public function collection(string $slug)
{
$collection = $this->find(Collection::published(), $slug);
$designs = $collection->designs()->visible()->get();
return $this->page('collection', 'collection', compact('collection', 'designs'), $collection);
}
public function design(string $slug, GarmentPreview $preview)
{
$design = $this->find(Design::visible()->with('collection'), $slug);
$templates = $preview->options($design);
if (request()->isMethod('GET')) {
$designId = $design->id;
$date = DesignDailyView::today()->toDateString();
defer(fn () => DesignDailyView::recordView($designId, $date));
}
return $this->page('design', 'design', compact('design', 'templates'), $design);
}
public function guides()
{
return $this->page('guide', 'guides', [
'title' => __('guide.title'),
'description' => __('guide.description'),
]);
}
public function artwork(int $id, string $file)
{
$design = Design::visible()->findOrFail($id);
return $this->serveWebp($design->artwork_path, $file);
}
public function collectionCover(int $id, string $file)
{
$collection = Collection::published()->findOrFail($id);
return $this->serveWebp($collection->cover, $file, Collection::COVER_DIRECTORY);
}
public function draftCollectionCover(int $id, string $file)
{
abort_unless(request()->user()->canAccessPanel(Filament::getPanel('studio')), 403);
$collection = Collection::findOrFail($id);
return $this->serveWebp($collection->cover, $file, Collection::COVER_DIRECTORY, private: true);
}
public function garmentPhoto(int $id, string $file)
{
$template = GarmentTemplate::findOrFail($id);
return $this->serveWebp($template->photo, $file, GarmentTemplate::PHOTO_DIRECTORY);
}
public function draft(int $id, string $locale, GarmentPreview $preview)
{
abort_unless(request()->user()->canAccessPanel(Filament::getPanel('studio')), 403);
app()->setLocale($locale);
$design = Design::with('collection')->findOrFail($id);
$templates = $preview->options($design);
$draft = true;
return response()->view('studio.design', [
'design' => $design,
'templates' => $templates,
'draft' => $draft,
'locale' => $locale,
'alternateLocale' => $locale === 'fa' ? 'en' : 'fa',
'alternates' => [
'fa' => route('studio.preview', ['id' => $id, 'locale' => 'fa']),
'en' => route('studio.preview', ['id' => $id, 'locale' => 'en']),
],
'title' => $design->text('name'),
'description' => $design->text('description'),
])->header('Cache-Control', 'private, no-store');
}
public function draftArt(int $id, string $file)
{
abort_unless(request()->user()->canAccessPanel(Filament::getPanel('studio')), 403);
return $this->serveWebp(Design::findOrFail($id)->artwork_path, $file, private: true);
}
private function serveWebp(?string $path, string $file, string $directory = 'artwork', bool $private = false)
{
abort_unless($path && $path === "$directory/$file", 404);
$disk = Storage::disk('local');
abort_unless($disk->exists($path), 404);
$response = response()->file($disk->path($path), [
'Content-Type' => 'image/webp',
'Cache-Control' => $private ? 'private, no-store' : 'public, max-age=300',
'X-Content-Type-Options' => 'nosniff',
]);
return $private ? $response->setPrivate() : $response;
}
public function sitemap()
{
$urls = [];
foreach (['fa', 'en'] as $locale) {
foreach (['home', 'catalog', 'guides'] as $page) {
$urls[] = route("$locale.$page");
}
}
foreach ([
'collection' => Collection::published(),
'design' => Design::visible(),
] as $page => $query) {
foreach ($query->get() as $record) {
foreach (['fa', 'en'] as $locale) {
$urls[] = route("$locale.$page", ['slug' => $record->text('slug', $locale)]);
}
}
}
$xml = new XMLWriter;
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElementNs(null, 'urlset', 'http://www.sitemaps.org/schemas/sitemap/0.9');
foreach ($urls as $url) {
$xml->startElement('url');
$xml->writeElement('loc', $url);
$xml->endElement();
}
$xml->endDocument();
return response($xml->outputMemory(), 200, ['Content-Type' => 'application/xml; charset=UTF-8']);
}
private function find($query, string $slug): LocalizedContent
{
return $query->where('slug_'.app()->getLocale(), $slug)->firstOrFail();
}
private function page(string $view, string $page, array $data, ?LocalizedContent $record = null)
{
$locale = app()->getLocale();
$alternates = [];
foreach (['fa', 'en'] as $language) {
$alternates[$language] = route("$language.$page", $record ? ['slug' => $record->text('slug', $language)] : []);
}
return view("studio.$view", [
...$data,
'locale' => $locale,
'alternateLocale' => $locale === 'fa' ? 'en' : 'fa',
'alternates' => $alternates,
'title' => $record?->text('name') ?? $data['title'] ?? __("studio.titles.$page"),
'description' => $record?->text('description') ?? $data['description'] ?? __('studio.description'),
]);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SetStudioLocale
{
public function handle(Request $request, Closure $next, string $locale): Response
{
app()->setLocale($locale);
return $next($request);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Collection extends LocalizedContent
{
public const COVER_DIRECTORY = 'collection-covers';
public function designs(): HasMany
{
return $this->hasMany(Design::class);
}
public function coverUrl(bool $preview = false): ?string
{
if (! $this->cover) {
return null;
}
if (! str_starts_with($this->cover, self::COVER_DIRECTORY.'/')) {
return asset($this->cover);
}
return route($preview ? 'studio.collection-cover' : 'collection.cover', [
'id' => $this->id,
'file' => basename($this->cover),
]);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Design extends LocalizedContent
{
protected function casts(): array
{
return [...parent::casts(), 'illustrative' => 'boolean'];
}
public function collection(): BelongsTo
{
return $this->belongsTo(Collection::class);
}
public function dailyViews(): HasMany
{
return $this->hasMany(DesignDailyView::class);
}
#[Scope]
protected function visible(Builder $query): void
{
$query->published()->whereHas('collection', fn (Builder $collection) => $collection->published())
->whereNotNull('artwork_path');
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class DesignDailyView extends Model
{
public const TIMEZONE = 'Asia/Tehran';
public $timestamps = false;
public static function today(): CarbonImmutable
{
return now(self::TIMEZONE)->toImmutable()->startOfDay();
}
public static function recordView(int $designId, string $date): void
{
static::query()->upsert([
['design_id' => $designId, 'viewed_on' => $date, 'views' => 1],
], ['design_id', 'viewed_on'], ['views' => DB::raw('design_daily_views.views + 1')]);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class GarmentTemplate extends Model
{
public const PHOTO_DIRECTORY = 'garment-photos';
protected $guarded = ['id'];
protected function casts(): array
{
return [
'placements' => 'array',
'illustrative' => 'boolean',
];
}
public function photoUrl(): string
{
if (! str_starts_with($this->photo, self::PHOTO_DIRECTORY.'/')) {
return asset($this->photo);
}
return route('garment.photo', ['id' => $this->id, 'file' => basename($this->photo)]);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
abstract class LocalizedContent extends Model
{
protected $guarded = ['id'];
protected function casts(): array
{
return ['published_at' => 'datetime'];
}
public function text(string $field, ?string $locale = null): string
{
return $this->getAttribute($field.'_'.($locale ?? app()->getLocale()));
}
#[Scope]
protected function published(Builder $query): void
{
$query->where('published_at', '<=', now());
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
public const STUDIO_PUBLIC_INFORMATION = 'studio.public_information';
protected $primaryKey = 'key';
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = ['key', 'value'];
protected function casts(): array
{
return ['value' => 'json'];
}
public static function read(string $key, mixed $default = null): mixed
{
$setting = static::query()->find($key);
return $setting === null ? $default : $setting->value;
}
public static function write(string $key, mixed $value): void
{
static::query()->updateOrCreate(['key' => $key], ['value' => $value]);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable implements FilamentUser
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
public function canAccessPanel(Panel $panel): bool
{
return (bool) $this->is_staff;
}
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Providers;
use App\Models\Setting;
use Illuminate\Contracts\View\View as ViewContract;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
View::composer('studio.footer', function (ViewContract $view): void {
$view->with('studioInformation', Setting::read(Setting::STUDIO_PUBLIC_INFORMATION, []));
});
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Providers\Filament;
use App\Http\Middleware\SetStudioLocale;
use Filament\FontProviders\LocalFontProvider;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Assets\Css;
use Filament\View\PanelsRenderHook;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class StudioPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->default()
->id('studio')
->path('studio')
->login()
->profile(isSimple: false)
->topNavigation()
->brandName(fn () => __('admin.brand'))
->brandLogo(fn () => view('filament.studio-logo'))
->brandLogoHeight('2.375rem')
->favicon(fn () => asset('porint/favicon.png'))
->font('Vazirmatn', fn () => asset('fonts/studio-font.css'), LocalFontProvider::class)
->assets([Css::make('porint-wordmark', asset('porint/wordmark.css'))])
->renderHook(PanelsRenderHook::HEAD_END, fn () => view('filament.dashboard-charts'), scopes: Dashboard::class)
->renderHook(PanelsRenderHook::SCRIPTS_BEFORE, fn () => view('filament.request-messages'))
->colors([
'primary' => '#ad263f',
])
->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
->pages([
Dashboard::class,
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets')
->middleware([
SetStudioLocale::class.':fa',
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
], isPersistent: true);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class Artwork
{
public function prepare(string $original): string
{
$disk = Storage::disk('local');
$path = $disk->path($original);
$info = is_file($path) ? @getimagesize($path) : false;
if (! $info || $info[2] !== IMAGETYPE_PNG || max($info[0], $info[1]) > 4096 || filesize($path) > 12 * 1024 * 1024) {
throw $this->invalid('requirements');
}
$source = @imagecreatefrompng($path);
if (! $source) {
throw $this->invalid('unreadable');
}
imagepalettetotruecolor($source);
imagealphablending($source, false);
imagesavealpha($source, true);
$artwork = imagecropauto($source, IMG_CROP_TRANSPARENT);
if (! $artwork) {
throw $this->invalid('empty');
}
$scale = min(1, 1200 / max(imagesx($artwork), imagesy($artwork)));
$resized = imagescale($artwork, max(1, (int) round(imagesx($artwork) * $scale)), max(1, (int) round(imagesy($artwork) * $scale)));
if (! $resized) {
throw $this->invalid('resize_failed');
}
imagealphablending($resized, false);
imagesavealpha($resized, true);
$file = 'artwork/'.Str::uuid().'.webp';
$disk->makeDirectory('artwork');
if (! imagewebp($resized, $disk->path($file), 91) || ! $disk->exists($file) || $disk->size($file) === 0) {
throw $this->invalid('write_failed');
}
return $file;
}
private function invalid(string $reason): ValidationException
{
return ValidationException::withMessages(['data.original_path' => __('admin.artwork.'.$reason)]);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class CatalogImage
{
public const MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
public function prepare(string $original, string $directory, string $field, bool $square = false): array
{
$disk = Storage::disk('local');
$source = $disk->path($original);
$info = is_file($source) ? @getimagesize($source) : false;
if (! $info || ! in_array($info['mime'], self::MIME_TYPES, true)
|| max($info[0], $info[1]) > 4096 || filesize($source) > 12 * 1024 * 1024) {
throw ValidationException::withMessages([$field => __('admin.catalog.invalid_image')]);
}
if ($square && $info[0] !== $info[1]) {
throw ValidationException::withMessages([$field => __('admin.garments.square_image')]);
}
$image = @imagecreatefromstring(file_get_contents($source));
if (! $image) {
throw ValidationException::withMessages([$field => __('admin.artwork.unreadable')]);
}
imagepalettetotruecolor($image);
imagealphablending($image, false);
imagesavealpha($image, true);
$file = $directory.'/'.Str::uuid().'.webp';
$disk->makeDirectory($directory);
if (! imagewebp($image, $disk->path($file), 90) || ! $disk->exists($file) || $disk->size($file) === 0) {
throw ValidationException::withMessages([$field => __('admin.artwork.write_failed')]);
}
return ['path' => $file, 'width' => $info[0]];
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Support;
use App\Models\Design;
use App\Models\GarmentTemplate;
class GarmentPreview
{
public function options(Design $design): array
{
return GarmentTemplate::orderBy('id')->get()->map(function (GarmentTemplate $template) use ($design): array {
$placements = [];
foreach ($template->placements as $key => $placement) {
if ($design->width_cm <= $placement['max_width_cm'] && $design->height_cm <= $placement['max_height_cm']) {
$placements[$key] = ['x' => $placement['x'], 'y' => $placement['y']];
}
}
return [
'name' => $template->{'name_'.app()->getLocale()},
'garment' => $template->garment,
'color' => $template->color,
'side' => $template->side,
'photo' => $template->photoUrl(),
'width' => 100 * $design->width_cm * $template->pixels_per_cm / $template->photo_width_px,
'placements' => $placements,
'illustrative' => $template->illustrative,
];
})->filter(fn (array $template) => $template['placements'] !== [])->values()->all();
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace App\Support;
use IntlChar;
class PhoneNumber
{
public static function dialString(string $number): string
{
$digits = preg_replace_callback('/\p{Nd}/u', fn (array $match): string => (string) IntlChar::digit($match[0]), $number);
return preg_replace('/[^+0-9]/', '', $digits);
}
}