Big changes added events for decisions

This commit is contained in:
Simon Pocrnjič
2025-10-22 23:20:04 +02:00
parent 872b76b012
commit 67ebe4b225
36 changed files with 2240 additions and 189 deletions
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Events;
use App\Models\Activity;
class ActivityDecisionApplied
{
public function __construct(public Activity $activity) {}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Events;
use App\Models\Contract;
use Illuminate\Foundation\Events\Dispatchable;
class ChangeContractSegment
{
use Dispatchable;
public function __construct(
public Contract $contract,
public int $segmentId,
public bool $deactivatePrevious = true,
) {}
}
-42
View File
@@ -1,42 +0,0 @@
<?php
namespace App\Events;
use App\Models\ClientCase;
use App\Models\Segment;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ClientCaseToTerrain implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public ClientCase $clientCase;
/**
* Create a new event instance.
*/
public function __construct(ClientCase $clientCase)
{
$this->clientCase = $clientCase;
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): PrivateChannel
{
return new PrivateChannel('segments'.$this->clientCase->id);
}
public function broadcastAs(){
return 'client_case.terrain.add';
}
}
-43
View File
@@ -1,43 +0,0 @@
<?php
namespace App\Events;
use App\Models\Contract;
use App\Models\Segment;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ContractToTerrain implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public Contract $contract;
public Segment $segment;
/**
* Create a new event instance.
*/
public function __construct(Contract $contract, Segment $segment)
{
//
$this->contract = $contract;
$this->segment = $segment;
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): PrivateChannel
{
return new PrivateChannel('contracts.'.$this->segment->id);
}
public function broadcastAs(){
return 'contract.terrain.add';
}
}
+84
View File
@@ -489,6 +489,90 @@ public function getEvents(Import $import)
return response()->json(['events' => $events]);
}
// List unresolved keyref contract rows (based on events containing keyref-not-found)
public function missingKeyrefRows(Import $import)
{
// Identify row IDs from events. Prefer specific event key, fallback to message pattern
$rowIds = \App\Models\ImportEvent::query()
->where('import_id', $import->id)
->where(function ($q) {
$q->where('event', 'contract_keyref_not_found')
->orWhereRaw('LOWER(message) LIKE ?', ['%keyref%not found%']);
})
->whereNotNull('import_row_id')
->pluck('import_row_id')
->filter()
->unique()
->values();
if ($rowIds->isEmpty()) {
return response()->json([
'columns' => (array) ($import->meta['columns'] ?? []),
'rows' => [],
]);
}
$rows = \App\Models\ImportRow::query()
->where('import_id', $import->id)
->whereIn('id', $rowIds)
->orderBy('row_number')
->get(['id', 'row_number', 'raw_data']);
$columns = (array) ($import->meta['columns'] ?? []);
// If no stored header, derive from first row raw_data keys
if (empty($columns)) {
$first = $rows->first();
if ($first && is_array($first->raw_data)) {
$columns = array_keys($first->raw_data);
}
}
// Normalize each row to ordered array by $columns
$dataRows = [];
foreach ($rows as $r) {
$line = [];
foreach ($columns as $col) {
$line[] = (string) ($r->raw_data[$col] ?? '');
}
$dataRows[] = [
'id' => $r->id,
'row_number' => $r->row_number,
'values' => $line,
];
}
return response()->json([
'columns' => $columns,
'rows' => $dataRows,
]);
}
// Export unresolved keyref rows as CSV (includes header if available)
public function exportMissingKeyrefCsv(Import $import)
{
$json = $this->missingKeyrefRows($import)->getData(true);
$columns = $json['columns'] ?? [];
$rows = $json['rows'] ?? [];
$fh = fopen('php://temp', 'r+');
if (! empty($columns)) {
fputcsv($fh, $columns);
}
foreach ($rows as $r) {
fputcsv($fh, $r['values'] ?? []);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
$filename = 'missing-keyref-rows-'.$import->id.'.csv';
return response($csv, 200, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
}
// Preview (up to N) raw CSV rows for an import for mapping review
public function preview(Import $import, Request $request)
{
+33 -3
View File
@@ -48,6 +48,7 @@ public function show(\App\Models\Segment $segment)
{
// Retrieve contracts that are active in this segment, eager-loading required relations
$search = request('search');
$clientFilter = request('client') ?? request('client_id'); // support either ?client=<uuid|id> or ?client_id=<id>
$contractsQuery = \App\Models\Contract::query()
->whereHas('segments', function ($q) use ($segment) {
$q->where('segments.id', $segment->id)
@@ -61,7 +62,18 @@ public function show(\App\Models\Segment $segment)
])
->latest('id');
if (!empty($search)) {
// Optional filter by client (accepts numeric id or client uuid)
if (! empty($clientFilter)) {
$contractsQuery->whereHas('clientCase.client', function ($q) use ($clientFilter) {
if (is_numeric($clientFilter)) {
$q->where('clients.id', (int) $clientFilter);
} else {
$q->where('clients.uuid', $clientFilter);
}
});
}
if (! empty($search)) {
$contractsQuery->where(function ($qq) use ($search) {
$qq->where('contracts.reference', 'ilike', '%'.$search.'%')
->orWhereHas('clientCase.person', function ($p) use ($search) {
@@ -88,9 +100,27 @@ public function show(\App\Models\Segment $segment)
$contracts->setCollection($items);
}
// Build a full client list for this segment (not limited to current page) for the dropdown
$clients = \App\Models\Client::query()
->whereHas('clientCases.contracts.segments', function ($q) use ($segment) {
$q->where('segments.id', $segment->id)
->where('contract_segment.active', '=', 1);
})
->with(['person:id,full_name'])
->get(['uuid', 'person_id'])
->map(function ($c) {
return [
'uuid' => (string) $c->uuid,
'name' => (string) optional($c->person)->full_name,
];
})
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
->values();
return Inertia::render('Segments/Show', [
'segment' => $segment->only(['id','name','description']),
'segment' => $segment->only(['id', 'name', 'description']),
'contracts' => $contracts,
'clients' => $clients,
]);
}
@@ -120,7 +150,7 @@ public function update(UpdateSegmentRequest $request, Segment $segment)
'name' => $data['name'],
'description' => $data['description'] ?? null,
'active' => $data['active'] ?? $segment->active,
'exclude' => $data['exclude'] ?? $segment->exclude
'exclude' => $data['exclude'] ?? $segment->exclude,
]);
return to_route('settings.segments')->with('success', 'Segment updated');
+130 -3
View File
@@ -3,10 +3,12 @@
namespace App\Http\Controllers;
use App\Models\Action;
use App\Models\ArchiveSetting;
use App\Models\Decision;
use App\Models\EmailTemplate;
use App\Models\Segment;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
class WorkflowController extends Controller
@@ -15,9 +17,11 @@ public function index(Request $request)
{
return Inertia::render('Settings/Workflow/Index', [
'actions' => Action::query()->with(['decisions', 'segment'])->withCount('activities')->orderBy('id')->get(),
'decisions' => Decision::query()->with('actions')->withCount('activities')->orderBy('id')->get(),
'decisions' => Decision::query()->with(['actions', 'events'])->withCount('activities')->orderBy('id')->get(),
'segments' => Segment::query()->get(),
'email_templates' => EmailTemplate::query()->where('active', true)->get(['id', 'name', 'entity_types']),
'events' => \App\Models\Event::query()->orderBy('name')->get(['id', 'name', 'key', 'description', 'active']),
'archive_settings' => ArchiveSetting::query()->where('enabled', true)->orderBy('id')->get(['id', 'name']),
]);
}
@@ -87,11 +91,43 @@ public function storeDecision(Request $request)
'actions' => 'nullable|array',
'actions.*.id' => 'required_with:actions.*|integer|exists:actions,id',
'actions.*.name' => 'required_with:actions.*|string|max:50',
'events' => 'nullable|array',
'events.*.id' => 'required_with:events.*|integer|exists:events,id',
'events.*.active' => 'sometimes|boolean',
'events.*.run_order' => 'nullable|integer',
'events.*.config' => 'nullable|array',
]);
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
$eventsPayload = collect($attributes['events'] ?? []);
\DB::transaction(function () use ($attributes, $actionIds) {
// Extra server-side validation for event-specific config keys
$validationErrors = [];
foreach ($eventsPayload as $i => $ev) {
$idEv = isset($ev['id']) ? (int) $ev['id'] : null;
if (! $idEv) {
continue;
}
$eventModel = \App\Models\Event::find($idEv);
$key = $eventModel?->key ?? ($ev['key'] ?? null);
if ($key === 'add_segment') {
$seg = $ev['config']['segment_id'] ?? null;
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
}
} elseif ($key === 'archive_contract') {
$as = $ev['config']['archive_setting_id'] ?? null;
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
}
}
}
if (! empty($validationErrors)) {
throw ValidationException::withMessages($validationErrors);
}
\DB::transaction(function () use ($attributes, $actionIds, $eventsPayload) {
/** @var \App\Models\Decision $row */
$row = Decision::create([
'name' => $attributes['name'],
@@ -103,6 +139,32 @@ public function storeDecision(Request $request)
if (! empty($actionIds)) {
$row->actions()->sync($actionIds);
}
// Attach decision events with pivot attributes
if ($eventsPayload->isNotEmpty()) {
$sync = [];
foreach ($eventsPayload as $ev) {
$id = (int) ($ev['id'] ?? 0);
if ($id <= 0) {
continue;
}
$cfg = $ev['config'] ?? null;
if (is_array($cfg)) {
$cfg = json_encode($cfg);
} elseif (is_string($cfg)) {
$trim = trim($cfg);
$cfg = $trim === '' ? null : $cfg;
} else {
$cfg = null;
}
$sync[$id] = [
'active' => (bool) ($ev['active'] ?? true),
'run_order' => isset($ev['run_order']) ? (int) $ev['run_order'] : null,
'config' => $cfg,
];
}
$row->events()->sync($sync);
}
});
return to_route('settings.workflow')->with('success', 'Decision created successfully!');
@@ -120,11 +182,43 @@ public function updateDecision(int $id, Request $request)
'actions' => 'nullable|array',
'actions.*.id' => 'required_with:actions.*|integer|exists:actions,id',
'actions.*.name' => 'required_with:actions.*|string|max:50',
'events' => 'nullable|array',
'events.*.id' => 'required_with:events.*|integer|exists:events,id',
'events.*.active' => 'sometimes|boolean',
'events.*.run_order' => 'nullable|integer',
'events.*.config' => 'nullable|array',
]);
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
$eventsPayload = collect($attributes['events'] ?? []);
\DB::transaction(function () use ($attributes, $actionIds, $row) {
// Extra server-side validation for event-specific config keys
$validationErrors = [];
foreach ($eventsPayload as $i => $ev) {
$idEv = isset($ev['id']) ? (int) $ev['id'] : null;
if (! $idEv) {
continue;
}
$eventModel = \App\Models\Event::find($idEv);
$key = $eventModel?->key ?? ($ev['key'] ?? null);
if ($key === 'add_segment') {
$seg = $ev['config']['segment_id'] ?? null;
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
}
} elseif ($key === 'archive_contract') {
$as = $ev['config']['archive_setting_id'] ?? null;
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
}
}
}
if (! empty($validationErrors)) {
throw ValidationException::withMessages($validationErrors);
}
\DB::transaction(function () use ($attributes, $actionIds, $eventsPayload, $row) {
$row->update([
'name' => $attributes['name'],
'color_tag' => $attributes['color_tag'] ?? null,
@@ -132,6 +226,39 @@ public function updateDecision(int $id, Request $request)
'email_template_id' => $attributes['email_template_id'] ?? null,
]);
$row->actions()->sync($actionIds);
// Sync decision events with pivot attributes
if ($eventsPayload->isNotEmpty()) {
$sync = [];
foreach ($eventsPayload as $ev) {
$id = (int) ($ev['id'] ?? 0);
if ($id <= 0) {
continue;
}
$cfg = $ev['config'] ?? null;
// ensure string JSON stored; accept already-JSON strings
if (is_array($cfg)) {
$cfg = json_encode($cfg);
} elseif (is_string($cfg)) {
$trim = trim($cfg);
// If not valid JSON, keep raw string (handler side can parse/ignore)
$cfg = $trim === '' ? null : $cfg;
} else {
$cfg = null;
}
$sync[$id] = [
'active' => (bool) ($ev['active'] ?? true),
'run_order' => isset($ev['run_order']) ? (int) $ev['run_order'] : null,
'config' => $cfg,
];
}
$row->events()->sync($sync);
} else {
// If empty provided explicitly, detach all to reflect UI intent
if (array_key_exists('events', $attributes)) {
$row->events()->detach();
}
}
});
return to_route('settings.workflow')->with('success', 'Decision updated successfully!');
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Jobs;
use App\Models\Activity;
use App\Models\Contract;
use App\Models\FieldJob;
use App\Models\FieldJobSetting;
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\DB;
class EndFieldJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $activityId,
public ?int $contractId = null,
public array $config = []
) {}
public function handle(): void
{
$activity = Activity::query()->find($this->activityId);
// Determine target contract ID
$contractId = $this->contractId;
if (! $contractId && $activity) {
$contractId = $activity->contract_id;
}
if (! $contractId) {
\Log::warning('EndFieldJob: missing contract id', ['activity_id' => $this->activityId]);
return;
}
// Use latest FieldJobSetting as the source of action/decision/segments
$setting = FieldJobSetting::query()->latest('id')->first();
$triggeredByEvent = (bool) $activity; // this job is invoked from a decision event when an Activity exists
DB::transaction(function () use ($contractId, $setting, $triggeredByEvent): void {
// Find active field job for this contract
$job = FieldJob::query()
->where('contract_id', $contractId)
->whereNull('completed_at')
->whereNull('cancelled_at')
->latest('id')
->first();
if ($job) {
// Complete the job (updated hook moves segment appropriately)
$job->completed_at = now();
$job->save();
// Optionally log a completion activity.
// By default, we SKIP creating an extra activity when triggered by a decision event (to avoid duplicates).
// To force creation from an event, set config['create_activity_from_event'] = true on the decision event.
// For non-event triggers, set config['create_activity'] = true to allow creation.
$shouldCreateActivity = $triggeredByEvent
? (bool) ($this->config['create_activity_from_event'] ?? false)
: (bool) ($this->config['create_activity'] ?? false);
if ($shouldCreateActivity) {
$job->loadMissing('contract');
$actionId = optional($job->setting)->action_id ?? optional($setting)->action_id;
$decisionId = optional($job->setting)->complete_decision_id ?? optional($setting)->complete_decision_id;
if ($actionId && $decisionId && $job->contract) {
Activity::create([
'due_date' => null,
'amount' => null,
'note' => 'Terensko opravilo zaključeno',
'action_id' => $actionId,
'decision_id' => $decisionId,
'client_case_id' => $job->contract->client_case_id,
'contract_id' => $job->contract_id,
]);
}
}
} else {
// No active job: still move contract to the configured return segment if available
if ($setting && $setting->return_segment_id) {
$tmp = new FieldJob;
$tmp->contract_id = $contractId;
$tmp->moveContractToSegment($setting->return_segment_id);
}
}
});
\Log::info('EndFieldJob executed', [
'activity_id' => $this->activityId,
'contract_id' => $contractId,
'config' => $this->config,
]);
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Jobs;
use App\Models\Activity;
use App\Models\Event as DecisionEventModel;
use App\Services\DecisionEvents\DecisionEventContext;
use App\Services\DecisionEvents\Registry;
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\DB;
class RunDecisionEvent implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $activityId,
public int $eventId,
public string $eventKey,
public array $config = [],
) {}
public function handle(): void
{
// Basic idempotency key per activity+event
$idempotencyKey = sha1($this->activityId.'|'.$this->eventId.'|'.$this->eventKey);
// Ensure log table record and uniqueness
$exists = DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->first();
if ($exists && ($exists->status ?? null) === 'succeeded') {
return; // already processed successfully
}
try {
$activity = Activity::with(['decision', 'contract', 'clientCase.client', 'user'])->findOrFail($this->activityId);
if (! $exists) {
DB::table('decision_event_logs')->insert([
'decision_id' => optional($activity->decision)->id,
'event_id' => $this->eventId,
'activity_id' => $this->activityId,
'handler' => $this->eventKey,
'status' => 'queued',
'idempotency_key' => $idempotencyKey,
'created_at' => now(),
'updated_at' => now(),
]);
$exists = (object) ['status' => 'queued'];
}
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
'status' => 'running',
'started_at' => now(),
'updated_at' => now(),
]);
$event = DecisionEventModel::findOrFail($this->eventId);
$handler = Registry::resolve($this->eventKey);
$context = new DecisionEventContext(
activity: $activity,
decision: $activity->decision,
contract: $activity->contract,
clientCase: $activity->clientCase,
client: optional($activity->clientCase)->client,
user: $activity->user,
);
$handler->handle($context, $this->config);
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
'status' => 'succeeded',
'finished_at' => now(),
'updated_at' => now(),
]);
} catch (\Throwable $e) {
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
'status' => 'failed',
'message' => substr($e->getMessage(), 0, 2000),
'finished_at' => now(),
'updated_at' => now(),
]);
throw $e; // allow retry
}
}
}
-41
View File
@@ -1,41 +0,0 @@
<?php
namespace App\Listeners;
use App\Events\ClientCaseToTerrain;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class AddClientCaseToTerrain
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(ClientCaseToTerrain $event): void
{
$clientCase = $event->clientCase;
$segment = \App\Models\Segment::where('name','terrain')->firstOrFail();
if( $segment ) {
$clientCase->segments()->detach($segment->id);
$clientCase->segments()->attach(
$segment->id,
);
\Log::info("Added contract to terrain", ['contract_id' => $clientCase->id, 'segment' => $segment->name ]);
}
}
public function failed(ClientCaseToTerrain $event, $exception)
{
\Log::error('Failed to update inventory', ['contract_id' => $event->clientCase->id, 'error' => $exception->getMessage()]);
}
}
-37
View File
@@ -1,37 +0,0 @@
<?php
namespace App\Listeners;
use App\Events\ContractToTerrain;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class AddContractToTerrain implements ShouldQueue
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(ContractToTerrain $event): void
{
$contract = $event->contract;
$segment = $event->segment->where('name', 'terrain')->firstOrFail();
if($segment) {
$contract->segments()->attach($segment->id);
//\Log::info("Added contract to terrain", ['contract_id' => $contract->id, 'segment' => $segment->name ]);
}
}
public function failed(ContractToTerrain $event, $exception)
{
//\Log::error('Failed to update inventory', ['contract_id' => $event->contract->id, 'error' => $exception->getMessage()]);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Listeners;
use App\Events\ChangeContractSegment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
class ApplyChangeContractSegment implements ShouldQueue
{
public function handle(ChangeContractSegment $event): void
{
$contract = $event->contract;
$segmentId = (int) $event->segmentId;
if ($segmentId <= 0) {
return;
}
DB::transaction(function () use ($contract, $segmentId, $event) {
if ($event->deactivatePrevious) {
DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('active', 1)
->update(['active' => 0, 'updated_at' => now()]);
}
$existing = DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('segment_id', $segmentId)
->first();
if ($existing) {
DB::table('contract_segment')
->where('id', $existing->id)
->update(['active' => 1, 'updated_at' => now()]);
} else {
DB::table('contract_segment')->insert([
'contract_id' => $contract->id,
'segment_id' => $segmentId,
'active' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
}
});
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Listeners;
use App\Events\ActivityDecisionApplied;
use App\Jobs\RunDecisionEvent;
use Illuminate\Support\Facades\Bus;
class TriggerDecisionEvents
{
public function handle(ActivityDecisionApplied $event): void
{
$activity = $event->activity->loadMissing(['decision.events' => function ($q) {
$q->wherePivot('active', true);
}, 'contract', 'clientCase.client', 'user']);
$decision = $activity->decision;
if (! $decision) {
return;
}
$events = $decision->events;
if ($events->isEmpty()) {
return;
}
// Sort by run_order when provided; otherwise keep natural order
$sorted = $events->sortBy(function ($ev) {
return $ev->pivot?->run_order ?? PHP_INT_MAX;
})->values();
$jobs = [];
foreach ($sorted as $ev) {
$base = is_array($ev->config ?? null) ? $ev->config : [];
$pivotCfgRaw = $ev->pivot?->config ?? null;
$pivotCfg = is_array($pivotCfgRaw)
? $pivotCfgRaw
: (is_string($pivotCfgRaw) ? (json_decode($pivotCfgRaw, true) ?: []) : []);
$effectiveConfig = array_replace_recursive($base, $pivotCfg);
$jobs[] = new RunDecisionEvent(
activityId: $activity->id,
eventId: $ev->id,
eventKey: (string) ($ev->key ?? ''),
config: $effectiveConfig,
);
}
// If any event has a finite run_order, chain to enforce order; else dispatch in parallel
$hasOrder = $sorted->contains(fn ($ev) => $ev->pivot?->run_order !== null);
// Run synchronously for local/dev/testing (or when debug is on) to ensure immediate effects without a queue worker
$shouldRunSync = app()->environment(['local', 'development', 'dev', 'testing'])
|| (bool) config('app.debug')
|| config('queue.default') === 'sync';
if ($hasOrder) {
if ($shouldRunSync) {
foreach ($jobs as $job) {
Bus::dispatchSync($job);
}
} else {
Bus::chain($jobs)->dispatch();
}
} else {
if ($shouldRunSync) {
foreach ($jobs as $job) {
Bus::dispatchSync($job);
}
} else {
foreach ($jobs as $job) {
dispatch($job);
}
}
}
}
}
+6
View File
@@ -49,6 +49,12 @@ protected static function booted()
);
}
});
static::created(function (Activity $activity) {
if (! empty($activity->decision_id)) {
event(new \App\Events\ActivityDecisionApplied($activity));
}
});
}
public function action(): BelongsTo
+3 -1
View File
@@ -29,7 +29,9 @@ public function actions(): BelongsToMany
public function events(): BelongsToMany
{
return $this->belongsToMany(\App\Models\Event::class);
return $this->belongsToMany(\App\Models\Event::class)
->withPivot(['run_order', 'active', 'config'])
->withTimestamps();
}
public function activities(): HasMany
+12
View File
@@ -11,6 +11,18 @@ class Event extends Model
/** @use HasFactory<\Database\Factories\EventFactory> */
use HasFactory;
protected $fillable = [
'name', 'key', 'description', 'active', 'config',
];
protected function casts(): array
{
return [
'active' => 'boolean',
'config' => 'array',
];
}
public function decisions(): BelongsToMany
{
return $this->belongsToMany(\App\Models\Decision::class);
+10
View File
@@ -2,8 +2,12 @@
namespace App\Providers;
use App\Events\ActivityDecisionApplied;
use App\Events\ChangeContractSegment;
use App\Events\DocumentGenerated;
use App\Listeners\ApplyChangeContractSegment;
use App\Listeners\LogDocumentGenerated;
use App\Listeners\TriggerDecisionEvents;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
@@ -12,5 +16,11 @@ class EventServiceProvider extends ServiceProvider
DocumentGenerated::class => [
LogDocumentGenerated::class,
],
ActivityDecisionApplied::class => [
TriggerDecisionEvents::class,
],
ChangeContractSegment::class => [
ApplyChangeContractSegment::class,
],
];
}
@@ -0,0 +1,10 @@
<?php
namespace App\Services\DecisionEvents\Contracts;
use App\Services\DecisionEvents\DecisionEventContext;
interface DecisionEventHandler
{
public function handle(DecisionEventContext $context, array $config = []): void;
}
@@ -0,0 +1,22 @@
<?php
namespace App\Services\DecisionEvents;
use App\Models\Activity;
use App\Models\Client;
use App\Models\ClientCase;
use App\Models\Contract;
use App\Models\Decision;
use App\Models\User;
class DecisionEventContext
{
public function __construct(
public Activity $activity,
public ?Decision $decision,
public ?Contract $contract,
public ?ClientCase $clientCase,
public ?Client $client,
public ?User $user,
) {}
}
@@ -0,0 +1,58 @@
<?php
namespace App\Services\DecisionEvents\Handlers;
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\DecisionEventContext;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
class AddSegmentHandler implements DecisionEventHandler
{
public function handle(DecisionEventContext $context, array $config = []): void
{
$contract = $context->contract;
if (! $contract) {
// If no contract on activity, nothing to apply
return;
}
$segmentId = (int) ($config['segment_id'] ?? 0);
if ($segmentId <= 0) {
throw new InvalidArgumentException('add_segment requires a valid segment_id');
}
$deactivatePrevious = array_key_exists('deactivate_previous', $config)
? (bool) $config['deactivate_previous']
: true;
DB::transaction(function () use ($contract, $segmentId, $deactivatePrevious) {
if ($deactivatePrevious) {
DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('active', 1)
->update(['active' => 0, 'updated_at' => now()]);
}
// Ensure pivot exists and mark active=1
$existing = DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('segment_id', $segmentId)
->first();
if ($existing) {
DB::table('contract_segment')
->where('id', $existing->id)
->update(['active' => 1, 'updated_at' => now()]);
} else {
DB::table('contract_segment')->insert([
'contract_id' => $contract->id,
'segment_id' => $segmentId,
'active' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
}
});
}
}
@@ -0,0 +1,110 @@
<?php
namespace App\Services\DecisionEvents\Handlers;
use App\Models\ArchiveSetting;
use App\Services\Archiving\ArchiveExecutor;
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\DecisionEventContext;
class ArchiveContractHandler implements DecisionEventHandler
{
/**
* Config contract:
* - archive_setting_id: int (required) which ArchiveSetting to execute
* - reactivate: bool (optional) override ArchiveSetting->reactivate per run
*/
public function handle(DecisionEventContext $context, array $config = []): void
{
$activity = $context->activity;
// Require a contract_id from the activity per request requirements
$contractId = (int) ($activity->contract_id ?? 0);
if ($contractId <= 0) {
throw new \InvalidArgumentException('ArchiveContractHandler requires activity.contract_id');
}
$settingId = (int) ($config['archive_setting_id'] ?? 0);
if ($settingId <= 0) {
throw new \InvalidArgumentException('ArchiveContractHandler requires config.archive_setting_id');
}
$setting = ArchiveSetting::query()->findOrFail($settingId);
// Optionally override reactivate flag for this run
if (array_key_exists('reactivate', $config)) {
$setting->reactivate = (bool) $config['reactivate'];
}
$results = app(ArchiveExecutor::class)->executeSetting(
$setting,
['contract_id' => $contractId],
$activity->user_id ?? null,
null,
);
// If the ArchiveSetting specifies a segment, move the contract to that segment (mirror controller logic)
if (! empty($setting->segment_id)) {
try {
$segmentId = (int) $setting->segment_id;
$clientCase = $context->clientCase; // expected per context contract
$contract = $context->contract; // already loaded on context
if ($clientCase && $contract) {
\DB::transaction(function () use ($clientCase, $contract, $segmentId) {
// Ensure the segment is attached to the client case (activate if previously inactive)
$casePivot = \DB::table('client_case_segment')
->where('client_case_id', $clientCase->id)
->where('segment_id', $segmentId)
->first();
if (! $casePivot) {
\DB::table('client_case_segment')->insert([
'client_case_id' => $clientCase->id,
'segment_id' => $segmentId,
'active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
} elseif (! $casePivot->active) {
\DB::table('client_case_segment')
->where('id', $casePivot->id)
->update(['active' => true, 'updated_at' => now()]);
}
// Deactivate all current active contract segments
\DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('active', true)
->update(['active' => false, 'updated_at' => now()]);
// Attach or activate the target segment for this contract
$existing = \DB::table('contract_segment')
->where('contract_id', $contract->id)
->where('segment_id', $segmentId)
->first();
if ($existing) {
\DB::table('contract_segment')
->where('id', $existing->id)
->update(['active' => true, 'updated_at' => now()]);
} else {
\DB::table('contract_segment')->insert([
'contract_id' => $contract->id,
'segment_id' => $segmentId,
'active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
});
}
} catch (\Throwable $e) {
// Do not fail the event; log warning for diagnostics
logger()->warning('ArchiveContractHandler: failed to move contract to segment', [
'error' => $e->getMessage(),
'setting_id' => $setting->id,
'segment_id' => $setting->segment_id,
'contract_id' => $contractId,
]);
}
}
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Services\DecisionEvents\Handlers;
use App\Jobs\EndFieldJob;
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\DecisionEventContext;
use Illuminate\Support\Facades\Bus;
class EndFieldJobHandler implements DecisionEventHandler
{
/**
* Config contract:
* - any pass-through keys needed by the EndFieldJob implementation
*/
public function handle(DecisionEventContext $context, array $config = []): void
{
$activity = $context->activity;
$job = new EndFieldJob(
activityId: (int) $activity->id,
contractId: $activity->contract_id ? (int) $activity->contract_id : null,
config: $config,
);
// Run synchronously in local/dev/testing or when debug is on or queue driver is sync; otherwise queue it.
$shouldRunSync = app()->environment(['local', 'development', 'dev', 'testing'])
|| (bool) config('app.debug')
|| config('queue.default') === 'sync';
if ($shouldRunSync) {
Bus::dispatchSync($job);
} else {
dispatch($job);
}
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Services\DecisionEvents;
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\Handlers\AddSegmentHandler;
use InvalidArgumentException;
class Registry
{
/**
* Map of event keys to handler classes.
*
* @var array<string, class-string<DecisionEventHandler>>
*/
protected static array $map = [
'add_segment' => AddSegmentHandler::class,
'archive_contract' => \App\Services\DecisionEvents\Handlers\ArchiveContractHandler::class,
'end_field_job' => \App\Services\DecisionEvents\Handlers\EndFieldJobHandler::class,
];
public static function resolve(string $key): DecisionEventHandler
{
$key = trim(strtolower($key));
$class = static::$map[$key] ?? null;
if (! $class || ! class_exists($class)) {
throw new InvalidArgumentException("Unknown decision event handler for key: {$key}");
}
$handler = app($class);
if (! $handler instanceof DecisionEventHandler) {
throw new InvalidArgumentException("Handler for key {$key} must implement DecisionEventHandler");
}
return $handler;
}
}