feat: tier 3 polish — M12/13/14/15 deep cleanup

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>
This commit is contained in:
2026-06-05 05:31:50 +00:00
parent cbcf08b28c
commit 03e030d6d2
17 changed files with 940 additions and 8 deletions
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Filament\Tenant\Pages;
use App\Models\Tenant\User;
use App\Models\Tenant\WorkOrderWork;
use Carbon\Carbon;
use Filament\Pages\Page;
/**
* Aggregate KPI dashboard per mechanic over a period: tasks done, norm vs
* actual hours, efficiency %, revenue from manopere. Period defaults to
* current month.
*/
class MechanicKpi extends Page
{
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';
protected static ?string $navigationLabel = 'KPI mecanici';
protected static string|\UnitEnum|null $navigationGroup = 'Service';
protected static ?int $navigationSort = 28;
protected static ?string $title = 'KPI mecanici';
protected string $view = 'filament.tenant.pages.mechanic-kpi';
public string $period = '';
public function mount(): void
{
$this->period = now()->format('Y-m');
}
public function shiftMonth(int $delta): void
{
$this->period = Carbon::parse($this->period . '-01')->addMonths($delta)->format('Y-m');
}
public function getRows(): array
{
[$y, $m] = explode('-', $this->period);
$rows = WorkOrderWork::query()
->with('workOrder:id,master_id')
->where('mechanic_status', 'done')
->whereYear('mechanic_done_at', $y)
->whereMonth('mechanic_done_at', $m)
->get()
->groupBy(fn ($w) => $w->workOrder?->master_id ?: 0);
$masters = User::whereIn('id', $rows->keys()->all())->get(['id', 'name'])->keyBy('id');
$out = [];
foreach ($rows as $masterId => $works) {
if (! $masterId) continue;
$totalNorm = (float) $works->sum('hours');
$totalActual = (float) $works->sum('actual_hours');
$efficiencyPct = $totalNorm > 0 ? round(100 * $totalActual / $totalNorm) : null;
$cls = match (true) {
$efficiencyPct === null => 'gray',
$efficiencyPct <= 100 => 'green',
$efficiencyPct <= 130 => 'amber',
default => 'red',
};
$out[] = [
'master_id' => $masterId,
'master_name' => $masters[$masterId]?->name ?? 'Mecanic #' . $masterId,
'tasks_done' => $works->count(),
'norm_hours' => round($totalNorm, 2),
'actual_hours' => round($totalActual, 2),
'efficiency_pct' => $efficiencyPct,
'efficiency_class' => $cls,
'revenue' => round((float) $works->sum('total'), 2),
];
}
usort($out, fn ($a, $b) => $b['revenue'] <=> $a['revenue']);
return $out;
}
public function getPeriodLabel(): string
{
return Carbon::parse($this->period . '-01')->locale('ro')->isoFormat('MMMM YYYY');
}
}
@@ -58,6 +58,16 @@ class PricingCoefficientResource extends Resource
->options(PricingCoefficient::VEHICLE_CLASSES)
->columns(2)
->columnSpanFull(),
Forms\Components\CheckboxList::make('conditions.body_types')
->label('Caroserie')
->options(\App\Models\Tenant\Vehicle::BODY_TYPES)
->columns(3)
->columnSpanFull(),
Forms\Components\CheckboxList::make('conditions.transmissions')
->label('Cutie de viteze')
->options(\App\Models\Tenant\Vehicle::TRANSMISSION_TYPES)
->columns(3)
->columnSpanFull(),
Forms\Components\TextInput::make('conditions.age_min')->label('Vârstă min (ani)')->numeric(),
Forms\Components\TextInput::make('conditions.age_max')->label('Vârstă max (ani)')->numeric(),
Forms\Components\Toggle::make('conditions.client_vip')->label('Doar clienți VIP'),
@@ -0,0 +1,127 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Tenant\WorkOrder;
use App\Models\Tenant\WorkOrderWork;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MechanicApiController extends Controller
{
/** GET /api/v1/mechanic/board — only OWN WOs with their works expanded. */
public function board(): JsonResponse
{
$userId = auth()->id();
$wos = WorkOrder::with(['client:id,name', 'vehicle:id,plate,make,model', 'works'])
->where('master_id', $userId)
->whereNotIn('status', ['done', 'cancelled'])
->orderBy('opened_at')
->get()
->map(fn ($wo) => [
'id' => $wo->id, 'number' => $wo->number, 'status' => $wo->status,
'client_name' => $wo->client?->name,
'vehicle' => trim(($wo->vehicle?->make ?? '') . ' ' . ($wo->vehicle?->model ?? '')),
'plate' => $wo->vehicle?->plate,
'complaint' => $wo->complaint,
'eta_at' => $wo->eta_at?->toIso8601String(),
'works' => $wo->works->map(fn ($w) => $this->workPayload($w))->all(),
]);
return response()->json(['data' => $wos]);
}
/** POST /api/v1/mechanic/tasks/{work}/start */
public function startTask(WorkOrderWork $work): JsonResponse
{
$this->authorizeOwn($work);
$work->start();
return response()->json(['data' => $this->workPayload($work->fresh())]);
}
public function pauseTask(WorkOrderWork $work): JsonResponse
{
$this->authorizeOwn($work);
$work->pause();
return response()->json(['data' => $this->workPayload($work->fresh())]);
}
public function resumeTask(WorkOrderWork $work): JsonResponse
{
$this->authorizeOwn($work);
$work->resume();
return response()->json(['data' => $this->workPayload($work->fresh())]);
}
public function doneTask(WorkOrderWork $work): JsonResponse
{
$this->authorizeOwn($work);
$work->markDone();
return response()->json(['data' => $this->workPayload($work->fresh())]);
}
public function blockTask(Request $request, WorkOrderWork $work): JsonResponse
{
$this->authorizeOwn($work);
$data = $request->validate([
'reason' => 'required|in:' . implode(',', array_keys(WorkOrderWork::BLOCK_REASONS)),
'note' => 'nullable|string|max:1000',
]);
$work->block($data['reason'], $data['note'] ?? null);
return response()->json(['data' => $this->workPayload($work->fresh())]);
}
/** GET /api/v1/mechanic/kpi?period=2026-06 — own efficiency aggregates. */
public function kpi(Request $request): JsonResponse
{
$userId = auth()->id();
$period = $request->query('period', now()->format('Y-m'));
[$y, $m] = explode('-', $period);
$rows = WorkOrderWork::whereHas('workOrder', fn ($q) => $q->where('master_id', $userId))
->where('mechanic_status', 'done')
->whereYear('mechanic_done_at', $y)
->whereMonth('mechanic_done_at', $m)
->get();
$totalNorm = (float) $rows->sum('hours');
$totalActual = (float) $rows->sum('actual_hours');
$tasksDone = $rows->count();
$totalRevenue = (float) $rows->sum('total');
$efficiencyPct = $totalNorm > 0 ? round(100 * $totalActual / $totalNorm) : null;
return response()->json([
'period' => $period,
'tasks_done' => $tasksDone,
'norm_hours' => round($totalNorm, 2),
'actual_hours' => round($totalActual, 2),
'efficiency_pct' => $efficiencyPct,
'revenue_manopere' => round($totalRevenue, 2),
]);
}
private function workPayload(WorkOrderWork $w): array
{
return [
'id' => $w->id,
'name' => $w->name,
'mechanic_status' => $w->mechanic_status,
'norm_hours' => (float) $w->hours,
'actual_hours' => (float) $w->actual_hours,
'efficiency_pct' => $w->efficiencyPct(),
'efficiency_class' => $w->efficiencyClass(),
'block_reason' => $w->block_reason,
'block_note' => $w->block_note,
'mechanic_started_at' => $w->mechanic_started_at?->toIso8601String(),
'mechanic_done_at' => $w->mechanic_done_at?->toIso8601String(),
];
}
private function authorizeOwn(WorkOrderWork $work): void
{
if ($work->workOrder?->master_id !== auth()->id()) {
abort(403, 'Work belongs to a different mechanic.');
}
}
}
@@ -79,6 +79,72 @@ class TrackingController extends Controller
return redirect()->route('tracking.show', ['token' => $token]);
}
/**
* GET /api/track/{token} JSON status payload for native apps.
* Public, no auth (token IS the credential). Tenant-scoped via subdomain.
*/
public function jsonStatus(Request $request, string $token)
{
$tenant = app(TenantManager::class)->current();
if (! $tenant) {
return response()->json(['error' => 'tenant_required'], 404);
}
$wo = WorkOrder::with(['client:id,name', 'vehicle:id,plate,make,model', 'master:id,name', 'works', 'parts'])
->where('tracking_token', $token)
->first();
if (! $wo) return response()->json(['error' => 'not_found'], 404);
$statuses = WorkOrder::STATUSES;
$flow = ['new', 'diagnosis', 'agreement', 'approved', 'in_work', 'awaiting_parts', 'ready', 'done'];
$currentIdx = array_search($wo->status, $flow, true);
$pendingApprovals = collect()
->merge($wo->works->filter(fn ($w) => $w->isPendingApproval())->map(fn ($w) => [
'kind' => 'work', 'id' => $w->id, 'token' => $w->approval_token,
'name' => $w->name, 'amount' => (float) $w->total,
'approve_url' => url("/t/{$token}/approve/work/{$w->approval_token}"),
]))
->merge($wo->parts->filter(fn ($p) => $p->isPendingApproval())->map(fn ($p) => [
'kind' => 'part', 'id' => $p->id, 'token' => $p->approval_token,
'name' => $p->name, 'amount' => (float) $p->total,
'approve_url' => url("/t/{$token}/approve/part/{$p->approval_token}"),
]));
// Timeline from activity_log (best-effort — empty array if not configured)
$timeline = [];
try {
$timeline = \DB::table('activity_log')
->where('subject_type', WorkOrder::class)
->where('subject_id', $wo->id)
->orderBy('created_at')
->limit(20)
->get(['event', 'description', 'created_at'])
->map(fn ($r) => [
'event' => $r->event,
'description' => $r->description,
'at' => $r->created_at,
])->toArray();
} catch (\Throwable $e) { /* activity_log table may not exist in some tenants */ }
return response()->json([
'number' => $wo->number,
'status' => $wo->status,
'status_label' => $statuses[$wo->status] ?? $wo->status,
'progress' => $currentIdx !== false ? round(100 * ($currentIdx + 1) / count($flow)) : null,
'client' => $wo->client?->name,
'vehicle' => trim(($wo->vehicle?->make ?? '') . ' ' . ($wo->vehicle?->model ?? '')),
'plate' => $wo->vehicle?->plate,
'master' => $wo->master?->name,
'eta_promised' => $wo->eta_promised?->toIso8601String(),
'eta_current' => $wo->eta_at?->toIso8601String(),
'eta_change_reason' => $wo->eta_change_reason,
'total' => (float) $wo->total,
'pay_status' => $wo->pay_status,
'pending_approvals' => $pendingApprovals->values(),
'timeline' => $timeline,
]);
}
public function qr(Request $request, string $token)
{
$tenant = app(TenantManager::class)->current();
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Jobs;
use App\Models\Tenant\OcrJob;
use App\Services\Ai\OcrInvoiceService;
use App\Tenancy\TenantManager;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
class ProcessOcrJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 2;
public int $timeout = 120;
public function __construct(public int $ocrJobId, public int $companyId) {}
public function handle(OcrInvoiceService $svc, TenantManager $tenants): void
{
// Re-establish tenant context inside the queue worker
$company = \App\Models\Central\Company::find($this->companyId);
if (! $company) { return; }
$tenants->setCurrent($company);
$job = OcrJob::find($this->ocrJobId);
if (! $job) return;
$job->update(['status' => 'processing']);
try {
$absPath = Storage::disk('local')->path($job->file_path);
$result = $svc->extract($absPath);
$job->update([
'status' => 'done',
'result' => $result,
'processed_at' => now(),
'ai_provider' => 'claude',
]);
} catch (\Throwable $e) {
$job->update([
'status' => 'failed',
'error_message' => $e->getMessage(),
'processed_at' => now(),
]);
throw $e;
}
}
public function failed(\Throwable $e): void
{
$job = OcrJob::find($this->ocrJobId);
$job?->update(['status' => 'failed', 'error_message' => $e->getMessage()]);
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Models\Tenant;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ClientNotificationLog extends Model
{
use BelongsToTenant;
public $timestamps = false;
protected $table = 'client_notifications_log';
public const CHANNELS = [
'sms' => 'SMS',
'whatsapp' => 'WhatsApp',
'telegram' => 'Telegram',
'email' => 'Email',
'push' => 'Web Push',
];
public const STATUSES = [
'sent' => 'Trimis',
'delivered' => 'Livrat',
'failed' => 'Eșuat',
'read' => 'Citit',
];
protected $fillable = [
'company_id', 'work_order_id', 'client_id',
'channel', 'template_key', 'message_text', 'status', 'error_detail',
'sent_at', 'delivered_at',
];
protected $casts = [
'sent_at' => 'datetime',
'delivered_at' => 'datetime',
];
public function workOrder(): BelongsTo { return $this->belongsTo(WorkOrder::class); }
public function client(): BelongsTo { return $this->belongsTo(Client::class); }
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models\Tenant;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OcrJob extends Model
{
use BelongsToTenant;
public const STATUSES = [
'pending' => 'În așteptare',
'processing' => 'Procesare',
'done' => 'Finalizat',
'failed' => 'Eșuat',
];
protected $fillable = [
'company_id', 'supplier_id', 'source_type', 'file_path', 'status',
'result', 'error_message', 'ai_provider', 'tokens_used',
'purchase_id', 'processed_at',
];
protected $casts = [
'result' => 'array',
'processed_at' => 'datetime',
'tokens_used' => 'integer',
];
public function supplier(): BelongsTo { return $this->belongsTo(Supplier::class); }
public function purchase(): BelongsTo { return $this->belongsTo(Purchase::class); }
}
@@ -0,0 +1,37 @@
<?php
namespace App\Models\Tenant;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* Append-only audit log: every PricingEngine::quote() call writes one row
* here so we can reconstruct "why was this part priced at 218 lei?" later.
*/
class PricingApplicationLog extends Model
{
use BelongsToTenant;
public $timestamps = false;
protected $fillable = [
'company_id', 'subject_type', 'subject_id', 'part_id', 'vehicle_id', 'client_id',
'base_price', 'final_price', 'applied_coefficients', 'context', 'calculated_at',
];
protected $casts = [
'base_price' => 'decimal:2',
'final_price' => 'decimal:2',
'applied_coefficients' => 'array',
'context' => 'array',
'calculated_at' => 'datetime',
];
public function subject(): MorphTo { return $this->morphTo(); }
public function part(): BelongsTo { return $this->belongsTo(Part::class); }
public function vehicle(): BelongsTo { return $this->belongsTo(Vehicle::class); }
public function client(): BelongsTo { return $this->belongsTo(Client::class); }
}
+16
View File
@@ -53,6 +53,22 @@ class PricingCoefficient extends Model
}
}
// Body type — sedan|suv|pickup|...
$bodyTypes = (array) ($c['body_types'] ?? []);
if (! empty($bodyTypes)) {
if (empty($ctx['body_type']) || ! in_array($ctx['body_type'], $bodyTypes, true)) {
return false;
}
}
// Transmission — dsg|cvt|automatic|...
$transmissions = (array) ($c['transmissions'] ?? []);
if (! empty($transmissions)) {
if (empty($ctx['transmission']) || ! in_array($ctx['transmission'], $transmissions, true)) {
return false;
}
}
// Vehicle age range.
if (isset($c['age_min']) && $c['age_min'] !== null && $c['age_min'] !== '') {
if (($ctx['age'] ?? null) === null || $ctx['age'] < (int) $c['age_min']) return false;
+18 -1
View File
@@ -12,10 +12,27 @@ class Vehicle extends Model
{
use Auditable, BelongsToTenant, SoftDeletes;
public const BODY_TYPES = [
'sedan' => 'Sedan', 'hatchback' => 'Hatchback', 'suv' => 'SUV',
'crossover' => 'Crossover', 'pickup' => 'Pickup', 'van' => 'Van',
'truck' => 'Camion', 'coupe' => 'Coupé', 'wagon' => 'Break',
'convertible' => 'Cabrio', 'minivan' => 'Minivan', 'moto' => 'Motocicletă',
];
public const TRANSMISSION_TYPES = [
'manual' => 'Manuală',
'automatic' => 'Automată',
'cvt' => 'CVT',
'dsg' => 'DSG',
'dct' => 'DCT (Dual-Clutch)',
'amt' => 'AMT (Robot)',
];
protected $fillable = [
'company_id', 'client_id',
'make', 'model', 'year', 'vin', 'plate',
'engine', 'gearbox', 'fuel', 'vehicle_class', 'mileage', 'color', 'notes',
'engine', 'gearbox', 'fuel', 'vehicle_class', 'body_type', 'transmission_type',
'mileage', 'color', 'notes',
];
public function client(): BelongsTo
+4 -1
View File
@@ -40,7 +40,8 @@ class WorkOrder extends Model implements HasMedia
'complaint', 'diagnosis', 'recommendations',
'status', 'urgency', 'pay_status', 'approved', 'approved_at',
'discount_pct', 'total',
'eta_at', 'tracking_token',
'eta_at', 'eta_promised', 'eta_change_reason', 'eta_updated_at',
'tracking_token',
];
protected $casts = [
@@ -48,6 +49,8 @@ class WorkOrder extends Model implements HasMedia
'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',
+24 -5
View File
@@ -47,7 +47,7 @@ class NotificationDispatcher
fn () => Mail::to($client->email)->send(new WorkOrderReadyMail($wo, $company)),
'workOrderReady', ['wo' => $wo->id]
),
]);
], workOrderId: $wo->id);
}
public function paymentReceived(Payment $payment): bool
@@ -62,7 +62,7 @@ class NotificationDispatcher
fn () => Mail::to($client->email)->send(new PaymentReceivedMail($payment, $company)),
'paymentReceived', ['payment' => $payment->id]
),
]);
], workOrderId: $payment->work_order_id);
}
public function appointmentConfirmed(Appointment $a): bool
@@ -138,24 +138,43 @@ class NotificationDispatcher
* @param array<string, callable(): bool> $senders channel-key sender callback
* @return bool Returns the channel name that delivered, or null on full miss.
*/
protected function dispatch(Company $company, Client $client, string $key, array $senders): bool
protected function dispatch(Company $company, Client $client, string $key, array $senders, ?int $workOrderId = null): bool
{
$any = false;
foreach ($this->channelsFor($company, $client, $key) as $channel) {
if (! isset($senders[$channel])) continue;
try {
if (($senders[$channel])() === true) {
$ok = ($senders[$channel])() === true;
$this->logNotification($company->id, $workOrderId, $client->id, $channel, $key, $ok);
if ($ok) {
$any = true;
// Try only one channel — first that succeeds is enough.
break;
}
} catch (\Throwable $e) {
Log::warning("notify.{$key} {$channel} threw", ['err' => $e->getMessage()]);
$this->logNotification($company->id, $workOrderId, $client->id, $channel, $key, false, $e->getMessage());
}
}
return $any;
}
/** Append-only log entry — never throw from here, swallow DB errors. */
protected function logNotification(int $companyId, ?int $workOrderId, ?int $clientId, string $channel, string $key, bool $success, ?string $error = null): void
{
try {
\App\Models\Tenant\ClientNotificationLog::create([
'company_id' => $companyId,
'work_order_id' => $workOrderId,
'client_id' => $clientId,
'channel' => $channel,
'template_key' => $key,
'status' => $success ? 'sent' : 'failed',
'error_detail' => $error,
'sent_at' => now(),
]);
} catch (\Throwable $e) { /* never break sending because of logging */ }
}
/**
* Resolve which channels to try and in what order, applying per-client
* preference if set, otherwise the tenant default.
+27 -1
View File
@@ -33,6 +33,8 @@ class PricingEngine
$ctx = [
'class' => $this->vehicleClass($vehicle),
'age' => $this->vehicleAge($vehicle),
'body_type' => $vehicle?->body_type,
'transmission' => $vehicle?->transmission_type,
'vip' => (bool) ($client?->is_vip),
'urgency' => $urgency ?: 'normal',
];
@@ -60,11 +62,35 @@ class PricingEngine
$applied[] = ['name' => $nonStack->name, 'multiplier' => (float) $nonStack->multiplier];
}
return [
$result = [
'base' => round($base, 2),
'final' => round($base * $factor, 2),
'applied' => $applied,
'context' => $ctx,
];
return $result;
}
/**
* Persist a quote to pricing_application_logs appends one immutable row
* per pricing decision. Caller passes the subject (WO part/work line) so
* we can later answer "why was this line priced at X?".
*/
public function logApplication(array $quote, $subject, ?Vehicle $vehicle = null, ?Client $client = null, ?Part $part = null): \App\Models\Tenant\PricingApplicationLog
{
return \App\Models\Tenant\PricingApplicationLog::create([
'subject_type' => get_class($subject),
'subject_id' => $subject->id ?? 0,
'part_id' => $part?->id,
'vehicle_id' => $vehicle?->id,
'client_id' => $client?->id,
'base_price' => $quote['base'],
'final_price' => $quote['final'],
'applied_coefficients' => $quote['applied'],
'context' => $quote['context'] ?? [],
'calculated_at' => now(),
]);
}
private function basePrice(Part $part): float