feat: granular permissions, export backup, user/role management
Some checks failed
Tests / PHP 8.3 (push) Has been cancelled
Tests / PHP 8.4 (push) Has been cancelled
Tests / PHP 8.5 (push) Has been cancelled

- PermissionSeeder: 29 permissions with role mapping (admin/manager/staff)
- Policies updated to use hasPermissionTo() instead of hasRole()
- ExportBackup command: JSON per-table backup with chunk processing
- UserResource: CRUD users with role assignment (admin only)
- RoleResource: CRUD roles with permission assignment (admin only)
- UserPolicy + RolePolicy: admin-only access control
- ImportCskh: detailed skip logging with color in dry-run mode
- Widgets: permission-based visibility checks
- Tests: 8/8 pass (21 assertions)
This commit is contained in:
2026-05-02 04:47:10 +00:00
parent 7c5055075b
commit 3a8db5cae6
40 changed files with 1804 additions and 440 deletions

View File

@@ -0,0 +1,146 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ExportBackup extends Command
{
protected $signature = 'app:export-backup
{--path= : Output directory path (default: storage/app/backups)}
{--tables= : Comma-separated list of tables to export (default: all)}
{--pretty : Pretty-print JSON output}';
protected $description = 'Export database backup to JSON files (one file per table)';
private array $stats = [];
public function handle(): int
{
$path = $this->option('path') ?? storage_path('app/backups');
$pretty = $this->option('pretty') ?? false;
$tablesFilter = $this->option('tables')
? array_map('trim', explode(',', $this->option('tables')))
: null;
if (! File::isDirectory($path)) {
File::makeDirectory($path, 0755, true);
}
$timestamp = now()->format('Y-m-d_His');
$backupDir = "{$path}/backup_{$timestamp}";
File::makeDirectory($backupDir, 0755, true);
$this->info("Backup directory: {$backupDir}");
$this->newLine();
$tables = $this->getTables();
if ($tablesFilter) {
$tables = array_filter($tables, fn ($t) => in_array($t, $tablesFilter));
}
$this->info("Exporting " . count($tables) . " tables...");
$this->newLine();
$bar = $this->output->createProgressBar(count($tables));
$bar->start();
$totalRows = 0;
foreach ($tables as $table) {
$count = $this->exportTable($table, $backupDir, $pretty);
$this->stats[$table] = $count;
$totalRows += $count;
$bar->advance();
}
$bar->finish();
$this->newLine(2);
// Write manifest
$manifest = [
'created_at' => now()->toIso8601String(),
'database' => config('database.default'),
'tables' => $this->stats,
'total_rows' => $totalRows,
];
File::put("{$backupDir}/manifest.json", json_encode($manifest, JSON_PRETTY_PRINT));
$this->printSummary($backupDir, $totalRows);
return self::SUCCESS;
}
private function getTables(): array
{
$driver = config('database.default');
if ($driver === 'sqlite') {
$results = DB::select("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
return array_map(fn ($r) => $r->name, $results);
}
return DB::getDoctrineSchemaManager()->listTableNames();
}
private function exportTable(string $table, string $backupDir, bool $pretty): int
{
$filename = "{$backupDir}/{$table}.json";
$count = 0;
$handle = fopen($filename, 'w');
fwrite($handle, "[\n");
$first = true;
DB::table($table)->orderBy('id')->chunk(500, function ($rows) use ($handle, &$count, &$first, $pretty) {
foreach ($rows as $row) {
if (! $first) {
fwrite($handle, ",\n");
}
$first = false;
$data = (array) $row;
$json = $pretty
? json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
: json_encode($data, JSON_UNESCAPED_UNICODE);
fwrite($handle, $json);
$count++;
}
});
fwrite($handle, "\n]\n");
fclose($handle);
return $count;
}
private function printSummary(string $backupDir, int $totalRows): void
{
$rows = [];
foreach ($this->stats as $table => $count) {
$rows[] = [$table, $count];
}
$rows[] = ['<bold>TOTAL</bold>', "<bold>{$totalRows}</bold>"];
$this->table(['Table', 'Rows'], $rows);
$size = File::size($backupDir);
$sizeFormatted = $this->formatBytes($size);
$this->info("Backup size: {$sizeFormatted}");
$this->info("Location: {$backupDir}");
}
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
}

View File

@@ -31,6 +31,11 @@ class ImportCskh extends Command
private int $statsFeedbacks = 0;
private int $statsInteractions = 0;
private int $statsSkipped = 0;
private int $statsSkippedEmptyCode = 0;
private int $statsSkippedNumericCode = 0;
private int $statsSkippedHeaderRow = 0;
private int $statsSkippedEmptyCustomer = 0;
private array $skippedRowDetails = [];
public function handle(): int
{
@@ -63,8 +68,9 @@ class ImportCskh extends Command
foreach ($rows as $row) {
$rowCount++;
if ($this->isMetaRow($row)) {
$this->statsSkipped++;
$metaReason = $this->getMetaRowReason($row);
if ($metaReason !== null) {
$this->recordSkip($rowCount, $metaReason, $row);
$bar->advance();
continue;
@@ -73,7 +79,7 @@ class ImportCskh extends Command
$chunk[] = $row;
if (count($chunk) >= $chunkSize) {
$this->processChunk($chunk, $dryRun);
$this->processChunk($chunk, $dryRun, $rowCount);
$chunk = [];
}
@@ -81,7 +87,7 @@ class ImportCskh extends Command
}
if (! empty($chunk)) {
$this->processChunk($chunk, $dryRun);
$this->processChunk($chunk, $dryRun, $rowCount);
}
$bar->finish();
@@ -92,44 +98,78 @@ class ImportCskh extends Command
}
private function isMetaRow(array $row): bool
{
return $this->getMetaRowReason($row) !== null;
}
private function getMetaRowReason(array $row): ?string
{
$code = $row['Mã căn hộ'] ?? '';
if (empty($code) || is_numeric($code)) {
return true;
if (empty($code)) {
return 'empty_code';
}
if (is_numeric($code)) {
return 'numeric_code';
}
if ($code === 'Ngày TT' || $code === 'Tình trạng' || $code === 'Tên DN') {
return true;
return 'header_row';
}
return false;
return null;
}
private function processChunk(array $rows, bool $dryRun): void
private function recordSkip(int $rowNum, string $reason, array $row): void
{
$this->statsSkipped++;
match ($reason) {
'empty_code' => $this->statsSkippedEmptyCode++,
'numeric_code' => $this->statsSkippedNumericCode++,
'header_row' => $this->statsSkippedHeaderRow++,
default => null,
};
$code = $row['Mã căn hộ'] ?? '';
$this->skippedRowDetails[] = [
'row' => $rowNum,
'reason' => $reason,
'code' => $code,
];
}
private function processChunk(array $rows, bool $dryRun, int $currentRowNum): void
{
if ($dryRun) {
foreach ($rows as $row) {
$this->processRow($row, true);
foreach ($rows as $i => $row) {
$this->processRow($row, true, $currentRowNum - count($rows) + $i + 1);
}
return;
}
DB::transaction(function () use ($rows): void {
foreach ($rows as $row) {
$this->processRow($row, false);
DB::transaction(function () use ($rows, $currentRowNum): void {
foreach ($rows as $i => $row) {
$this->processRow($row, false, $currentRowNum - count($rows) + $i + 1);
}
});
}
private function processRow(array $row, bool $dryRun): void
private function processRow(array $row, bool $dryRun, int $rowNum): void
{
$productCode = trim($row['Mã căn hộ'] ?? '');
$customerName = trim($row['Họ tên KH'] ?? '');
if (empty($productCode) || empty($customerName)) {
$this->statsSkipped++;
$this->statsSkippedEmptyCustomer++;
$this->skippedRowDetails[] = [
'row' => $rowNum,
'reason' => 'empty_customer',
'code' => $productCode,
];
return;
}
@@ -433,6 +473,10 @@ class ImportCskh extends Command
[
['Total rows in file', $totalRows],
['Skipped (meta/empty)', $this->statsSkipped],
[' ├─ Empty code (row trống)', $this->statsSkippedEmptyCode],
[' ├─ Numeric code (hàng tổng)', $this->statsSkippedNumericCode],
[' ├─ Header row (tiêu đề)', $this->statsSkippedHeaderRow],
[' └─ Empty customer name', $this->statsSkippedEmptyCustomer],
[$mode . 'New Products', $this->statsProducts],
[$mode . 'New Customers', $this->statsCustomers],
[$mode . 'New Contracts', $this->statsContracts],
@@ -442,5 +486,56 @@ class ImportCskh extends Command
[$mode . 'New Interactions', $this->statsInteractions],
]
);
if ($dryRun && ! empty($this->skippedRowDetails)) {
$this->newLine();
$this->warn('=== Chi tiết các dòng bị bỏ qua ===');
$this->newLine();
$reasonLabels = [
'empty_code' => '<fg=red>Trống mã căn hộ</>',
'numeric_code' => '<fg=yellow>Hàng tổng (numeric)</>',
'header_row' => '<fg=cyan>Hàng tiêu đề</>',
'empty_customer' => '<fg=magenta>Trống tên KH</>',
];
$reasonColors = [
'empty_code' => 'red',
'numeric_code' => 'yellow',
'header_row' => 'cyan',
'empty_customer' => 'magenta',
];
$grouped = [];
foreach ($this->skippedRowDetails as $detail) {
$grouped[$detail['reason']][] = $detail;
}
foreach ($grouped as $reason => $details) {
$color = $reasonColors[$reason] ?? 'white';
$label = $reasonLabels[$reason] ?? $reason;
$count = count($details);
$this->line(" <fg={$color};options=bold>{$label}</> — {$count} dòng:");
$showDetails = array_slice($details, 0, 30);
$rowNumbers = array_column($showDetails, 'row');
$codes = array_column($showDetails, 'code');
$chunks = array_chunk($rowNumbers, 15);
foreach ($chunks as $chunk) {
$this->line(" <fg={$color}>Rows: " . implode(', ', $chunk) . "</>");
}
if ($count > 30) {
$this->line(" <fg=gray>... và " . ($count - 30) . " dòng nữa</>");
}
$this->newLine();
}
$this->line('<fg=gray>Gợi ý: Các dòng "Empty customer name" thường là dòng trống trong Excel chỉ có mã căn hộ nhưng không có dữ liệu khác.</>');
$this->line('<fg=gray>Chúng được bỏ qua vì thiếu thông tin bắt buộc (Họ tên KH).</>');
}
}
}

View File

@@ -36,7 +36,7 @@ class EditFeedback extends EditRecord
->label('Transfer Department')
->icon('heroicon-o-arrows-right-left')
->color('warning')
->visible(fn (): bool => auth()->user()->hasRole(['admin', 'manager']))
->visible(fn (): bool => auth()->user()->hasPermissionTo('transfer-department'))
->form([
Select::make('to_department_id')
->label('Target Department')
@@ -106,7 +106,7 @@ class EditFeedback extends EditRecord
->label('Close Ticket')
->icon('heroicon-o-check-circle')
->color('success')
->visible(fn (): bool => $this->getRecord()->status !== 'closed' && auth()->user()->hasRole(['admin', 'manager']))
->visible(fn (): bool => $this->getRecord()->status !== 'closed' && auth()->user()->hasPermissionTo('close-ticket'))
->requiresConfirmation()
->modalHeading('Close Ticket')
->modalDescription('Bạn có chắc muốn đóng phiếu này? Hành động này KHÔNG thể hoàn tác.')

View File

@@ -53,7 +53,7 @@ class InteractionsRelationManager extends RelationManager
Select::make('new_status')
->label('New Status')
->options(fn (): array => auth()->user()->hasRole(['admin', 'manager'])
->options(fn (): array => auth()->user()->hasPermissionTo('close-ticket')
? ['pending' => 'Pending', 'processing' => 'Processing', 'resolved' => 'Resolved', 'closed' => 'Closed']
: ['pending' => 'Pending', 'processing' => 'Processing', 'resolved' => 'Resolved'],
)

View File

@@ -11,6 +11,7 @@ use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
class FeedbackForm
@@ -19,18 +20,22 @@ class FeedbackForm
{
return $schema
->components([
Section::make('Feedback Information')
Section::make('Customer & Product')
->description('Select the customer and their associated product')
->icon('heroicon-o-user-group')
->schema([
Select::make('customer_id')
->relationship('customer', 'name')
->searchable()
->required()
->live(),
->live()
->columnSpan(1),
Toggle::make('is_general')
->label('General feedback (not related to a product)')
->default(false)
->live(),
->live()
->columnSpan(1),
Select::make('customer_product_id')
->label('Product')
@@ -57,7 +62,7 @@ class FeedbackForm
->live(),
Select::make('contract_id')
->label('Hợp đồng')
->label('Contract')
->visible(fn ($get): bool => ! $get('is_general') && filled($get('customer_product_id')))
->options(function ($get): array {
$customerProductId = $get('customer_product_id');
@@ -102,48 +107,46 @@ class FeedbackForm
})
->nullable()
->searchable(),
])
->columns(2),
Section::make('Feedback Details')
->description('Describe the customer feedback')
->icon('heroicon-o-chat-bubble-left-right')
->schema([
Select::make('feedback_channel_id')
->relationship('feedbackChannel', 'name')
->required()
->preload(),
->preload()
->columnSpan(1),
TextInput::make('title')
->required()
->maxLength(255),
->maxLength(255)
->columnSpan(1),
Textarea::make('content')
->required()
->rows(6)
->columnSpanFull(),
Select::make('attachment_collection')
->label('Attachment Collection')
->options([
'general' => 'General',
'proof_of_resolution' => 'Proof of Resolution',
'customer_evidence' => 'Customer Evidence',
])
->default('general'),
FileUpload::make('attachments')
->label('Attachments')
->multiple()
->disk('local')
->directory('feedback-attachments')
->columnSpanFull()
->dehydrated(false),
Select::make('tags')
->relationship('tags', 'name')
->multiple()
->preload()
->columnSpanFull()
->createOptionForm([
TextInput::make('name')->required(),
TextInput::make('slug')->required(),
ColorPicker::make('color')->default('#3b82f6'),
]),
])
->columns(2),
Section::make('Assignment & Status')
->description('Assign handler and set initial status')
->icon('heroicon-o-arrow-path-rounded-square')
->schema([
Select::make('status')
->options([
'pending' => 'Pending',
@@ -152,22 +155,50 @@ class FeedbackForm
'closed' => 'Closed',
])
->default('pending')
->required(),
->required()
->columnSpan(1),
Select::make('assigned_to')
->relationship('assignedTo', 'name')
->searchable()
->nullable(),
->nullable()
->columnSpan(1),
Select::make('current_department_id')
->label('Department')
->options(Department::pluck('name', 'id')->toArray())
->searchable()
->nullable(),
->nullable()
->columnSpan(1),
Toggle::make('is_escalated')
->label('Escalated')
->visible(fn (): bool => auth()->user()?->hasRole(['admin', 'manager']) ?? false),
->visible(fn (): bool => auth()->user()?->hasPermissionTo('close-ticket') ?? false)
->columnSpan(1),
])
->columns(2),
Section::make('Attachments')
->description('Upload files related to this feedback')
->icon('heroicon-o-paper-clip')
->schema([
Select::make('attachment_collection')
->label('Collection')
->options([
'general' => 'General',
'proof_of_resolution' => 'Proof of Resolution',
'customer_evidence' => 'Customer Evidence',
])
->default('general')
->columnSpan(1),
FileUpload::make('attachments')
->label('Files')
->multiple()
->disk('local')
->directory('feedback-attachments')
->columnSpan(1)
->dehydrated(false),
])
->columns(2),
]);

View File

@@ -16,16 +16,28 @@ class FeedbackTable
{
return $table
->columns([
TextColumn::make('id')
->label('#')
->sortable()
->weight('bold')
->color('primary'),
TextColumn::make('title')
->searchable()
->sortable(),
->sortable()
->weight('semibold')
->limit(40),
TextColumn::make('customer.name')
->searchable()
->sortable(),
TextColumn::make('customerProduct.product.name')
->label('Product')
->placeholder('General')
->sortable(),
->sortable()
->toggleable(),
TextColumn::make('contract.type')
->label('Contract')
->badge()
@@ -38,17 +50,17 @@ class FeedbackTable
})
->placeholder('-')
->toggleable(),
TextColumn::make('feedbackChannel.name')
->label('Channel')
->formatStateUsing(fn ($state, $record) => sprintf(
'<span style="display:inline-block;background:%s;color:#fff;padding:2px 10px;border-radius:9999px;font-size:0.75rem;">%s</span>',
$record->feedbackChannel?->color ?: '#6b7280',
e($state)
))
->html(),
->badge()
->color('gray'),
TextColumn::make('tags.name')
->badge()
->separator(','),
->separator(',')
->toggleable(),
TextColumn::make('status')
->badge()
->color(fn(string $state): string => match ($state) {
@@ -58,20 +70,28 @@ class FeedbackTable
'closed' => 'gray',
default => 'gray',
}),
TextColumn::make('currentDepartment.name')
->label('Department')
->badge()
->color('info')
->toggleable(),
TextColumn::make('assignedTo.name')
->label('Assigned To')
->toggleable(),
IconColumn::make('is_escalated')
->label('Escalated')
->boolean()
->toggleable(),
TextColumn::make('created_at')
->dateTime()
->label('Created')
->since()
->sortable()
->toggleable(),
->toggleable()
->color('secondary'),
])
->filters([
SelectFilter::make('status')

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\RoleResource;
use Filament\Resources\Pages\CreateRecord;
use Spatie\Permission\Models\Permission;
class CreateRole extends CreateRecord
{
protected static string $resource = RoleResource::class;
protected function afterCreate(): void
{
$record = $this->record;
$permissionNames = $this->data['permissions'] ?? [];
if (! empty($permissionNames)) {
$record->syncPermissions($permissionNames);
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\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(),
];
}
protected function afterSave(): void
{
$record = $this->record;
$permissionNames = $this->data['permissions'] ?? [];
$record->syncPermissions($permissionNames);
}
protected function mutateFormDataBeforeFill(array $data): array
{
$role = $this->record;
$data['permissions'] = $role->permissions->pluck('name')->toArray();
return $data;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\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(),
];
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Roles;
use App\Filament\Resources\Roles\Pages\CreateRole;
use App\Filament\Resources\Roles\Pages\EditRole;
use App\Filament\Resources\Roles\Pages\ListRoles;
use App\Filament\Resources\Roles\Schemas\RoleForm;
use App\Filament\Resources\Roles\Tables\RolesTable;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Spatie\Permission\Models\Role;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedShieldCheck;
protected static ?string $pluralLabel = 'Roles';
protected static ?int $navigationSort = 6;
protected static ?string $recordTitleAttribute = 'name';
public static function getNavigationGroup(): ?string
{
return 'Management';
}
public static function form(Schema $schema): Schema
{
return RoleForm::configure($schema);
}
public static function table(Table $table): Table
{
return RolesTable::configure($table);
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => ListRoles::route('/'),
'create' => CreateRole::route('/create'),
'edit' => EditRole::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Filament\Resources\Roles\Schemas;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
use Filament\Schemas\Components\Section;
use Spatie\Permission\Models\Permission;
class RoleForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make()
->schema([
TextInput::make('name')
->label('Role Name')
->required()
->maxLength(255)
->unique(ignoreRecord: true),
]),
Section::make('Permissions')
->description('Chọn quyền cho role này')
->schema([
CheckboxList::make('permissions')
->label('')
->options(fn () => Permission::orderBy('name')->pluck('name', 'name')->toArray())
->columns(4)
->columnSpanFull(),
]),
]);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Filament\Resources\Roles\Tables;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class RolesTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('id')
->label('#')
->sortable(),
TextColumn::make('name')
->label('Role Name')
->searchable()
->sortable()
->badge()
->color(fn (string $state): string => match ($state) {
'admin' => 'danger',
'manager' => 'warning',
'staff' => 'info',
default => 'gray',
}),
TextColumn::make('permissions_count')
->label('Permissions')
->counts('permissions')
->badge()
->color('primary'),
TextColumn::make('users_count')
->label('Users')
->counts('users')
->badge()
->color('success'),
TextColumn::make('created_at')
->dateTime('d/m/Y H:i')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('id', 'asc')
->filters([
//
])
->recordActions([
EditAction::make(),
])
->bulkActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
]),
]);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use Filament\Resources\Pages\CreateRecord;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
protected function afterCreate(): void
{
$record = $this->record;
$role = $record->role;
// Assign the primary role
$record->syncRoles([$role]);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use Filament\Resources\Pages\EditRecord;
class EditUser extends EditRecord
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
\Filament\Actions\DeleteAction::make(),
];
}
protected function afterSave(): void
{
$record = $this->record;
$role = $record->role;
// Sync the primary role
$record->syncRoles([$role]);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;
class ListUsers extends ListRecords
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
public function getTabs(): array
{
return [
'all' => Tab::make(),
'admin' => Tab::make()
->modifyQueryUsing(fn (Builder $query) => $query->where('role', 'admin'))
->badge(fn () => static::getResource()::getModel()::where('role', 'admin')->count()),
'manager' => Tab::make()
->modifyQueryUsing(fn (Builder $query) => $query->where('role', 'manager'))
->badge(fn () => static::getResource()::getModel()::where('role', 'manager')->count()),
'staff' => Tab::make()
->modifyQueryUsing(fn (Builder $query) => $query->where('role', 'staff'))
->badge(fn () => static::getResource()::getModel()::where('role', 'staff')->count()),
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Filament\Resources\Users\Schemas;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
use Spatie\Permission\Models\Role;
class UserForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('name')
->required()
->maxLength(255),
TextInput::make('email')
->email()
->required()
->maxLength(255)
->unique(ignoreRecord: true),
TextInput::make('password')
->password()
->revealable()
->required(fn (string $operation): bool => $operation === 'create')
->dehydrateStateUsing(fn (?string $state): ?string => filled($state) ? bcrypt($state) : null)
->dehydrated(fn (?string $state): bool => filled($state))
->maxLength(255)
->columnSpanFull(),
Select::make('role')
->label('Role')
->options(Role::pluck('name', 'name')->toArray())
->required()
->searchable(),
]);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Filament\Resources\Users\Tables;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class UsersTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('id')
->label('#')
->sortable(),
TextColumn::make('name')
->searchable()
->sortable(),
TextColumn::make('email')
->searchable()
->sortable(),
TextColumn::make('role')
->badge()
->color(fn (string $state): string => match ($state) {
'admin' => 'danger',
'manager' => 'warning',
'staff' => 'info',
default => 'gray',
}),
TextColumn::make('created_at')
->dateTime('d/m/Y H:i')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('id', 'asc')
->filters([
//
])
->recordActions([
EditAction::make(),
])
->headerActions([
//
])
->bulkActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
]),
]);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Users;
use App\Filament\Resources\Users\Pages\CreateUser;
use App\Filament\Resources\Users\Pages\EditUser;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\Schemas\UserForm;
use App\Filament\Resources\Users\Tables\UsersTable;
use App\Models\User;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;
protected static ?string $pluralLabel = 'Users';
protected static ?int $navigationSort = 5;
protected static ?string $recordTitleAttribute = 'name';
public static function getNavigationGroup(): ?string
{
return 'Management';
}
public static function form(Schema $schema): Schema
{
return UserForm::configure($schema);
}
public static function table(Table $table): Table
{
return UsersTable::configure($table);
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => ListUsers::route('/'),
'create' => CreateUser::route('/create'),
'edit' => EditUser::route('/{record}/edit'),
];
}
}

View File

@@ -17,7 +17,7 @@ class AvgProcessingTimeWidget extends BaseWidget
->whereNotNull('assigned_to')
->whereNotNull('updated_at');
if ($user->hasRole('manager')) {
if ($user->hasRole('manager') && ! $user->hasRole('admin')) {
$deptIds = Department::where('manager_id', $user->id)->pluck('id');
$query->whereIn('current_department_id', $deptIds);
}
@@ -33,27 +33,38 @@ class AvgProcessingTimeWidget extends BaseWidget
$escalatedCount = (clone $query)->where('is_escalated', true)->count();
$avgDisplay = $avgMinutes ? round($avgMinutes) . ' min' : 'N/A';
$avgDescription = $avgMinutes
? 'Avg time from creation to resolution'
: 'No resolved tickets yet';
return [
Stat::make('Resolved Tickets', (string) $totalResolved)
->description('Total resolved/closed tickets')
->color('success'),
->descriptionIcon('heroicon-m-check-circle')
->color('success')
->chart([7, 3, 4, 5, 6, 8, $totalResolved]),
Stat::make('Avg Processing Time', $avgMinutes ? round($avgMinutes) . ' min' : 'N/A')
->description('Average time from creation to resolution')
->color('warning'),
Stat::make('Avg Processing Time', $avgDisplay)
->description($avgDescription)
->descriptionIcon('heroicon-m-clock')
->color('info'),
Stat::make('Pending Tickets', (string) $totalPending)
->description('Still in progress')
->color('danger'),
->descriptionIcon('heroicon-m-arrow-path')
->color('warning')
->chart([3, 5, 4, 6, 5, 4, $totalPending]),
Stat::make('Escalated', (string) $escalatedCount)
->description('Tickets marked as escalated')
->color('gray'),
->descriptionIcon('heroicon-m-exclamation-triangle')
->color('danger'),
];
}
public static function canView(): bool
{
return auth()->user()?->hasRole(['admin', 'manager']) ?? false;
return auth()->user()?->hasPermissionTo('view-dashboard-widgets') ?? false;
}
}

