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>
240 lines
11 KiB
PHP
240 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Tenant\Resources;
|
|
|
|
use App\Filament\Tenant\Resources\WorkOrderResource\Pages;
|
|
use App\Filament\Tenant\Resources\WorkOrderResource\RelationManagers;
|
|
use App\Models\Tenant\Client;
|
|
use App\Models\Tenant\User;
|
|
use App\Models\Tenant\Vehicle;
|
|
use App\Models\Tenant\WorkOrder;
|
|
use App\Tenancy\TenantManager;
|
|
use Filament\Actions;
|
|
use Filament\Forms;
|
|
use Filament\Resources\Resource;
|
|
use Filament\Schemas;
|
|
use Filament\Schemas\Components\Utilities\Get;
|
|
use Filament\Schemas\Schema;
|
|
use Filament\Tables;
|
|
use Filament\Tables\Table;
|
|
|
|
class WorkOrderResource extends Resource
|
|
{
|
|
protected static ?string $model = WorkOrder::class;
|
|
|
|
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-wrench-screwdriver';
|
|
|
|
protected static ?string $navigationLabel = 'Fișe lucru';
|
|
|
|
protected static string|\UnitEnum|null $navigationGroup = 'Service';
|
|
|
|
protected static ?string $modelLabel = 'fișă';
|
|
|
|
protected static ?string $pluralModelLabel = 'fișe lucru';
|
|
|
|
protected static ?int $navigationSort = 30;
|
|
|
|
public static function getGloballySearchableAttributes(): array
|
|
{
|
|
return ['number', 'complaint', 'diagnosis', 'vehicle.plate', 'vehicle.vin', 'client.name', 'client.phone'];
|
|
}
|
|
|
|
public static function getGlobalSearchResultTitle(\Illuminate\Database\Eloquent\Model $record): string
|
|
{
|
|
return '#' . ($record->number ?? $record->id) . ' · ' . ($record->vehicle?->plate ?? '?');
|
|
}
|
|
|
|
public static function getGlobalSearchResultDetails(\Illuminate\Database\Eloquent\Model $record): array
|
|
{
|
|
return [
|
|
'Client' => $record->client?->name ?? '—',
|
|
'Status' => $record->status,
|
|
'Total' => number_format((float) $record->total, 2),
|
|
];
|
|
}
|
|
|
|
public static function form(Schema $schema): Schema
|
|
{
|
|
return $schema->components([
|
|
Schemas\Components\Section::make('Antet')
|
|
->columns(3)
|
|
->schema([
|
|
Forms\Components\TextInput::make('number')
|
|
->label('Nr.')
|
|
->disabled()
|
|
->dehydrated(false)
|
|
->placeholder('Generat automat'),
|
|
Forms\Components\DatePicker::make('opened_at')
|
|
->label('Deschis')
|
|
->default(today())
|
|
->required(),
|
|
Forms\Components\Select::make('status')
|
|
->options(WorkOrder::STATUSES)
|
|
->default('new')
|
|
->required(),
|
|
Forms\Components\Select::make('urgency')
|
|
->label('Urgență')
|
|
->options(\App\Models\Tenant\PricingCoefficient::URGENCY)
|
|
->default('normal')
|
|
->required(),
|
|
Forms\Components\Select::make('client_id')
|
|
->label('Client')
|
|
->options(fn () => Client::pluck('name', 'id'))
|
|
->searchable()
|
|
->live()
|
|
->required(),
|
|
Forms\Components\Select::make('vehicle_id')
|
|
->label('Auto')
|
|
->options(fn (Get $get) => $get('client_id')
|
|
? Vehicle::where('client_id', $get('client_id'))
|
|
->get()
|
|
->mapWithKeys(fn ($v) => [$v->id => "{$v->make} {$v->model} {$v->plate}"])
|
|
->toArray()
|
|
: [])
|
|
->searchable(),
|
|
Forms\Components\Select::make('master_id')
|
|
->label('Maistru')
|
|
->options(fn () => User::where('status', 'active')->pluck('name', 'id'))
|
|
->searchable(),
|
|
Forms\Components\TextInput::make('mileage_in')->label('Km la intrare')->numeric(),
|
|
Forms\Components\TextInput::make('mileage_out')->label('Km la ieșire')->numeric(),
|
|
]),
|
|
Schemas\Components\Section::make('Diagnostic')
|
|
->collapsible()
|
|
->schema([
|
|
Forms\Components\Textarea::make('complaint')->label('Plângere client')->rows(2)->columnSpanFull(),
|
|
Forms\Components\Textarea::make('diagnosis')->label('Diagnostic')->rows(3)->columnSpanFull(),
|
|
Forms\Components\Textarea::make('recommendations')->label('Recomandări')->rows(2)->columnSpanFull(),
|
|
]),
|
|
Schemas\Components\Section::make('Foto')
|
|
->collapsible()
|
|
->schema([
|
|
\Filament\Forms\Components\SpatieMediaLibraryFileUpload::make('photos')
|
|
->label('Fotografii')
|
|
->collection('photos')
|
|
->multiple()
|
|
->reorderable()
|
|
->image()
|
|
->imageEditor()
|
|
->maxFiles(20)
|
|
->columnSpanFull(),
|
|
]),
|
|
Schemas\Components\Section::make('Tracking & ETA')
|
|
->columns(3)
|
|
->collapsible()
|
|
->schema([
|
|
Forms\Components\DateTimePicker::make('eta_at')
|
|
->label('Gata estimat (ETA)')
|
|
->seconds(false),
|
|
Forms\Components\TextInput::make('tracking_token')
|
|
->label('Token public')
|
|
->disabled()
|
|
->dehydrated(false)
|
|
->columnSpan(2)
|
|
->helperText(fn (?WorkOrder $record) => $record?->tracking_token
|
|
? 'Link client: ' . $record->trackingUrl()
|
|
: 'Se generează la salvare'),
|
|
]),
|
|
Schemas\Components\Section::make('Plată & total')
|
|
->columns(3)
|
|
->schema([
|
|
Forms\Components\Select::make('pay_status')
|
|
->options(WorkOrder::PAY_STATUSES)
|
|
->default('unpaid')
|
|
->required(),
|
|
Forms\Components\TextInput::make('discount_pct')->label('Discount %')->numeric()->default(0),
|
|
Forms\Components\TextInput::make('override_margin_pct')
|
|
->label('Marjă internă (%) — override')
|
|
->numeric()
|
|
->step(0.01)
|
|
->minValue(0)
|
|
->maxValue(90)
|
|
->placeholder('Ex: 25 pentru VIP / contract')
|
|
->helperText('Doar pentru cazuri speciale. Lasă gol pentru a folosi marja mecanicului.')
|
|
->visible(fn () => auth()->user()?->canDo(\App\Auth\Permissions::FINANCE_VIEW_INTERNAL_MARGIN) ?? false),
|
|
Forms\Components\TextInput::make('total')->label('Total')->numeric()->disabled()->dehydrated(false),
|
|
Forms\Components\Toggle::make('approved')->label('Aprobat de client'),
|
|
Forms\Components\DatePicker::make('closed_at')->label('Închis'),
|
|
]),
|
|
]);
|
|
}
|
|
|
|
public static function table(Table $table): Table
|
|
{
|
|
return $table
|
|
->columns([
|
|
Tables\Columns\TextColumn::make('number')->label('Nr.')->searchable()->sortable(),
|
|
Tables\Columns\TextColumn::make('opened_at')->label('Deschis')->date('d.m.Y')->sortable(),
|
|
Tables\Columns\TextColumn::make('client.name')->label('Client')->searchable(),
|
|
Tables\Columns\TextColumn::make('vehicle.plate')->label('Auto')->placeholder('—'),
|
|
Tables\Columns\TextColumn::make('master.name')->label('Maistru')->placeholder('—'),
|
|
Tables\Columns\TextColumn::make('status')
|
|
->formatStateUsing(fn ($state) => WorkOrder::STATUSES[$state] ?? $state)
|
|
->badge()
|
|
->colors([
|
|
'gray' => ['new'],
|
|
'info' => ['diagnosis', 'agreement', 'approved'],
|
|
'warning' => ['in_work', 'awaiting_parts'],
|
|
'success' => ['ready', 'done'],
|
|
'danger' => ['cancelled'],
|
|
]),
|
|
Tables\Columns\TextColumn::make('pay_status')
|
|
->formatStateUsing(fn ($state) => WorkOrder::PAY_STATUSES[$state] ?? $state)
|
|
->badge()
|
|
->colors([
|
|
'danger' => ['unpaid'],
|
|
'warning' => ['partial'],
|
|
'success' => ['paid'],
|
|
]),
|
|
Tables\Columns\TextColumn::make('total')->money('MDL')->alignRight()->sortable(),
|
|
])
|
|
->filters([
|
|
Tables\Filters\SelectFilter::make('status')->options(WorkOrder::STATUSES),
|
|
Tables\Filters\SelectFilter::make('pay_status')->options(WorkOrder::PAY_STATUSES),
|
|
Tables\Filters\SelectFilter::make('master_id')
|
|
->label('Maistru')
|
|
->options(fn () => User::pluck('name', 'id')),
|
|
])
|
|
->actions([
|
|
Actions\Action::make('pdf')
|
|
->label('PDF')
|
|
->icon('heroicon-m-document-arrow-down')
|
|
->color('gray')
|
|
->action(function (WorkOrder $r) {
|
|
$svc = app(\App\Services\WorkOrderPdfService::class);
|
|
$pdf = $svc->generate($r);
|
|
$filename = $svc->filename($r);
|
|
return response()->streamDownload(
|
|
fn () => print($pdf->output()),
|
|
$filename
|
|
);
|
|
}),
|
|
Actions\EditAction::make(),
|
|
Actions\DeleteAction::make(),
|
|
])
|
|
->emptyStateHeading('Nicio fișă de lucru')
|
|
->emptyStateDescription('Crează prima fișă pentru o mașină existentă. Adaugă manopere, piese, plăți — totalul se calculează automat.')
|
|
->emptyStateIcon('heroicon-o-wrench-screwdriver')
|
|
->defaultSort('opened_at', 'desc');
|
|
}
|
|
|
|
public static function getRelations(): array
|
|
{
|
|
return [
|
|
RelationManagers\WorksRelationManager::class,
|
|
RelationManagers\PartsRelationManager::class,
|
|
RelationManagers\SubcontractJobsRelationManager::class,
|
|
RelationManagers\PaymentsRelationManager::class,
|
|
];
|
|
}
|
|
|
|
public static function getPages(): array
|
|
{
|
|
return [
|
|
'index' => Pages\ListWorkOrders::route('/'),
|
|
'create' => Pages\CreateWorkOrder::route('/create'),
|
|
'edit' => Pages\EditWorkOrder::route('/{record}/edit'),
|
|
];
|
|
}
|
|
}
|