70ca2fa74a
Client sees only Total. Salary is calculated from salary_base = client_price
× (1 − margin/100). Margin never appears in customer-facing surfaces (PDF,
tracking JSON, portal).
Terminology: "marjă internă" — internal profit margin. NOT VAT/TVA. Never
called NDS/TVA anywhere in the code to avoid confusion with real Moldova
tax reporting (Doc 19/1C integration).
== Configuration ==
Fallback chain (in MarginResolver::resolve):
1. WorkOrder.override_margin_pct — per-Fișă for special contracts/VIP
2. User.internal_margin_pct — per-mechanic (main setting)
3. Company.settings.default_internal_margin_pct — tenant default
4. 0.0 — no margin
Example (mechanic Andrei with 20% margin):
User enters price_per_hour = 250 for 1h diagnosis
→ total = 250 (what client sees, goes into PDF)
→ salary_base = 250 × 0.80 = 200 (what mechanic gets salaried on)
→ applied_margin_pct = 20 (frozen)
If admin later changes Andrei's margin to 40%, the row's salary_base does
NOT change — history is immutable. Only new rows use the new margin.
Solves the retroactive-recompute problem for closed payroll periods.
== salary_base freeze semantics ==
wo_works gains 2 columns:
salary_base decimal(10,2) nullable
applied_margin_pct decimal(5,2) nullable
Frozen at save time by WorkOrderWork::saving hook. Recomputes only if
total OR master_id changes (i.e., someone actively edits the price or
reassigns the mechanic — in those cases we WANT the salary_base to
follow). Legacy rows (before this feature) have null salary_base;
PayrollCalculator falls back to total for them.
== PayrollCalculator uses salary_base ==
Previously: sum(wo_works.total) × works_pct → gave the mechanic a cut
of the price INCLUDING margin.
Now: sum(salary_base ?? total) × works_pct → the cut is from the
labor rate excluding margin.
Impact: for a 250 lei diagnosis at 20% margin with 50% payroll cut, the
mechanic gets 200 × 50% = 100 lei (was 250 × 50% = 125 lei). The shop
keeps the 50 lei margin regardless of the payroll %.
== RBAC gate ==
New permission FINANCE_VIEW_INTERNAL_MARGIN. Assigned to owner + admin +
manager + accountant in seed matrix. Not granted to mechanic,
receptionist, or viewer — those roles never see the "Bază salariu"
disclosure line or the margin % fields.
== UI surfaces ==
UserResource — new "Salariu & marjă" section (visible only with
FINANCE_VIEW_INTERNAL_MARGIN):
- Tarif orar (MDL)
- Marjă internă (%) with helper text explaining the -X% semantics
- Placeholder tells manager the exact formula
WorkOrderResource form — new override_margin_pct field in the "Plată &
total" section, gated by same permission. Helper text: "Doar pentru
cazuri speciale. Lasă gol pentru a folosi marja mecanicului."
WorksRelationManager (WO edit page) — Total column now shows a gray
subtitle line "Bază salariu: 200.00 MDL · marjă 20%" ONLY for users
with FINANCE_VIEW_INTERNAL_MARGIN. Everyone else sees just Total.
== Contract tests: NO leak ==
InternalMarginTest verifies with black-box grepping that:
- WorkOrderPdfService::generate output contains NONE of
{salary_base, internal_margin, applied_margin_pct, marja intern,
Bază salariu}
- /api/track/{token} JSON payload contains NONE of the same terms
- wo_parts table has no salary_base column (margin ONLY on labor)
- Changing mechanic.internal_margin_pct after work is saved does NOT
rewrite the historical salary_base (frozen)
- WO override wins over mechanic margin (contract-priced clients)
- Fallback chain: WO → mechanic → company default → 0
== Suite ==
298 passed (828 assertions). Was 285. +13 InternalMarginTest.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
220 lines
10 KiB
PHP
220 lines
10 KiB
PHP
<?php
|
||
|
||
namespace App\Filament\Tenant\Resources;
|
||
|
||
use App\Filament\Tenant\Resources\UserResource\Pages;
|
||
use App\Filament\Tenant\Resources\UserResource\RelationManagers;
|
||
use App\Models\Tenant\User;
|
||
use Filament\Forms;
|
||
use Filament\Resources\Resource;
|
||
use Filament\Schemas\Schema;
|
||
use Filament\Actions;
|
||
use Filament\Schemas;
|
||
use Filament\Tables;
|
||
use Filament\Tables\Table;
|
||
use Illuminate\Support\Facades\Hash;
|
||
|
||
class UserResource extends Resource
|
||
{
|
||
protected static ?string $model = User::class;
|
||
|
||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-user-group';
|
||
|
||
protected static ?string $navigationLabel = 'Utilizatori';
|
||
|
||
protected static string|\UnitEnum|null $navigationGroup = 'Admin';
|
||
|
||
protected static ?string $modelLabel = 'utilizator';
|
||
|
||
protected static ?string $pluralModelLabel = 'utilizatori';
|
||
|
||
protected static ?int $navigationSort = 80;
|
||
|
||
public static function canViewAny(): bool
|
||
{
|
||
return auth()->user()?->canDo(\App\Auth\Permissions::ADMIN_USERS_VIEW) ?? false;
|
||
}
|
||
|
||
public static function canCreate(): bool
|
||
{
|
||
return auth()->user()?->canDo(\App\Auth\Permissions::ADMIN_USERS_MANAGE) ?? false;
|
||
}
|
||
|
||
public static function canDelete($record): bool
|
||
{
|
||
return auth()->user()?->canDo(\App\Auth\Permissions::ADMIN_USERS_MANAGE) ?? false;
|
||
}
|
||
|
||
public static function form(Schema $schema): Schema
|
||
{
|
||
return $schema->components([
|
||
Schemas\Components\Section::make('Identitate')
|
||
->columns(2)
|
||
->schema([
|
||
Forms\Components\TextInput::make('name')->label('Nume')->required()->maxLength(120),
|
||
Forms\Components\TextInput::make('email')->email()->required()->maxLength(120),
|
||
Forms\Components\TextInput::make('phone')->tel()->maxLength(40),
|
||
Forms\Components\Select::make('locale')
|
||
->options(['ro' => 'Română', 'ru' => 'Русский', 'en' => 'English'])
|
||
->default('ro'),
|
||
]),
|
||
Schemas\Components\Section::make('Acces')
|
||
->columns(2)
|
||
->schema([
|
||
Forms\Components\Select::make('role')
|
||
->label('Rol primar')
|
||
->options(\App\Auth\Permissions::roleLabels())
|
||
->required()
|
||
->default('mechanic')
|
||
->helperText('Rolul principal — sincronizat automat cu drepturile RBAC.'),
|
||
Forms\Components\Select::make('status')
|
||
->options(['active' => 'Activ', 'inactive' => 'Inactiv', 'blocked' => 'Blocat'])
|
||
->default('active')
|
||
->required(),
|
||
Forms\Components\TextInput::make('password')
|
||
->label('Parolă')
|
||
->password()
|
||
->required(fn (string $context) => $context === 'create')
|
||
->dehydrated(fn ($state) => filled($state))
|
||
->dehydrateStateUsing(fn ($state) => Hash::make($state))
|
||
->minLength(6)
|
||
->helperText('La editare lasă gol pentru a păstra parola actuală.'),
|
||
Forms\Components\Select::make('roles_picked')
|
||
->label('Roluri suplimentare')
|
||
->multiple()
|
||
->options(\App\Auth\Permissions::roleLabels())
|
||
->afterStateHydrated(function ($component, $record) {
|
||
if ($record) $component->state($record->roles->pluck('name')->all());
|
||
})
|
||
->dehydrated(false)
|
||
->columnSpanFull()
|
||
->helperText('Roluri suplimentare peste rolul primar — drepturile se cumulează.'),
|
||
]),
|
||
Schemas\Components\Section::make('Salariu & marjă')
|
||
->description('Configurează procentele pentru calcul salariu. Marja internă (nu TVA) se scade din prețul de manoperă pentru a determina baza salariului.')
|
||
->columns(2)
|
||
->visible(fn () => auth()->user()?->canDo(\App\Auth\Permissions::FINANCE_VIEW_INTERNAL_MARGIN) ?? false)
|
||
->schema([
|
||
Forms\Components\TextInput::make('hourly_rate')
|
||
->label('Tarif orar (MDL)')
|
||
->numeric()
|
||
->step(0.01)
|
||
->placeholder('Ex: 100'),
|
||
Forms\Components\TextInput::make('internal_margin_pct')
|
||
->label('Marjă internă (%)')
|
||
->numeric()
|
||
->step(0.01)
|
||
->minValue(0)
|
||
->maxValue(90)
|
||
->placeholder('Ex: 20 pentru +20%')
|
||
->helperText('Doar la manopere (proprii + subcontract). Baza salariu = preț client × (1 − marjă/100). Lasă gol pentru a folosi valoarea implicită a companiei.'),
|
||
]),
|
||
Schemas\Components\Section::make('Securitate')
|
||
->columns(2)
|
||
->schema([
|
||
Forms\Components\Placeholder::make('mfa_status')
|
||
->label('Autentificare 2FA')
|
||
->content(fn ($record) => $record && $record->hasTwoFactorEnabled() ? '✓ Activat (TOTP)' : '✗ Dezactivat'),
|
||
Forms\Components\Placeholder::make('last_login')
|
||
->label('Ultima autentificare')
|
||
->content(fn ($record) => $record?->last_login_at?->diffForHumans() ?? '—'),
|
||
]),
|
||
]);
|
||
}
|
||
|
||
public static function table(Table $table): Table
|
||
{
|
||
return $table
|
||
->columns([
|
||
Tables\Columns\TextColumn::make('name')->searchable()->sortable(),
|
||
Tables\Columns\TextColumn::make('email')->searchable()->copyable(),
|
||
Tables\Columns\TextColumn::make('phone')->placeholder('—'),
|
||
Tables\Columns\TextColumn::make('role')
|
||
->formatStateUsing(fn ($state) => \App\Auth\Permissions::roleLabels()[$state] ?? $state)
|
||
->badge(),
|
||
Tables\Columns\IconColumn::make('app_authentication_secret')
|
||
->label('2FA')
|
||
->boolean()
|
||
->getStateUsing(fn ($record) => $record->hasTwoFactorEnabled())
|
||
->trueIcon('heroicon-o-shield-check')
|
||
->trueColor('success')
|
||
->falseIcon('heroicon-o-shield-exclamation')
|
||
->falseColor('warning'),
|
||
Tables\Columns\TextColumn::make('active_sessions')
|
||
->label('Sesiuni')
|
||
->getStateUsing(fn ($record) => \Illuminate\Support\Facades\DB::table('sessions')->where('user_id', $record->id)->count())
|
||
->badge()
|
||
->color(fn ($state) => $state > 0 ? 'success' : 'gray')
|
||
->toggleable(),
|
||
Tables\Columns\TextColumn::make('permission_overrides_count')
|
||
->counts('permissionOverrides')
|
||
->label('Excepții')
|
||
->badge()
|
||
->color('warning')
|
||
->toggleable(isToggledHiddenByDefault: true),
|
||
Tables\Columns\TextColumn::make('status')
|
||
->badge()
|
||
->colors([
|
||
'success' => ['active'],
|
||
'warning' => ['inactive'],
|
||
'danger' => ['blocked'],
|
||
]),
|
||
Tables\Columns\TextColumn::make('last_login_at')->dateTime()->placeholder('—')->toggleable(),
|
||
Tables\Columns\TextColumn::make('created_at')->date()->sortable()->toggleable(isToggledHiddenByDefault: true),
|
||
])
|
||
->filters([
|
||
Tables\Filters\SelectFilter::make('role')->options([
|
||
'admin' => 'Admin', 'manager' => 'Manager', 'receptionist' => 'Recepție',
|
||
'mechanic' => 'Mecanic', 'parts_manager' => 'Magazie', 'accountant' => 'Contabil', 'marketer' => 'Marketing',
|
||
]),
|
||
Tables\Filters\SelectFilter::make('status')->options([
|
||
'active' => 'Activ', 'inactive' => 'Inactiv', 'blocked' => 'Blocat',
|
||
]),
|
||
])
|
||
->actions([
|
||
Actions\EditAction::make(),
|
||
Actions\Action::make('force_logout')
|
||
->label('Force logout')
|
||
->icon('heroicon-o-arrow-right-on-rectangle')
|
||
->color('warning')
|
||
->visible(fn ($record) => \Illuminate\Support\Facades\DB::table('sessions')->where('user_id', $record->id)->exists())
|
||
->requiresConfirmation()
|
||
->modalDescription('Va deconecta utilizatorul pe toate device-urile.')
|
||
->action(function ($record) {
|
||
$n = \Illuminate\Support\Facades\DB::table('sessions')->where('user_id', $record->id)->delete();
|
||
\Filament\Notifications\Notification::make()->title("$n sesiuni revoke-uite")->success()->send();
|
||
}),
|
||
Actions\Action::make('reset_2fa')
|
||
->label('Resetează 2FA')
|
||
->icon('heroicon-o-shield-exclamation')
|
||
->color('warning')
|
||
->visible(fn ($record) => $record && $record->hasTwoFactorEnabled())
|
||
->requiresConfirmation()
|
||
->modalDescription('Dezactivează 2FA pentru acest utilizator. Va trebui să re-configureze TOTP la următoarea autentificare.')
|
||
->action(function ($record) {
|
||
$record->saveAppAuthenticationSecret(null);
|
||
$record->saveAppAuthenticationRecoveryCodes(null);
|
||
\Filament\Notifications\Notification::make()->title('2FA resetat')->success()->send();
|
||
}),
|
||
Actions\DeleteAction::make(),
|
||
])
|
||
->defaultSort('created_at', 'desc');
|
||
}
|
||
|
||
public static function getRelations(): array
|
||
{
|
||
return [
|
||
RelationManagers\PermissionOverridesRelationManager::class,
|
||
];
|
||
}
|
||
|
||
public static function getPages(): array
|
||
{
|
||
return [
|
||
'index' => Pages\ListUsers::route('/'),
|
||
'create' => Pages\CreateUser::route('/create'),
|
||
'edit' => Pages\EditUser::route('/{record}/edit'),
|
||
];
|
||
}
|
||
}
|