View File

@@ -10,6 +10,8 @@ class HandlerPerformanceWidget extends ChartWidget
{
protected ?string $heading = 'Avg Processing Time by Handler';
protected ?string $description = 'Average time from ticket creation to resolution, broken down by handler.';
protected int|string|array $columnSpan = 'full';
protected function getType(): string
@@ -25,7 +27,7 @@ class HandlerPerformanceWidget extends ChartWidget
->whereIn('status', ['resolved', 'closed'])
->whereNotNull('assigned_to');
if ($user->hasRole('manager')) {
if ($user->hasRole('manager') && ! $user->hasRole('admin')) {
$deptIds = Department::where('manager_id', $user->id)->pluck('id');
$query->whereIn('current_department_id', $deptIds);
}
@@ -40,12 +42,37 @@ class HandlerPerformanceWidget extends ChartWidget
$labels = $handlers->map(fn ($h) => $h->assignedTo?->name ?? 'Unknown')->toArray();
$data = $handlers->map(fn ($h) => round($h->avg_minutes, 1))->toArray();
// Generate gradient colors based on performance
$maxMinutes = max($data) ?: 1;
$colors = collect($data)->map(function ($minutes) use ($maxMinutes) {
$ratio = $minutes / $maxMinutes;
if ($ratio > 0.8) {
return 'rgba(220, 38, 38, 0.8)'; // Red for slow
} elseif ($ratio > 0.5) {
return 'rgba(217, 119, 6, 0.8)'; // Amber for medium
}
return 'rgba(26, 86, 219, 0.8)'; // Blue for fast
})->toArray();
$borderColors = collect($data)->map(function ($minutes) use ($maxMinutes) {
$ratio = $minutes / $maxMinutes;
if ($ratio > 0.8) {
return 'rgb(220, 38, 38)';
} elseif ($ratio > 0.5) {
return 'rgb(217, 119, 6)';
}
return 'rgb(26, 86, 219)';
})->toArray();
return [
'datasets' => [
[
'label' => 'Avg Time (minutes)',
'data' => $data,
'backgroundColor' => '#3b82f6',
'backgroundColor' => $colors,
'borderColor' => $borderColors,
'borderWidth' => 1,
'borderRadius' => 6,
],
],
'labels' => $labels,
@@ -54,6 +81,6 @@ class HandlerPerformanceWidget extends ChartWidget
public static function canView(): bool
{
return auth()->user()?->hasRole(['admin', 'manager']) ?? false;
return auth()->user()?->hasPermissionTo('view-dashboard-widgets') ?? false;
}
}

View File

@@ -20,7 +20,7 @@ class ResolvedTicketsWidget extends BaseWidget
Feedback::query()
->where('status', 'resolved')
->when(
auth()->user()->hasRole('manager'),
auth()->user()->hasRole('manager') && ! auth()->user()->hasRole('admin'),
function ($q) {
$deptIds = Department::where('manager_id', auth()->id())->pluck('id');
return $q->whereIn('current_department_id', $deptIds);
@@ -30,30 +30,47 @@ class ResolvedTicketsWidget extends BaseWidget
->columns([
TextColumn::make('id')
->label('#')
->sortable(),
->sortable()
->weight('bold')
->color('primary'),
TextColumn::make('title')
->label('Ticket')
->searchable()
->url(fn (Feedback $record): string => FeedbackResource::getUrl('edit', ['record' => $record])),
->weight('semibold')
->url(fn (Feedback $record): string => FeedbackResource::getUrl('edit', ['record' => $record]))
->color('primary'),
TextColumn::make('customer.name')
->label('Customer')
->searchable(),
TextColumn::make('customerProduct.product.name')
->label('Product')
->placeholder('General'),
TextColumn::make('assignedTo.name')
->label('Handler'),
TextColumn::make('currentDepartment.name')
->label('Department'),
->label('Department')
->badge()
->color('info'),
TextColumn::make('updated_at')
->label('Resolved Date')
->dateTime('d/m/Y')
->sortable(),
->label('Resolved')
->since()
->sortable()
->color('secondary'),
])
->defaultSort('updated_at', 'desc')
->heading('Tickets Awaiting Closure (Resolved)')
->description('Tickets that have been resolved and are pending manager review for closure.');
->heading('Tickets Awaiting Closure')
->description('Tickets that have been resolved and are pending manager review for closure.')
->paginated([5]);
}
public static function canView(): bool
{
return auth()->user()?->hasRole(['admin', 'manager']) ?? false;
return auth()->user()?->hasPermissionTo('view-dashboard-widgets') ?? false;
}
}

View File

@@ -9,27 +9,27 @@ class ContractPolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-contract');
}
public function view(User $user, Contract $contract): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-contract');
}
public function create(User $user): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('create-contract');
}
public function update(User $user, Contract $contract): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('update-contract');
}
public function delete(User $user, Contract $contract): bool
{
return $user->hasRole('admin');
return $user->hasPermissionTo('delete-contract');
}
public function restore(User $user, Contract $contract): bool

