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
+212
View File
@@ -0,0 +1,212 @@
<?php
namespace Tests\Feature;
use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\Client;
use App\Models\Tenant\ClientNotificationLog;
use App\Models\Tenant\Part;
use App\Models\Tenant\PricingApplicationLog;
use App\Models\Tenant\PricingCoefficient;
use App\Models\Tenant\User;
use App\Models\Tenant\Vehicle;
use App\Models\Tenant\WorkOrder;
use App\Models\Tenant\WorkOrderWork;
use App\Services\Pricing\PricingEngine;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class PolishTier3Test extends TestCase
{
use RefreshDatabase;
private Company $company;
protected function setUp(): void
{
parent::setUp();
$plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
$this->company = Company::create(['plan_id' => $plan->id, 'slug' => 't3-' . uniqid(), 'name' => 'T3', 'status' => 'active']);
app(TenantManager::class)->setCurrent($this->company);
}
private function makeClient(string $prefix = ''): Client
{
return Client::create(['name' => $prefix . 'C', 'phone' => '+3739900' . random_int(1000, 9999), 'type' => 'individual', 'status' => 'active']);
}
// ── M12 ──
public function test_pricing_engine_matches_body_type_condition(): void
{
PricingCoefficient::create([
'name' => 'Pickup +20%', 'multiplier' => 1.20,
'conditions' => ['body_types' => ['pickup']],
'stackable' => true, 'priority' => 100, 'is_active' => true,
]);
$part = Part::create(['name' => 'P', 'article' => 'X', 'buy_price' => 100, 'sell_price' => 100]);
$pickup = Vehicle::create(['client_id' => $this->makeClient('p')->id, 'make' => 'Ford', 'model' => 'Ranger', 'plate' => 'P1', 'body_type' => 'pickup']);
$sedan = Vehicle::create(['client_id' => $this->makeClient('s')->id, 'make' => 'BMW', 'model' => 'X5', 'plate' => 'S1', 'body_type' => 'sedan']);
$q1 = app(PricingEngine::class)->quote($part, $pickup);
$q2 = app(PricingEngine::class)->quote($part, $sedan);
$this->assertCount(1, $q1['applied']);
$this->assertEmpty($q2['applied']);
}
public function test_pricing_engine_matches_transmission_dsg(): void
{
PricingCoefficient::create([
'name' => 'DSG +15%', 'multiplier' => 1.15,
'conditions' => ['transmissions' => ['dsg']],
'stackable' => true, 'priority' => 100, 'is_active' => true,
]);
$part = Part::create(['name' => 'P', 'article' => 'X', 'buy_price' => 100, 'sell_price' => 100]);
$dsg = Vehicle::create(['client_id' => $this->makeClient('d')->id, 'make' => 'VW', 'model' => 'Golf', 'plate' => 'D1', 'transmission_type' => 'dsg']);
$q = app(PricingEngine::class)->quote($part, $dsg);
$this->assertCount(1, $q['applied']);
$this->assertEquals('DSG +15%', $q['applied'][0]['name']);
}
public function test_pricing_log_persists_breakdown(): void
{
PricingCoefficient::create([
'name' => 'SUV +15%', 'multiplier' => 1.15,
'conditions' => ['classes' => ['suv']],
'stackable' => true, 'priority' => 100, 'is_active' => true,
]);
$part = Part::create(['name' => 'P', 'article' => 'X', 'buy_price' => 100, 'sell_price' => 150]);
$client = $this->makeClient('pl');
$vehicle = Vehicle::create(['client_id' => $client->id, 'make' => 'BMW', 'model' => 'X5', 'plate' => 'X1', 'vehicle_class' => 'suv', 'year' => 2020]);
$wo = WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'client_id' => $client->id, 'vehicle_id' => $vehicle->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 0]);
$line = \App\Models\Tenant\WorkOrderPart::create(['work_order_id' => $wo->id, 'name' => 'P', 'qty' => 1, 'sell_price' => 150]);
$quote = app(PricingEngine::class)->quote($part, $vehicle, $client);
$log = app(PricingEngine::class)->logApplication($quote, $line, $vehicle, $client, $part);
$this->assertEqualsWithDelta(150.0, (float) $log->base_price, 0.01);
$this->assertEqualsWithDelta(172.5, (float) $log->final_price, 0.01);
$this->assertCount(1, $log->applied_coefficients);
$this->assertEquals('suv', $log->context['class']);
}
// ── M13 ──
public function test_mechanic_api_board_returns_only_own_wos(): void
{
$mech = User::create(['name' => 'M', 'email' => 'm@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$other = User::create(['name' => 'O', 'email' => 'o@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'master_id' => $mech->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 100]);
WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'master_id' => $other->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 200]);
Sanctum::actingAs($mech);
$resp = $this->getJson('/api/v1/mechanic/board');
$resp->assertOk();
$this->assertCount(1, $resp->json('data'));
}
public function test_mechanic_api_start_task_only_own(): void
{
$mech = User::create(['name' => 'M', 'email' => 'm@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$other = User::create(['name' => 'O', 'email' => 'o@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$foreignWo = WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'master_id' => $other->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 0]);
$foreignWork = WorkOrderWork::create(['work_order_id' => $foreignWo->id, 'name' => "Other's", 'hours' => 1, 'price_per_hour' => 100]);
Sanctum::actingAs($mech);
$resp = $this->postJson("/api/v1/mechanic/tasks/{$foreignWork->id}/start");
$resp->assertForbidden();
}
public function test_mechanic_kpi_endpoint_aggregates_period(): void
{
$mech = User::create(['name' => 'M', 'email' => 'm@e.com', 'password' => bcrypt('x'), 'role' => 'mechanic', 'status' => 'active']);
$wo = WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'master_id' => $mech->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 0]);
// Two done works in 2026-06
WorkOrderWork::create(['work_order_id' => $wo->id, 'name' => 'A', 'hours' => 2, 'price_per_hour' => 300, 'mechanic_status' => 'done', 'actual_hours' => 1.5, 'mechanic_done_at' => '2026-06-10 10:00:00']);
WorkOrderWork::create(['work_order_id' => $wo->id, 'name' => 'B', 'hours' => 1, 'price_per_hour' => 300, 'mechanic_status' => 'done', 'actual_hours' => 1.0, 'mechanic_done_at' => '2026-06-15 10:00:00']);
Sanctum::actingAs($mech);
$resp = $this->getJson('/api/v1/mechanic/kpi?period=2026-06');
$resp->assertOk();
$this->assertEquals(2, $resp->json('tasks_done'));
$this->assertEqualsWithDelta(3.0, $resp->json('norm_hours'), 0.01);
$this->assertEqualsWithDelta(2.5, $resp->json('actual_hours'), 0.01);
$this->assertEquals(83, $resp->json('efficiency_pct')); // 2.5/3 = 83%
}
// ── M14 ──
public function test_ocr_job_can_be_queued_and_processed(): void
{
\Queue::fake();
$jobModel = \App\Models\Tenant\OcrJob::create([
'company_id' => $this->company->id,
'source_type' => 'pdf', 'file_path' => 'imports/test.pdf', 'status' => 'pending',
]);
\App\Jobs\ProcessOcrJob::dispatch($jobModel->id, $this->company->id);
\Queue::assertPushed(\App\Jobs\ProcessOcrJob::class, fn ($j) => $j->ocrJobId === $jobModel->id);
}
// ── M15 ──
public function test_tracking_json_endpoint_returns_status_payload(): void
{
$client = Client::create(['name' => 'C', 'phone' => '+37399000000', 'type' => 'individual', 'status' => 'active']);
$vehicle = Vehicle::create(['client_id' => $client->id, 'make' => 'BMW', 'model' => 'X5', 'plate' => 'JS-1']);
$wo = WorkOrder::create([
'number' => WorkOrder::generateNumber($this->company->id),
'client_id' => $client->id, 'vehicle_id' => $vehicle->id,
'opened_at' => today(), 'status' => 'in_work', 'total' => 500,
'eta_promised' => now()->addHours(3),
'eta_at' => now()->addHours(4),
'eta_change_reason' => 'Aștept piesă',
]);
$resp = $this->getJson("/api/track/{$wo->tracking_token}");
$resp->assertOk();
$this->assertEquals($wo->number, $resp->json('number'));
$this->assertEquals('in_work', $resp->json('status'));
$this->assertEquals('Aștept piesă', $resp->json('eta_change_reason'));
$this->assertNotNull($resp->json('eta_promised'));
$this->assertNotNull($resp->json('eta_current'));
}
public function test_tracking_json_returns_pending_approvals_with_signed_urls(): void
{
$client = Client::create(['name' => 'C', 'phone' => '+37399000000', 'type' => 'individual', 'status' => 'active']);
$wo = WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'client_id' => $client->id, 'opened_at' => today(), 'status' => 'in_work', 'total' => 0]);
WorkOrderWork::create(['work_order_id' => $wo->id, 'name' => 'Needs OK', 'hours' => 1, 'price_per_hour' => 200, 'requires_approval' => true]);
$resp = $this->getJson("/api/track/{$wo->tracking_token}");
$resp->assertOk();
$this->assertCount(1, $resp->json('pending_approvals'));
$this->assertEquals('work', $resp->json('pending_approvals.0.kind'));
$this->assertStringContainsString('/approve/work/', $resp->json('pending_approvals.0.approve_url'));
}
public function test_dispatcher_writes_notification_log_entry(): void
{
$client = Client::create(['name' => 'C', 'phone' => '+37399000000', 'email' => 'c@e.com', 'type' => 'individual', 'status' => 'active']);
$wo = WorkOrder::create(['number' => WorkOrder::generateNumber($this->company->id), 'client_id' => $client->id, 'opened_at' => today(), 'closed_at' => today(), 'status' => 'ready', 'total' => 500]);
\Mail::fake();
app(\App\Services\NotificationDispatcher::class)->workOrderReady($wo);
$log = ClientNotificationLog::where('work_order_id', $wo->id)->first();
$this->assertNotNull($log);
$this->assertEquals('wo_ready', $log->template_key);
$this->assertContains($log->channel, ['email', 'telegram']);
$this->assertEquals($wo->id, $log->work_order_id);
}
public function test_vehicle_body_and_transmission_round_trip(): void
{
$v = Vehicle::create(['client_id' => $this->makeClient()->id, 'make' => 'VW', 'model' => 'Tiguan', 'plate' => 'VR-1', 'body_type' => 'crossover', 'transmission_type' => 'dsg']);
$fresh = Vehicle::find($v->id);
$this->assertEquals('crossover', $fresh->body_type);
$this->assertEquals('dsg', $fresh->transmission_type);
}
}