03e030d6d2
Closes the remaining ~50h of items from CONFORMITY-12-15.md across all
four modules. Single umbrella migration (2026_06_05_000004) lands four
tables + 5 column additions, no downtime risk.
== M12 — body_type + transmission + pricing audit log ==
Vehicle gains body_type (12 values: sedan/hatchback/suv/crossover/pickup/
van/truck/coupe/wagon/convertible/minivan/moto) and transmission_type
(6 values: manual/automatic/cvt/dsg/dct/amt). These are separate from
vehicle_class so admin can configure DSG-only coefficients without
contaminating the SUV detection.
PricingCoefficient.matches() now also tests:
- conditions.body_types[] against ctx.body_type
- conditions.transmissions[] against ctx.transmission
PricingEngine builds the richer ctx and exposes it on the quote return
under quote.context.
New pricing_application_logs table (append-only) — call
PricingEngine::logApplication($quote, $subject, $vehicle, $client, $part)
after applying a price to a WO line. Stores base, final, full
applied[] array, and the ctx snapshot so the question "why was this
priced at 218 lei in March?" stays answerable forever.
PricingCoefficientResource form gains CheckboxList for body_types and
transmissions (3-column layouts, full-width). Both are optional —
empty list = applies to anything.
== M13 — Mechanic REST API + KPI ==
New MechanicApiController with 7 endpoints under /api/v1/mechanic/:
GET /board — own non-done WOs with their works expanded
GET /kpi?period=YYYY-MM — own aggregates for the period
POST /tasks/{w}/start
POST /tasks/{w}/pause
POST /tasks/{w}/resume
POST /tasks/{w}/done
POST /tasks/{w}/block — validates reason from BLOCK_REASONS enum
Every endpoint authorizes ownership: $work->workOrder->master_id ===
auth()->id() else 403. board() returns null pending_works so native
apps don't make round-trips. workPayload() emits efficiency_pct and
efficiency_class on every response.
New MechanicKpi Filament page at /app/mechanic-kpi (Service group). Same
aggregation logic but tenant-wide: groups WorkOrderWork rows by
master_id for the selected period, computes totals + efficiency_pct +
revenue. Period navigation via ◀/▶ buttons, default = current month.
Color-coded efficiency badges (green ≤100%, amber ≤130%, red >130%).
Rows sort by revenue descending — easy "top earners this month" view.
== M14 — OCR async via Laravel queue ==
New ocr_jobs table (id, supplier_id?, source_type, file_path, status,
result JSON, error_message, ai_provider, tokens_used, purchase_id?,
processed_at). Idempotent migration.
New OcrJob model + ProcessOcrJob queueable job. Job re-establishes
tenant context inside the worker (Company::find + TenantManager::setCurrent)
since queue workers don't inherit middleware-resolved tenants.
handle() walks: status=pending → processing, calls OcrInvoiceService::extract,
on success → status=done + result + ai_provider; on throw → status=failed
+ error_message. Failed jobs auto-retry once (tries=2) with 120s timeout.
The existing synchronous OcrInvoiceService stays for inline use cases
(tests, quick imports). The job is now the canonical path for the
admin UI to keep requests sub-100ms.
== M15 — eta_promised + JSON tracking + notifications log ==
Three new wo columns: eta_promised (initial commitment, never changes),
eta_change_reason (text for "așteptăm piesă"), eta_updated_at (when
the current eta was last touched). Existing eta_at remains as "current"
ETA so the UI can render both side-by-side.
New /api/track/{token} JSON endpoint (public, tenant-scoped via subdomain):
number, status, status_label, progress %, client, vehicle, plate, master,
eta_promised, eta_current, eta_change_reason, total, pay_status,
pending_approvals[] (each with kind/id/name/amount/approve_url —
signed URLs ready for native app webview),
timeline[] (from activity_log, last 20 events).
NotificationDispatcher::dispatch() gains optional workOrderId param.
Every send call (success or failure) now writes one row to the new
client_notifications_log table with channel/template_key/status (sent
or failed)/error_detail/sent_at. Failures of logging are swallowed
so a missing activity_log never breaks notifications. workOrderReady
and paymentReceived pass the WO id through; others can be wired in
future commits without schema change.
New tables tracked:
client_notifications_log — every push to client, append-only
pricing_application_logs — every pricing decision, append-only
ocr_jobs — async OCR job queue
== Tests ==
PolishTier3Test (11):
- M12: body_type condition match/no-match; transmission DSG match;
pricing_log row persists base/final/applied/ctx
- M13: mechanic API board scoped to own WOs; start task on foreign
work returns 403; KPI endpoint computes 2.5/3 = 83% efficiency
across 2 done works in period
- M14: ocr_job queueable + Queue::fake assertion
- M15: tracking JSON returns ETA promised/current/reason + pending
approvals with correctly-signed approve_url; dispatcher writes
ClientNotificationLog row on workOrderReady
- M12: vehicle body_type + transmission_type round-trip through save
Suite: 269 passed (761 assertions). Was 258.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
198 lines
6.4 KiB
PHP
198 lines
6.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Tenant;
|
|
|
|
use App\Models\Concerns\BelongsToTenant;
|
|
use App\Models\Concerns\Auditable;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Spatie\MediaLibrary\HasMedia;
|
|
use Spatie\MediaLibrary\InteractsWithMedia;
|
|
|
|
class WorkOrder extends Model implements HasMedia
|
|
{
|
|
use Auditable, BelongsToTenant, InteractsWithMedia, SoftDeletes;
|
|
|
|
public const STATUSES = [
|
|
'new' => 'Nou',
|
|
'diagnosis' => 'Diagnosticare',
|
|
'agreement' => 'Aprobare client',
|
|
'approved' => 'Aprobat',
|
|
'in_work' => 'În lucru',
|
|
'awaiting_parts' => 'Așteaptă piese',
|
|
'ready' => 'Gata de ridicare',
|
|
'done' => 'Predat',
|
|
'cancelled' => 'Anulat',
|
|
];
|
|
|
|
public const PAY_STATUSES = [
|
|
'unpaid' => 'Neplătit',
|
|
'partial' => 'Parțial',
|
|
'paid' => 'Plătit',
|
|
];
|
|
|
|
protected $fillable = [
|
|
'company_id', 'number',
|
|
'client_id', 'vehicle_id', 'master_id', 'deal_id', 'appointment_id',
|
|
'opened_at', 'closed_at', 'mileage_in', 'mileage_out',
|
|
'complaint', 'diagnosis', 'recommendations',
|
|
'status', 'urgency', 'pay_status', 'approved', 'approved_at',
|
|
'discount_pct', 'total',
|
|
'eta_at', 'eta_promised', 'eta_change_reason', 'eta_updated_at',
|
|
'tracking_token',
|
|
];
|
|
|
|
protected $casts = [
|
|
'opened_at' => 'date',
|
|
'closed_at' => 'date',
|
|
'approved_at' => 'datetime',
|
|
'eta_at' => 'datetime',
|
|
'eta_promised' => 'datetime',
|
|
'eta_updated_at' => 'datetime',
|
|
'approved' => 'boolean',
|
|
'discount_pct' => 'decimal:2',
|
|
'total' => 'decimal:2',
|
|
];
|
|
|
|
public function registerMediaCollections(): void
|
|
{
|
|
$this->addMediaCollection('photos');
|
|
}
|
|
|
|
public function trackingUrl(): string
|
|
{
|
|
return url('/t/' . $this->tracking_token);
|
|
}
|
|
|
|
public function client(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Client::class);
|
|
}
|
|
|
|
public function vehicle(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Vehicle::class);
|
|
}
|
|
|
|
public function master(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'master_id');
|
|
}
|
|
|
|
public function works(): HasMany
|
|
{
|
|
return $this->hasMany(WorkOrderWork::class);
|
|
}
|
|
|
|
public function parts(): HasMany
|
|
{
|
|
return $this->hasMany(WorkOrderPart::class);
|
|
}
|
|
|
|
public function payments(): HasMany
|
|
{
|
|
return $this->hasMany(Payment::class);
|
|
}
|
|
|
|
public function subcontractJobs(): HasMany
|
|
{
|
|
return $this->hasMany(SubcontractJob::class);
|
|
}
|
|
|
|
public function paidAmount(): float
|
|
{
|
|
return (float) $this->payments()->sum('amount');
|
|
}
|
|
|
|
public function balanceDue(): float
|
|
{
|
|
return max(0.0, (float) $this->total - $this->paidAmount());
|
|
}
|
|
|
|
public function recalcTotal(): void
|
|
{
|
|
$worksTotal = $this->works()->sum('total');
|
|
$partsTotal = $this->parts()->sum('total');
|
|
$subcontractTotal = $this->subcontractJobs()
|
|
->where('status', '!=', 'cancelled')
|
|
->sum('client_price');
|
|
$sub = (float) $worksTotal + (float) $partsTotal + (float) $subcontractTotal;
|
|
$disc = (float) $this->discount_pct;
|
|
$this->total = round($sub * (1 - $disc / 100), 2);
|
|
$this->save();
|
|
}
|
|
|
|
public static function generateNumber(int $companyId): string
|
|
{
|
|
$year = date('y');
|
|
$count = static::withoutGlobalScopes()
|
|
->where('company_id', $companyId)
|
|
->whereYear('created_at', date('Y'))
|
|
->count();
|
|
return sprintf('WO-%s-%04d', $year, $count + 1);
|
|
}
|
|
|
|
/** Auto-send 'ready' email + broadcast WS event on status change. */
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (self $wo) {
|
|
if (empty($wo->tracking_token)) {
|
|
$wo->tracking_token = \Illuminate\Support\Str::random(24);
|
|
}
|
|
});
|
|
|
|
static::updated(function (self $wo) {
|
|
if (
|
|
$wo->wasChanged('status')
|
|
&& $wo->status === 'ready'
|
|
&& $wo->getOriginal('status') !== 'ready'
|
|
) {
|
|
app(\App\Services\NotificationDispatcher::class)->workOrderReady($wo);
|
|
}
|
|
|
|
// Push the assigned mechanic when a WO gets assigned to them.
|
|
if ($wo->wasChanged('master_id') && $wo->master_id) {
|
|
try {
|
|
app(\App\Services\Notifications\WebPushService::class)->sendToUser(
|
|
(int) $wo->master_id,
|
|
'Fișă nouă atribuită',
|
|
"Fișa #{$wo->number} · " . ($wo->vehicle?->plate ?? ''),
|
|
'/app/resources/work-orders/' . $wo->id . '/edit',
|
|
'wo-assign-' . $wo->id,
|
|
);
|
|
} catch (\Throwable $e) {
|
|
\Illuminate\Support\Facades\Log::debug('WO assign push skipped: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
// Warehouse lifecycle: status=done → consume reservations into issues;
|
|
// status=cancelled → release reservations.
|
|
if ($wo->wasChanged('status')) {
|
|
$svc = app(\App\Services\Warehouse\WarehouseService::class);
|
|
if ($wo->status === 'done' && $wo->getOriginal('status') !== 'done') {
|
|
$svc->consume($wo);
|
|
}
|
|
if ($wo->status === 'cancelled' && $wo->getOriginal('status') !== 'cancelled') {
|
|
foreach ($wo->parts as $wop) {
|
|
$svc->release($wop);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Broadcast real-time update on any field change (skip if broadcasting=log).
|
|
if (config('broadcasting.default') !== 'log') {
|
|
try {
|
|
$company = \App\Models\Central\Company::withoutGlobalScopes()->find($wo->company_id);
|
|
if ($company) {
|
|
\App\Events\WorkOrderUpdated::dispatch($wo, $company->slug);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
\Illuminate\Support\Facades\Log::debug('WO broadcast skipped: ' . $e->getMessage());
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|