View File

@@ -9,27 +9,27 @@ class CustomerPolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-customer');
}
public function view(User $user, Customer $customer): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-customer');
}
public function create(User $user): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('create-customer');
}
public function update(User $user, Customer $customer): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('update-customer');
}
public function delete(User $user, Customer $customer): bool
{
return $user->hasRole('admin');
return $user->hasPermissionTo('delete-customer');
}
public function restore(User $user, Customer $customer): bool

View File

@@ -9,36 +9,36 @@ class FeedbackChannelPolicy
{
public function viewAny(User $user): bool
{
return in_array($user->role, ['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-channel');
}
public function view(User $user, FeedbackChannel $feedbackChannel): bool
public function view(User $user, FeedbackChannel $channel): bool
{
return in_array($user->role, ['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-channel');
}
public function create(User $user): bool
{
return in_array($user->role, ['admin', 'manager']);
return $user->hasPermissionTo('create-channel');
}
public function update(User $user, FeedbackChannel $feedbackChannel): bool
public function update(User $user, FeedbackChannel $channel): bool
{
return in_array($user->role, ['admin', 'manager']);
return $user->hasPermissionTo('update-channel');
}
public function delete(User $user, FeedbackChannel $feedbackChannel): bool
public function delete(User $user, FeedbackChannel $channel): bool
{
return $user->role === 'admin';
return $user->hasPermissionTo('delete-channel');
}
public function restore(User $user, FeedbackChannel $feedbackChannel): bool
public function restore(User $user, FeedbackChannel $channel): bool
{
return $user->role === 'admin';
return $user->hasRole('admin');
}
public function forceDelete(User $user, FeedbackChannel $feedbackChannel): bool
public function forceDelete(User $user, FeedbackChannel $channel): bool
{
return $user->role === 'admin';
return $user->hasRole('admin');
}
}

View File

@@ -9,27 +9,27 @@ class FeedbackPolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-feedback');
}
public function view(User $user, Feedback $feedback): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-feedback');
}
public function create(User $user): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('create-feedback');
}
public function update(User $user, Feedback $feedback): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('update-feedback');
}
public function delete(User $user, Feedback $feedback): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('delete-feedback');
}
public function restore(User $user, Feedback $feedback): bool

