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>
193 lines
6.6 KiB
PHP
193 lines
6.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Tenant;
|
|
|
|
use App\Models\Concerns\BelongsToTenant;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
class WorkOrderWork extends Model
|
|
{
|
|
use BelongsToTenant;
|
|
|
|
protected $table = 'wo_works';
|
|
|
|
protected $attributes = [
|
|
'mechanic_status' => 'pending',
|
|
'paused_seconds_total' => 0,
|
|
];
|
|
|
|
public const STATUSES = [
|
|
'todo' => 'De făcut',
|
|
'in_progress' => 'În lucru',
|
|
'done' => 'Finalizat',
|
|
];
|
|
|
|
public const MECHANIC_STATUSES = [
|
|
'pending' => 'În așteptare',
|
|
'in_progress' => 'În lucru',
|
|
'paused' => 'Pe pauză',
|
|
'done' => 'Finalizat',
|
|
'blocked' => 'Blocat',
|
|
];
|
|
|
|
public const BLOCK_REASONS = [
|
|
'missing_part' => 'Lipsă piesă',
|
|
'awaiting_approval' => 'Aștept aprobare client',
|
|
'broken_equipment' => 'Echipament defect',
|
|
'other' => 'Altă problemă',
|
|
];
|
|
|
|
protected $fillable = [
|
|
'company_id', 'work_order_id', 'labor_id', 'master_id',
|
|
'name', 'hours', 'price_per_hour', 'total', 'status', 'notes',
|
|
'requires_approval', 'approved_at', 'approval_token', 'declined_at',
|
|
'mechanic_status', 'mechanic_started_at', 'mechanic_done_at',
|
|
'actual_hours', 'paused_seconds_total', 'paused_at',
|
|
'block_reason', 'block_note',
|
|
'salary_base', 'applied_margin_pct',
|
|
];
|
|
|
|
protected $casts = [
|
|
'hours' => 'decimal:2',
|
|
'price_per_hour' => 'decimal:2',
|
|
'total' => 'decimal:2',
|
|
'requires_approval' => 'boolean',
|
|
'approved_at' => 'datetime',
|
|
'declined_at' => 'datetime',
|
|
'mechanic_started_at' => 'datetime',
|
|
'mechanic_done_at' => 'datetime',
|
|
'paused_at' => 'datetime',
|
|
'actual_hours' => 'decimal:2',
|
|
'paused_seconds_total' => 'integer',
|
|
'salary_base' => 'decimal:2',
|
|
'applied_margin_pct' => 'decimal:2',
|
|
];
|
|
|
|
// ── State machine ────────────────────────────────────────────
|
|
public function start(): void
|
|
{
|
|
if ($this->mechanic_status === 'done') return;
|
|
$this->forceFill([
|
|
'mechanic_status' => 'in_progress',
|
|
'mechanic_started_at' => $this->mechanic_started_at ?? now(),
|
|
'paused_at' => null,
|
|
'block_reason' => null,
|
|
'block_note' => null,
|
|
'status' => 'in_progress',
|
|
])->save();
|
|
}
|
|
|
|
public function pause(): void
|
|
{
|
|
if ($this->mechanic_status !== 'in_progress') return;
|
|
$this->forceFill([
|
|
'mechanic_status' => 'paused',
|
|
'paused_at' => now(),
|
|
])->save();
|
|
}
|
|
|
|
public function resume(): void
|
|
{
|
|
if ($this->mechanic_status !== 'paused') return;
|
|
$added = $this->paused_at ? $this->paused_at->diffInSeconds(now()) : 0;
|
|
$this->forceFill([
|
|
'mechanic_status' => 'in_progress',
|
|
'paused_seconds_total' => (int) $this->paused_seconds_total + (int) $added,
|
|
'paused_at' => null,
|
|
])->save();
|
|
}
|
|
|
|
public function markDone(): void
|
|
{
|
|
// If currently paused, count up till now as paused time before stopping.
|
|
if ($this->mechanic_status === 'paused' && $this->paused_at) {
|
|
$this->paused_seconds_total = (int) $this->paused_seconds_total + (int) $this->paused_at->diffInSeconds(now());
|
|
$this->paused_at = null;
|
|
}
|
|
$started = $this->mechanic_started_at ?? now();
|
|
$endedAt = now();
|
|
$elapsedSec = max(0, $started->diffInSeconds($endedAt) - (int) $this->paused_seconds_total);
|
|
$actualHours = round($elapsedSec / 3600, 2);
|
|
|
|
$this->forceFill([
|
|
'mechanic_status' => 'done',
|
|
'mechanic_done_at' => $endedAt,
|
|
'actual_hours' => $actualHours,
|
|
'status' => 'done',
|
|
'block_reason' => null,
|
|
])->save();
|
|
}
|
|
|
|
public function block(string $reason, ?string $note = null): void
|
|
{
|
|
if (! array_key_exists($reason, self::BLOCK_REASONS)) return;
|
|
$this->forceFill([
|
|
'mechanic_status' => 'blocked',
|
|
'block_reason' => $reason,
|
|
'block_note' => $note,
|
|
'paused_at' => null,
|
|
])->save();
|
|
}
|
|
|
|
/** 'green' if faster than norm, 'amber' if 30%+ over, 'red' if 100%+ over. */
|
|
public function efficiencyClass(): ?string
|
|
{
|
|
if ((float) $this->actual_hours <= 0 || (float) $this->hours <= 0) return null;
|
|
$ratio = (float) $this->actual_hours / (float) $this->hours;
|
|
return match (true) {
|
|
$ratio <= 1.0 => 'green',
|
|
$ratio <= 1.3 => 'amber',
|
|
default => 'red',
|
|
};
|
|
}
|
|
|
|
public function efficiencyPct(): ?int
|
|
{
|
|
if ((float) $this->actual_hours <= 0 || (float) $this->hours <= 0) return null;
|
|
return (int) round(100 * (float) $this->actual_hours / (float) $this->hours);
|
|
}
|
|
|
|
public function isPendingApproval(): bool
|
|
{
|
|
return $this->requires_approval && $this->approved_at === null && $this->declined_at === null;
|
|
}
|
|
|
|
public function workOrder(): BelongsTo
|
|
{
|
|
return $this->belongsTo(WorkOrder::class);
|
|
}
|
|
|
|
public function labor(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Labor::class);
|
|
}
|
|
|
|
public function master(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'master_id');
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::saving(function (self $row) {
|
|
$row->total = round((float) $row->hours * (float) $row->price_per_hour, 2);
|
|
if ($row->requires_approval && empty($row->approval_token)) {
|
|
$row->approval_token = \Illuminate\Support\Str::random(24);
|
|
}
|
|
// Compute internal margin & freeze salary_base at save time.
|
|
// Once frozen, changing user.internal_margin_pct later does NOT rewrite history.
|
|
if (($row->salary_base === null || $row->isDirty(['total', 'master_id'])) && (float) $row->total > 0) {
|
|
$resolver = app(\App\Services\MarginResolver::class);
|
|
$mechanic = $row->master_id ? User::find($row->master_id) : null;
|
|
$wo = $row->workOrder;
|
|
$marginPct = $resolver->resolve($wo, $mechanic);
|
|
$row->applied_margin_pct = $marginPct;
|
|
$row->salary_base = $resolver->computeSalaryBase((float) $row->total, $marginPct);
|
|
}
|
|
});
|
|
static::saved(fn (self $row) => $row->workOrder?->recalcTotal());
|
|
static::deleted(fn (self $row) => $row->workOrder?->recalcTotal());
|
|
}
|
|
}
|