View File

@@ -9,27 +9,27 @@ class ProductPolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-product');
}
public function view(User $user, Product $product): bool
{
return $user->hasRole(['admin', 'manager', 'staff']);
return $user->hasPermissionTo('view-product');
}
public function create(User $user): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('create-product');
}
public function update(User $user, Product $product): bool
{
return $user->hasRole(['admin', 'manager']);
return $user->hasPermissionTo('update-product');
}
public function delete(User $user, Product $product): bool
{
return $user->hasRole('admin');
return $user->hasPermissionTo('delete-product');
}
public function restore(User $user, Product $product): bool

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Policies;
use App\Models\User;
use Spatie\Permission\Models\Role;
class RolePolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole('admin');
}
public function view(User $user, Role $role): bool
{
return $user->hasRole('admin');
}
public function create(User $user): bool
{
return $user->hasRole('admin');
}
public function update(User $user, Role $role): bool
{
return $user->hasRole('admin');
}
public function delete(User $user, Role $role): bool
{
return $user->hasRole('admin') && ! in_array($role->name, ['admin', 'manager', 'staff']);
}
public function restore(User $user, Role $role): bool
{
return $user->hasRole('admin');
}
public function forceDelete(User $user, Role $role): bool
{
return $user->hasRole('admin') && ! in_array($role->name, ['admin', 'manager', 'staff']);
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Policies;
use App\Models\User;
class UserPolicy
{
public function viewAny(User $user): bool
{
return $user->hasRole('admin');
}
public function view(User $user, User $model): bool
{
return $user->hasRole('admin');
}
public function create(User $user): bool
{
return $user->hasRole('admin');
}
public function update(User $user, User $model): bool
{
return $user->hasRole('admin');
}
public function delete(User $user, User $model): bool
{
return $user->hasRole('admin') && $model->id !== $user->id;
}
public function restore(User $user, User $model): bool
{
return $user->hasRole('admin');
}
public function forceDelete(User $user, User $model): bool
{
return $user->hasRole('admin') && $model->id !== $user->id;
}
}

View File

@@ -33,17 +33,18 @@ class AdminPanelProvider extends PanelProvider
->path('admin')
->login()
->brandName('AfterSales CRM')
->topNavigation()
->sidebarCollapsibleOnDesktop()
->colors([
'primary' => '#0058be',
'secondary' => '#585f6c',
'gray' => '#585f6c',
'success' => '#10b981',
'warning' => '#f59e0b',
'danger' => '#ba1a1a',
'info' => '#3b82f6',
'primary' => '#1a56db',
'secondary' => '#64748b',
'gray' => '#64748b',
'success' => '#059669',
'warning' => '#d97706',
'danger' => '#dc2626',
'info' => '#2563eb',
])
->font('Inter')
->favicon(asset('favicon.svg'))
->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
->pages([
@@ -55,9 +56,11 @@ class AdminPanelProvider extends PanelProvider
])
->navigationGroups([
NavigationGroup::make()
->label('Customer Care'),
->label('Customer Care')
->icon('heroicon-o-chat-bubble-left-right'),
NavigationGroup::make()
->label('Management'),
->label('Management')
->icon('heroicon-o-cog-6-tooth'),
])
->middleware([
EncryptCookies::class,

View File

@@ -22,7 +22,7 @@ class ClosingService
]);
}
if ($actor->hasRole('staff')) {
if (! $actor->hasPermissionTo('close-ticket')) {
throw new HttpException(403, __('Chỉ lãnh đạo cấp phòng mới có quyền đóng phiếu.'));
}