Big changes added events for decisions
This commit is contained in:
parent
872b76b012
commit
67ebe4b225
10
app/Events/ActivityDecisionApplied.php
Normal file
10
app/Events/ActivityDecisionApplied.php
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use App\Models\Activity;
|
||||
|
||||
class ActivityDecisionApplied
|
||||
{
|
||||
public function __construct(public Activity $activity) {}
|
||||
}
|
||||
17
app/Events/ChangeContractSegment.php
Normal file
17
app/Events/ChangeContractSegment.php
Normal 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,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -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';
|
||||
}
|
||||
}
|
||||
|
|
@ -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';
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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
app/Jobs/EndFieldJob.php
Normal file
100
app/Jobs/EndFieldJob.php
Normal 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
app/Jobs/RunDecisionEvent.php
Normal file
88
app/Jobs/RunDecisionEvent.php
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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()]);
|
||||
}
|
||||
}
|
||||
|
|
@ -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()]);
|
||||
}
|
||||
}
|
||||
47
app/Listeners/ApplyChangeContractSegment.php
Normal file
47
app/Listeners/ApplyChangeContractSegment.php
Normal file
|
|
@ -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
app/Listeners/TriggerDecisionEvents.php
Normal file
77
app/Listeners/TriggerDecisionEvents.php
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
22
app/Services/DecisionEvents/DecisionEventContext.php
Normal file
22
app/Services/DecisionEvents/DecisionEventContext.php
Normal file
|
|
@ -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,
|
||||
) {}
|
||||
}
|
||||
58
app/Services/DecisionEvents/Handlers/AddSegmentHandler.php
Normal file
58
app/Services/DecisionEvents/Handlers/AddSegmentHandler.php
Normal file
|
|
@ -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(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
110
app/Services/DecisionEvents/Handlers/ArchiveContractHandler.php
Normal file
110
app/Services/DecisionEvents/Handlers/ArchiveContractHandler.php
Normal file
|
|
@ -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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
36
app/Services/DecisionEvents/Handlers/EndFieldJobHandler.php
Normal file
36
app/Services/DecisionEvents/Handlers/EndFieldJobHandler.php
Normal file
|
|
@ -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
app/Services/DecisionEvents/Registry.php
Normal file
36
app/Services/DecisionEvents/Registry.php
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// events table extra columns
|
||||
Schema::table('events', function (Blueprint $table) {
|
||||
if (! Schema::hasColumn('events', 'key')) {
|
||||
$table->string('key')->nullable()->after('id');
|
||||
}
|
||||
if (! Schema::hasColumn('events', 'description')) {
|
||||
$table->text('description')->nullable()->after('name');
|
||||
}
|
||||
if (! Schema::hasColumn('events', 'active')) {
|
||||
$table->boolean('active')->default(true)->after('name');
|
||||
}
|
||||
if (! Schema::hasColumn('events', 'config')) {
|
||||
$table->json('config')->nullable()->after('active');
|
||||
}
|
||||
});
|
||||
|
||||
// decision_event pivot enhancements
|
||||
if (Schema::hasTable('decision_event')) {
|
||||
Schema::table('decision_event', function (Blueprint $table) {
|
||||
if (! Schema::hasColumn('decision_event', 'run_order')) {
|
||||
$table->integer('run_order')->nullable()->after('event_id');
|
||||
}
|
||||
if (! Schema::hasColumn('decision_event', 'active')) {
|
||||
$table->boolean('active')->default(true)->after('run_order');
|
||||
}
|
||||
if (! Schema::hasColumn('decision_event', 'config')) {
|
||||
$table->json('config')->nullable()->after('active');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// logs table
|
||||
if (! Schema::hasTable('decision_event_logs')) {
|
||||
Schema::create('decision_event_logs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignIdFor(\App\Models\Decision::class)->nullable();
|
||||
$table->foreignIdFor(\App\Models\Event::class, 'event_id');
|
||||
$table->foreignIdFor(\App\Models\Activity::class);
|
||||
$table->string('handler')->nullable();
|
||||
$table->enum('status', ['queued', 'running', 'succeeded', 'failed', 'skipped'])->default('queued');
|
||||
$table->text('message')->nullable();
|
||||
$table->string('idempotency_key')->unique();
|
||||
$table->timestamp('started_at')->nullable();
|
||||
$table->timestamp('finished_at')->nullable();
|
||||
$table->timestamps();
|
||||
$table->index(['decision_id', 'event_id']);
|
||||
$table->index(['activity_id']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (Schema::hasTable('decision_event_logs')) {
|
||||
Schema::drop('decision_event_logs');
|
||||
}
|
||||
|
||||
if (Schema::hasTable('decision_event')) {
|
||||
Schema::table('decision_event', function (Blueprint $table) {
|
||||
if (Schema::hasColumn('decision_event', 'config')) {
|
||||
$table->dropColumn('config');
|
||||
}
|
||||
if (Schema::hasColumn('decision_event', 'active')) {
|
||||
$table->dropColumn('active');
|
||||
}
|
||||
if (Schema::hasColumn('decision_event', 'run_order')) {
|
||||
$table->dropColumn('run_order');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Schema::table('events', function (Blueprint $table) {
|
||||
if (Schema::hasColumn('events', 'config')) {
|
||||
$table->dropColumn('config');
|
||||
}
|
||||
if (Schema::hasColumn('events', 'active')) {
|
||||
$table->dropColumn('active');
|
||||
}
|
||||
if (Schema::hasColumn('events', 'description')) {
|
||||
$table->dropColumn('description');
|
||||
}
|
||||
if (Schema::hasColumn('events', 'key')) {
|
||||
$table->dropColumn('key');
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -3,8 +3,8 @@
|
|||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
|
||||
use Illuminate\Database\Seeder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class EventSeeder extends Seeder
|
||||
{
|
||||
|
|
@ -13,12 +13,39 @@ class EventSeeder extends Seeder
|
|||
*/
|
||||
public function run(): void
|
||||
{
|
||||
$events = [
|
||||
[ 'name' => 'client_case.terrain.add', 'options' => json_encode([]) ]
|
||||
// Seed the new decision event type(s)
|
||||
// Use query builder to satisfy legacy NOT NULL "options" column
|
||||
$rows = [
|
||||
[
|
||||
'key' => 'add_segment',
|
||||
'name' => 'Add segment',
|
||||
'description' => 'Activates a target segment for a contract and deactivates previous ones.',
|
||||
],
|
||||
[
|
||||
'key' => 'archive_contract',
|
||||
'name' => 'Archive contract',
|
||||
'description' => 'Runs ArchiveExecutor for the activity\'s contract using a specified ArchiveSetting.',
|
||||
],
|
||||
[
|
||||
'key' => 'end_field_job',
|
||||
'name' => 'End field job',
|
||||
'description' => 'Dispatches a queued job to finalize field-related processing (implementation-specific).',
|
||||
],
|
||||
];
|
||||
|
||||
foreach($events as $e) {
|
||||
Event::create($e);
|
||||
foreach ($rows as $row) {
|
||||
DB::table('events')->updateOrInsert(
|
||||
['key' => $row['key']],
|
||||
[
|
||||
'name' => $row['name'],
|
||||
'description' => $row['description'],
|
||||
'active' => true,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'updated_at' => now(),
|
||||
'created_at' => now(),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ const decisions = ref(
|
|||
: []
|
||||
);
|
||||
|
||||
const emit = defineEmits(["close"]);
|
||||
const emit = defineEmits(["close", "saved"]);
|
||||
const close = () => emit("close");
|
||||
|
||||
const form = useForm({
|
||||
|
|
@ -123,6 +123,8 @@ const store = async () => {
|
|||
onSuccess: () => {
|
||||
close();
|
||||
form.reset("due_date", "amount", "note");
|
||||
// Notify parent to react (e.g., refresh, redirect in phone mode when no contracts left)
|
||||
emit("saved");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import SavedMappingsTable from "./Partials/SavedMappingsTable.vue";
|
|||
import LogsTable from "./Partials/LogsTable.vue";
|
||||
import ProcessResult from "./Partials/ProcessResult.vue";
|
||||
import { ref, computed, onMounted, watch } from "vue";
|
||||
import { router } from "@inertiajs/vue3";
|
||||
import Multiselect from "vue-multiselect";
|
||||
import axios from "axios";
|
||||
import Modal from "@/Components/Modal.vue"; // still potentially used elsewhere
|
||||
|
|
@ -150,6 +151,40 @@ async function openMissingContracts() {
|
|||
}
|
||||
}
|
||||
|
||||
// Unresolved keyref rows (contracts not found) UI state
|
||||
const showUnresolved = ref(false);
|
||||
const unresolvedLoading = ref(false);
|
||||
const unresolvedColumns = ref([]);
|
||||
const unresolvedRows = ref([]); // [{id,row_number,values:[]}]
|
||||
async function openUnresolved() {
|
||||
if (!importId.value || !contractRefIsKeyref.value) return;
|
||||
showUnresolved.value = true;
|
||||
unresolvedLoading.value = true;
|
||||
try {
|
||||
const { data } = await axios.get(
|
||||
route("imports.missing-keyref-rows", { import: importId.value }),
|
||||
{ headers: { Accept: "application/json" }, withCredentials: true }
|
||||
);
|
||||
unresolvedColumns.value = Array.isArray(data?.columns) ? data.columns : [];
|
||||
unresolvedRows.value = Array.isArray(data?.rows) ? data.rows : [];
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"Unresolved keyref rows fetch failed",
|
||||
e.response?.status || "",
|
||||
e.response?.data || e
|
||||
);
|
||||
unresolvedColumns.value = [];
|
||||
unresolvedRows.value = [];
|
||||
} finally {
|
||||
unresolvedLoading.value = false;
|
||||
}
|
||||
}
|
||||
function downloadUnresolvedCsv() {
|
||||
if (!importId.value) return;
|
||||
// Direct download
|
||||
window.location.href = route("imports.missing-keyref-csv", { import: importId.value });
|
||||
}
|
||||
|
||||
// Determine if all detected columns are mapped with entity+field
|
||||
function evaluateMappingSaved() {
|
||||
console.log("here the evaluation happen of mapping save!");
|
||||
|
|
@ -881,6 +916,9 @@ async function processImport() {
|
|||
}
|
||||
);
|
||||
processResult.value = data;
|
||||
// Immediately refresh the page props to reflect the completed state
|
||||
// Reload only the 'import' prop to minimize payload; don't preserve state so UI reflects new status
|
||||
router.reload({ only: ["import"], preserveScroll: true, preserveState: false });
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"Process import error",
|
||||
|
|
@ -1153,6 +1191,14 @@ async function fetchSimulation() {
|
|||
>
|
||||
Ogled manjkajoče
|
||||
</button>
|
||||
<button
|
||||
v-if="isCompleted && contractRefIsKeyref"
|
||||
class="px-3 py-1.5 bg-amber-600 text-white text-xs rounded"
|
||||
@click.prevent="openUnresolved"
|
||||
title="Prikaži vrstice, kjer pogodba (keyref) ni bila najdena"
|
||||
>
|
||||
Neobstoječi
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
|
|
@ -1331,6 +1377,67 @@ async function fetchSimulation() {
|
|||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<!-- Unresolved keyref rows modal -->
|
||||
<Modal :show="showUnresolved" max-width="5xl" @close="showUnresolved = false">
|
||||
<div class="p-4 max-h-[75vh] overflow-auto">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="font-semibold text-lg">
|
||||
Vrstice z neobstoječim contract.reference (KEYREF)
|
||||
</h3>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="px-3 py-1.5 bg-green-600 text-white text-xs rounded"
|
||||
@click.prevent="downloadUnresolvedCsv"
|
||||
>
|
||||
Prenesi CSV
|
||||
</button>
|
||||
<button
|
||||
class="text-gray-500 hover:text-gray-700"
|
||||
@click.prevent="showUnresolved = false"
|
||||
>
|
||||
Zapri
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="unresolvedLoading" class="py-8 text-center text-sm text-gray-500">
|
||||
Nalagam …
|
||||
</div>
|
||||
<div v-else>
|
||||
<div v-if="!unresolvedRows.length" class="py-6 text-sm text-gray-600">
|
||||
Ni zadetkov.
|
||||
</div>
|
||||
<div v-else class="overflow-auto border border-gray-200 rounded">
|
||||
<table class="min-w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-700">
|
||||
<tr>
|
||||
<th class="px-3 py-2 text-left w-24"># vrstica</th>
|
||||
<th
|
||||
v-for="(c, i) in unresolvedColumns"
|
||||
:key="i"
|
||||
class="px-3 py-2 text-left"
|
||||
>
|
||||
{{ c }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in unresolvedRows" :key="r.id" class="border-t">
|
||||
<td class="px-3 py-2 text-gray-500">{{ r.row_number }}</td>
|
||||
<td
|
||||
v-for="(c, i) in unresolvedColumns"
|
||||
:key="i"
|
||||
class="px-3 py-2 whitespace-pre-wrap break-words"
|
||||
>
|
||||
{{ r.values?.[i] ?? "" }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
<SimulationModal
|
||||
:show="showPaymentSim"
|
||||
:rows="paymentSimRows"
|
||||
|
|
|
|||
|
|
@ -6,13 +6,13 @@ import PersonDetailPhone from "@/Components/PersonDetailPhone.vue";
|
|||
// import DocumentsTable from '@/Components/DocumentsTable.vue';
|
||||
import DocumentViewerDialog from "@/Components/DocumentViewerDialog.vue";
|
||||
import { classifyDocument } from "@/Services/documents";
|
||||
import { reactive, ref, computed } from "vue";
|
||||
import { reactive, ref, computed, watch, onMounted } from "vue";
|
||||
import DialogModal from "@/Components/DialogModal.vue";
|
||||
import InputLabel from "@/Components/InputLabel.vue";
|
||||
import TextInput from "@/Components/TextInput.vue";
|
||||
import PrimaryButton from "@/Components/PrimaryButton.vue";
|
||||
import BasicButton from "@/Components/buttons/BasicButton.vue";
|
||||
import { useForm } from "@inertiajs/vue3";
|
||||
import { useForm, router } from "@inertiajs/vue3";
|
||||
import ActivityDrawer from "@/Pages/Cases/Partials/ActivityDrawer.vue";
|
||||
import ConfirmationModal from "@/Components/ConfirmationModal.vue";
|
||||
|
||||
|
|
@ -112,6 +112,37 @@ const closeDrawer = () => {
|
|||
drawerAddActivity.value = false;
|
||||
};
|
||||
|
||||
// After an activity is saved, if there are no contracts left for this case (assigned to me),
|
||||
// redirect back to the Phone index to pick the next case.
|
||||
const onActivitySaved = () => {
|
||||
// Inertia onSuccess already refreshed props, so props.contracts reflects current state.
|
||||
const count = Array.isArray(props.contracts) ? props.contracts.length : 0;
|
||||
if (count === 0) {
|
||||
router.visit(route("phone.index"));
|
||||
}
|
||||
};
|
||||
|
||||
// Also react if the page is reloaded with zero contracts (e.g., after EndFieldJob moves the only contract):
|
||||
const redirectIfNoContracts = () => {
|
||||
const count = Array.isArray(props.contracts) ? props.contracts.length : 0;
|
||||
if (count === 0) {
|
||||
router.visit(route("phone.index"));
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
redirectIfNoContracts();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => (Array.isArray(props.contracts) ? props.contracts.length : null),
|
||||
(len) => {
|
||||
if (len === 0) {
|
||||
router.visit(route("phone.index"));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Document upload state
|
||||
const docDialogOpen = ref(false);
|
||||
const docForm = useForm({
|
||||
|
|
@ -533,6 +564,7 @@ const clientSummary = computed(() => {
|
|||
<ActivityDrawer
|
||||
:show="drawerAddActivity"
|
||||
@close="closeDrawer"
|
||||
@saved="onActivitySaved"
|
||||
:client_case="client_case"
|
||||
:actions="actions"
|
||||
:contract-uuid="activityContractUuid"
|
||||
|
|
|
|||
|
|
@ -1,16 +1,20 @@
|
|||
<script setup>
|
||||
import AppLayout from "@/Layouts/AppLayout.vue";
|
||||
import { Link } from "@inertiajs/vue3";
|
||||
import { ref } from "vue";
|
||||
import { Link, router } from "@inertiajs/vue3";
|
||||
import { ref, computed, watch } from "vue";
|
||||
import DataTableServer from "@/Components/DataTable/DataTableServer.vue";
|
||||
|
||||
const props = defineProps({
|
||||
segment: Object,
|
||||
contracts: Object, // LengthAwarePaginator payload from Laravel
|
||||
clients: Array, // Full list of clients with contracts in this segment
|
||||
});
|
||||
|
||||
// Initialize search from current URL so input reflects server filter
|
||||
const search = ref(new URLSearchParams(window.location.search).get("search") || "");
|
||||
// Initialize search and client filter from current URL so inputs reflect server filters
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const search = ref(urlParams.get("search") || "");
|
||||
const initialClient = urlParams.get("client") || urlParams.get("client_id") || "";
|
||||
const selectedClient = ref(initialClient);
|
||||
|
||||
// Column definitions for the server-driven table
|
||||
const columns = [
|
||||
|
|
@ -23,6 +27,29 @@ const columns = [
|
|||
{ key: "account", label: "Stanje", align: "right" },
|
||||
];
|
||||
|
||||
// Build client options from the full list provided by the server, so the dropdown isn't limited by current filters
|
||||
const clientOptions = computed(() => {
|
||||
const list = Array.isArray(props.clients) ? props.clients : [];
|
||||
const opts = list.map((c) => ({
|
||||
value: c.uuid || "",
|
||||
label: c.name || "(neznana stranka)",
|
||||
}));
|
||||
return opts.sort((a, b) => (a.label || "").localeCompare(b.label || ""));
|
||||
});
|
||||
|
||||
// React to client selection changes by visiting the same route with updated query
|
||||
watch(selectedClient, (val) => {
|
||||
const query = { search: search.value };
|
||||
if (val) {
|
||||
query.client = val;
|
||||
}
|
||||
router.get(
|
||||
route("segments.show", { segment: props.segment?.id ?? props.segment }),
|
||||
query,
|
||||
{ preserveState: true, preserveScroll: true, only: ["contracts"], replace: true }
|
||||
);
|
||||
});
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) {
|
||||
return "-";
|
||||
|
|
@ -54,6 +81,36 @@ function formatCurrency(value) {
|
|||
<h2 class="text-lg">{{ segment.name }}</h2>
|
||||
<div class="text-sm text-gray-600 mb-4">{{ segment?.description }}</div>
|
||||
|
||||
<!-- Filters -->
|
||||
<div class="mb-4 flex flex-col sm:flex-row sm:items-end gap-3">
|
||||
<div class="flex-1">
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Stranka</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<select
|
||||
v-model="selectedClient"
|
||||
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm"
|
||||
>
|
||||
<option value="">Vse stranke</option>
|
||||
<option
|
||||
v-for="opt in clientOptions"
|
||||
:key="opt.value || opt.label"
|
||||
:value="opt.value"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
class="text-sm text-gray-600 hover:text-gray-900"
|
||||
@click="selectedClient = ''"
|
||||
v-if="selectedClient"
|
||||
>
|
||||
Počisti
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTableServer
|
||||
:columns="columns"
|
||||
:rows="contracts?.data || []"
|
||||
|
|
@ -61,6 +118,7 @@ function formatCurrency(value) {
|
|||
v-model:search="search"
|
||||
route-name="segments.show"
|
||||
:route-params="{ segment: segment?.id ?? segment }"
|
||||
:query="{ client: selectedClient || undefined }"
|
||||
:only-props="['contracts']"
|
||||
:page-size-options="[10, 25, 50]"
|
||||
empty-text="Ni pogodb v tem segmentu."
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script setup>
|
||||
// flowbite-vue table imports removed; using DataTableClient
|
||||
import { EditIcon, TrashBinIcon } from "@/Utilities/Icons";
|
||||
import { EditIcon, TrashBinIcon, DottedMenu } from "@/Utilities/Icons";
|
||||
import DialogModal from "@/Components/DialogModal.vue";
|
||||
import ConfirmationModal from "@/Components/ConfirmationModal.vue";
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import { computed, onMounted, ref, watch, nextTick } from "vue";
|
||||
import { router, useForm } from "@inertiajs/vue3";
|
||||
import InputLabel from "@/Components/InputLabel.vue";
|
||||
import TextInput from "@/Components/TextInput.vue";
|
||||
|
|
@ -12,11 +12,15 @@ import PrimaryButton from "@/Components/PrimaryButton.vue";
|
|||
import ActionMessage from "@/Components/ActionMessage.vue";
|
||||
import DataTableClient from "@/Components/DataTable/DataTableClient.vue";
|
||||
import InlineColorPicker from "@/Components/InlineColorPicker.vue";
|
||||
import Dropdown from "@/Components/Dropdown.vue";
|
||||
|
||||
const props = defineProps({
|
||||
decisions: Array,
|
||||
actions: Array,
|
||||
emailTemplates: { type: Array, default: () => [] },
|
||||
availableEvents: { type: Array, default: () => [] },
|
||||
segments: { type: Array, default: () => [] },
|
||||
archiveSettings: { type: Array, default: () => [] },
|
||||
});
|
||||
|
||||
const drawerEdit = ref(false);
|
||||
|
|
@ -38,6 +42,7 @@ const columns = [
|
|||
{ key: "id", label: "#", sortable: true, class: "w-16" },
|
||||
{ key: "name", label: "Ime", sortable: true },
|
||||
{ key: "color_tag", label: "Barva", sortable: false },
|
||||
{ key: "events", label: "Dogodki", sortable: false, class: "w-40" },
|
||||
{ key: "belongs", label: "Pripada akcijam", sortable: false, class: "w-40" },
|
||||
{ key: "auto_mail", label: "Auto mail", sortable: false, class: "w-46" },
|
||||
];
|
||||
|
|
@ -49,6 +54,7 @@ const form = useForm({
|
|||
actions: [],
|
||||
auto_mail: false,
|
||||
email_template_id: null,
|
||||
events: [],
|
||||
});
|
||||
|
||||
const createForm = useForm({
|
||||
|
|
@ -57,6 +63,7 @@ const createForm = useForm({
|
|||
actions: [],
|
||||
auto_mail: false,
|
||||
email_template_id: null,
|
||||
events: [],
|
||||
});
|
||||
|
||||
// When auto mail is disabled, also detach email template selection (edit form)
|
||||
|
|
@ -86,6 +93,27 @@ const openEditDrawer = (item) => {
|
|||
form.color_tag = item.color_tag;
|
||||
form.auto_mail = !!item.auto_mail;
|
||||
form.email_template_id = item.email_template_id || null;
|
||||
form.events = (item.events || []).map((ev) => {
|
||||
let cfgObj = {};
|
||||
const pCfg = ev.pivot?.config;
|
||||
if (typeof pCfg === "string" && pCfg.trim() !== "") {
|
||||
try {
|
||||
cfgObj = JSON.parse(pCfg);
|
||||
} catch (e) {
|
||||
cfgObj = {};
|
||||
}
|
||||
} else if (typeof pCfg === "object" && pCfg !== null) {
|
||||
cfgObj = pCfg;
|
||||
}
|
||||
return {
|
||||
id: ev.id,
|
||||
key: ev.key,
|
||||
name: ev.name,
|
||||
active: ev.pivot?.active ?? true,
|
||||
run_order: ev.pivot?.run_order ?? null,
|
||||
config: cfgObj,
|
||||
};
|
||||
});
|
||||
drawerEdit.value = true;
|
||||
|
||||
item.actions.forEach((a) => {
|
||||
|
|
@ -120,6 +148,69 @@ onMounted(() => {
|
|||
});
|
||||
});
|
||||
|
||||
function eventById(id) {
|
||||
return (props.availableEvents || []).find((e) => Number(e.id) === Number(id));
|
||||
}
|
||||
|
||||
function eventKey(ev) {
|
||||
const id = ev?.id;
|
||||
const found = eventById(id);
|
||||
return (found?.key || ev?.key || "").toString();
|
||||
}
|
||||
|
||||
function defaultConfigForKey(key) {
|
||||
switch (key) {
|
||||
case "add_segment":
|
||||
return { segment_id: null, deactivate_previous: true };
|
||||
case "archive_contract":
|
||||
return { archive_setting_id: null, reactivate: false };
|
||||
case "end_field_job":
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function adoptKeyAndName(ev) {
|
||||
const found = eventById(ev.id);
|
||||
if (found) {
|
||||
ev.key = found.key;
|
||||
ev.name = found.name;
|
||||
}
|
||||
}
|
||||
|
||||
function onEventChange(ev) {
|
||||
adoptKeyAndName(ev);
|
||||
const key = eventKey(ev);
|
||||
// Reset config to sensible defaults for the new key
|
||||
ev.config = defaultConfigForKey(key);
|
||||
// Clear any raw JSON cache
|
||||
if (ev.__rawJson !== undefined) delete ev.__rawJson;
|
||||
}
|
||||
|
||||
function defaultEventPayload() {
|
||||
const first = (props.availableEvents || [])[0] || { id: null, key: null, name: null };
|
||||
return {
|
||||
id: first.id || null,
|
||||
key: first.key || null,
|
||||
name: first.name || null,
|
||||
active: true,
|
||||
run_order: null,
|
||||
config: defaultConfigForKey(first.key || ""),
|
||||
};
|
||||
}
|
||||
|
||||
function tryAdoptRaw(ev) {
|
||||
try {
|
||||
const obj = JSON.parse(ev.__rawJson || "{}");
|
||||
if (obj && typeof obj === "object") {
|
||||
ev.config = obj;
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore parse error, leave raw as-is
|
||||
}
|
||||
}
|
||||
|
||||
const filtered = computed(() => {
|
||||
const term = search.value?.toLowerCase() ?? "";
|
||||
const tplId = selectedTemplateId.value ? Number(selectedTemplateId.value) : null;
|
||||
|
|
@ -135,21 +226,104 @@ const filtered = computed(() => {
|
|||
});
|
||||
|
||||
const update = () => {
|
||||
const clientErrors = validateEventsClientSide(form.events || []);
|
||||
if (Object.keys(clientErrors).length > 0) {
|
||||
// attach errors to form for display
|
||||
form.setErrors(clientErrors);
|
||||
scrollToFirstEventError(clientErrors, "edit");
|
||||
return;
|
||||
}
|
||||
|
||||
form.put(route("settings.decisions.update", { id: form.id }), {
|
||||
onSuccess: () => {
|
||||
closeEditDrawer();
|
||||
},
|
||||
onError: (errors) => {
|
||||
// preserve server errors for display
|
||||
scrollToFirstEventError(form.errors, "edit");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const store = () => {
|
||||
const clientErrors = validateEventsClientSide(createForm.events || []);
|
||||
if (Object.keys(clientErrors).length > 0) {
|
||||
createForm.setErrors(clientErrors);
|
||||
scrollToFirstEventError(clientErrors, "create");
|
||||
return;
|
||||
}
|
||||
|
||||
createForm.post(route("settings.decisions.store"), {
|
||||
onSuccess: () => {
|
||||
closeCreateDrawer();
|
||||
},
|
||||
onError: () => {
|
||||
scrollToFirstEventError(createForm.errors, "create");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
function validateEventsClientSide(events) {
|
||||
const errors = {};
|
||||
(events || []).forEach((ev, idx) => {
|
||||
const key = eventKey(ev);
|
||||
if (key === "add_segment") {
|
||||
if (!ev.config || !ev.config.segment_id) {
|
||||
errors[`events.${idx}.config.segment_id`] = "Izberite segment.";
|
||||
}
|
||||
} else if (key === "archive_contract") {
|
||||
if (!ev.config || !ev.config.archive_setting_id) {
|
||||
errors[`events.${idx}.config.archive_setting_id`] = "Izberite nastavitve arhiva.";
|
||||
}
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function scrollToFirstEventError(errorsBag, mode /* 'edit' | 'create' */) {
|
||||
const keys = Object.keys(errorsBag || {});
|
||||
// find first event-related error key
|
||||
const first = keys.find((k) =>
|
||||
/^events\.\d+\.config\.(segment_id|archive_setting_id)$/.test(k)
|
||||
);
|
||||
if (!first) return;
|
||||
const match = first.match(/^events\.(\d+)\.config\.(segment_id|archive_setting_id)$/);
|
||||
if (!match) return;
|
||||
const idx = Number(match[1]);
|
||||
const field = match[2];
|
||||
let targetId = null;
|
||||
if (field === "segment_id") {
|
||||
targetId = mode === "create" ? `cseg-${idx}` : `seg-${idx}`;
|
||||
} else if (field === "archive_setting_id") {
|
||||
targetId = mode === "create" ? `cas-${idx}` : `as-${idx}`;
|
||||
}
|
||||
if (!targetId) return;
|
||||
nextTick(() => {
|
||||
const el = document.getElementById(targetId);
|
||||
if (el && "scrollIntoView" in el) {
|
||||
el.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
// also focus the control for accessibility
|
||||
if ("focus" in el) {
|
||||
try {
|
||||
el.focus();
|
||||
} catch (e) {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const eventsValidEdit = computed(() => {
|
||||
const errs = validateEventsClientSide(form.events || []);
|
||||
return Object.keys(errs).length === 0;
|
||||
});
|
||||
|
||||
const eventsValidCreate = computed(() => {
|
||||
const errs = validateEventsClientSide(createForm.events || []);
|
||||
return Object.keys(errs).length === 0;
|
||||
});
|
||||
|
||||
const confirmDelete = (decision) => {
|
||||
toDelete.value = decision;
|
||||
showDelete.value = true;
|
||||
|
|
@ -218,6 +392,52 @@ const destroyDecision = () => {
|
|||
<template #cell-belongs="{ row }">
|
||||
{{ row.actions?.length ?? 0 }}
|
||||
</template>
|
||||
<template #cell-events="{ row }">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm text-gray-600">{{ row.events?.length ?? 0 }}</span>
|
||||
<Dropdown align="left" width="64" :close-on-content-click="false">
|
||||
<template #trigger>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 rounded hover:bg-gray-100 border border-transparent hover:border-gray-200"
|
||||
>
|
||||
<DottedMenu size="sm" css="text-gray-600" />
|
||||
</button>
|
||||
</template>
|
||||
<template #content>
|
||||
<div class="py-2">
|
||||
<div
|
||||
v-if="!row.events || row.events.length === 0"
|
||||
class="px-3 py-1 text-sm text-gray-500"
|
||||
>
|
||||
Ni dogodkov
|
||||
</div>
|
||||
<ul v-else class="max-h-64 overflow-auto">
|
||||
<li
|
||||
v-for="(ev, i) in row.events"
|
||||
:key="ev.id"
|
||||
class="px-3 py-1 text-sm flex items-center gap-2"
|
||||
>
|
||||
<span
|
||||
class="inline-flex items-center justify-center w-2 h-2 rounded-full"
|
||||
:class="ev.pivot?.active === false ? 'bg-gray-300' : 'bg-green-500'"
|
||||
></span>
|
||||
<span
|
||||
class="text-gray-800"
|
||||
:class="
|
||||
ev.pivot?.active === false ? 'line-through text-gray-400' : ''
|
||||
"
|
||||
>
|
||||
{{ ev.pivot?.run_order ?? i + 1 }}.
|
||||
{{ ev.name || ev.key || "#" + ev.id }}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</template>
|
||||
<template #cell-auto_mail="{ row }">
|
||||
<div class="flex flex-col text-sm">
|
||||
<span :class="row.auto_mail ? 'text-green-700' : 'text-gray-500'">{{
|
||||
|
|
@ -317,14 +537,161 @@ const destroyDecision = () => {
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end mt-4">
|
||||
<!-- Quick JSON event config editor -->
|
||||
<div class="mt-6">
|
||||
<h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
|
||||
<div class="space-y-4">
|
||||
<div v-for="(ev, idx) in form.events" :key="idx" class="border rounded p-3">
|
||||
<div class="flex flex-col sm:flex-row gap-3">
|
||||
<div class="flex-1">
|
||||
<InputLabel :for="`event-${idx}`" value="Dogodek" />
|
||||
<select
|
||||
:id="`event-${idx}`"
|
||||
v-model.number="ev.id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
@change="onEventChange(ev)"
|
||||
>
|
||||
<option :value="null">— Izberi —</option>
|
||||
<option v-for="opt in availableEvents" :key="opt.id" :value="opt.id">
|
||||
{{ opt.name || opt.key || `#${opt.id}` }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-36">
|
||||
<InputLabel :for="`order-${idx}`" value="Vrstni red" />
|
||||
<TextInput
|
||||
:id="`order-${idx}`"
|
||||
v-model.number="ev.run_order"
|
||||
type="number"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-end gap-2">
|
||||
<label class="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.active"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Aktivno
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="text-red-600 text-sm"
|
||||
@click="form.events.splice(idx, 1)"
|
||||
>
|
||||
Odstrani
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<template v-if="eventKey(ev) === 'add_segment'">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<InputLabel :for="`seg-${idx}`" value="Segment" />
|
||||
<select
|
||||
:id="`seg-${idx}`"
|
||||
v-model.number="ev.config.segment_id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
>
|
||||
<option :value="null">— Izberi segment —</option>
|
||||
<option v-for="s in segments" :key="s.id" :value="s.id">
|
||||
{{ s.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p
|
||||
v-if="form.errors[`events.${idx}.config.segment_id`]"
|
||||
class="text-xs text-red-600 mt-1"
|
||||
>
|
||||
{{ form.errors[`events.${idx}.config.segment_id`] }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-end">
|
||||
<label class="flex items-center gap-2 text-sm mt-6">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.config.deactivate_previous"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Deaktiviraj prejšnje
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="eventKey(ev) === 'archive_contract'">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<InputLabel :for="`as-${idx}`" value="Archive setting" />
|
||||
<select
|
||||
:id="`as-${idx}`"
|
||||
v-model.number="ev.config.archive_setting_id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
>
|
||||
<option :value="null">— Izberi nastavitev —</option>
|
||||
<option v-for="a in archiveSettings" :key="a.id" :value="a.id">
|
||||
{{ a.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p
|
||||
v-if="form.errors[`events.${idx}.config.archive_setting_id`]"
|
||||
class="text-xs text-red-600 mt-1"
|
||||
>
|
||||
{{ form.errors[`events.${idx}.config.archive_setting_id`] }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-end">
|
||||
<label class="flex items-center gap-2 text-sm mt-6">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.config.reactivate"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Reactivate namesto arhiva
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="eventKey(ev) === 'end_field_job'">
|
||||
<p class="text-sm text-gray-600">
|
||||
Ta dogodek nima dodatnih nastavitev.
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<!-- Fallback advanced editor for unknown event keys -->
|
||||
<InputLabel :for="`cfg-${idx}`" value="Napredna nastavitev (JSON)" />
|
||||
<textarea
|
||||
:id="`cfg-${idx}`"
|
||||
v-model="ev.__rawJson"
|
||||
@focus="
|
||||
ev.__rawJson =
|
||||
ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
|
||||
"
|
||||
@change="tryAdoptRaw(ev)"
|
||||
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
|
||||
rows="6"
|
||||
placeholder="{ }"
|
||||
></textarea>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<PrimaryButton
|
||||
type="button"
|
||||
@click="form.events.push(defaultEventPayload())"
|
||||
>+ Dodaj dogodek</PrimaryButton
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end mt-6">
|
||||
<ActionMessage :on="form.recentlySuccessful" class="me-3">
|
||||
Shranjuje.
|
||||
</ActionMessage>
|
||||
|
||||
<PrimaryButton
|
||||
:class="{ 'opacity-25': form.processing }"
|
||||
:disabled="form.processing"
|
||||
:class="{ 'opacity-25': form.processing || !eventsValidEdit }"
|
||||
:disabled="form.processing || !eventsValidEdit"
|
||||
>
|
||||
Shrani
|
||||
</PrimaryButton>
|
||||
|
|
@ -407,14 +774,166 @@ const destroyDecision = () => {
|
|||
/>
|
||||
</div>
|
||||
|
||||
<!-- Create: Decision events editor -->
|
||||
<div class="mt-6">
|
||||
<h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-for="(ev, idx) in createForm.events"
|
||||
:key="`c-${idx}`"
|
||||
class="border rounded p-3"
|
||||
>
|
||||
<div class="flex flex-col sm:flex-row gap-3">
|
||||
<div class="flex-1">
|
||||
<InputLabel :for="`cevent-${idx}`" value="Dogodek" />
|
||||
<select
|
||||
:id="`cevent-${idx}`"
|
||||
v-model.number="ev.id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
@change="onEventChange(ev)"
|
||||
>
|
||||
<option :value="null">— Izberi —</option>
|
||||
<option v-for="opt in availableEvents" :key="opt.id" :value="opt.id">
|
||||
{{ opt.name || opt.key || `#${opt.id}` }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-36">
|
||||
<InputLabel :for="`corder-${idx}`" value="Vrstni red" />
|
||||
<TextInput
|
||||
:id="`corder-${idx}`"
|
||||
v-model.number="ev.run_order"
|
||||
type="number"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-end gap-2">
|
||||
<label class="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.active"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Aktivno
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="text-red-600 text-sm"
|
||||
@click="createForm.events.splice(idx, 1)"
|
||||
>
|
||||
Odstrani
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<template v-if="eventKey(ev) === 'add_segment'">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<InputLabel :for="`cseg-${idx}`" value="Segment" />
|
||||
<select
|
||||
:id="`cseg-${idx}`"
|
||||
v-model.number="ev.config.segment_id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
>
|
||||
<option :value="null">— Izberi segment —</option>
|
||||
<option v-for="s in segments" :key="s.id" :value="s.id">
|
||||
{{ s.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p
|
||||
v-if="createForm.errors[`events.${idx}.config.segment_id`]"
|
||||
class="text-xs text-red-600 mt-1"
|
||||
>
|
||||
{{ createForm.errors[`events.${idx}.config.segment_id`] }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-end">
|
||||
<label class="flex items-center gap-2 text-sm mt-6">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.config.deactivate_previous"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Deaktiviraj prejšnje
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="eventKey(ev) === 'archive_contract'">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<InputLabel :for="`cas-${idx}`" value="Archive setting" />
|
||||
<select
|
||||
:id="`cas-${idx}`"
|
||||
v-model.number="ev.config.archive_setting_id"
|
||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||
>
|
||||
<option :value="null">— Izberi nastavitev —</option>
|
||||
<option v-for="a in archiveSettings" :key="a.id" :value="a.id">
|
||||
{{ a.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p
|
||||
v-if="
|
||||
createForm.errors[`events.${idx}.config.archive_setting_id`]
|
||||
"
|
||||
class="text-xs text-red-600 mt-1"
|
||||
>
|
||||
{{ createForm.errors[`events.${idx}.config.archive_setting_id`] }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-end">
|
||||
<label class="flex items-center gap-2 text-sm mt-6">
|
||||
<input
|
||||
type="checkbox"
|
||||
v-model="ev.config.reactivate"
|
||||
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||
/>
|
||||
Reactivate namesto arhiva
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="eventKey(ev) === 'end_field_job'">
|
||||
<p class="text-sm text-gray-600">
|
||||
Ta dogodek nima dodatnih nastavitev.
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<InputLabel :for="`ccfg-${idx}`" value="Napredna nastavitev (JSON)" />
|
||||
<textarea
|
||||
:id="`ccfg-${idx}`"
|
||||
v-model="ev.__rawJson"
|
||||
@focus="
|
||||
ev.__rawJson =
|
||||
ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
|
||||
"
|
||||
@change="tryAdoptRaw(ev)"
|
||||
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
|
||||
rows="6"
|
||||
placeholder="{ }"
|
||||
></textarea>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<PrimaryButton
|
||||
type="button"
|
||||
@click="createForm.events.push(defaultEventPayload())"
|
||||
>+ Dodaj dogodek</PrimaryButton
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end mt-4">
|
||||
<ActionMessage :on="createForm.recentlySuccessful" class="me-3">
|
||||
Shranjuje.
|
||||
</ActionMessage>
|
||||
|
||||
<PrimaryButton
|
||||
:class="{ 'opacity-25': createForm.processing }"
|
||||
:disabled="createForm.processing"
|
||||
:class="{ 'opacity-25': createForm.processing || !eventsValidCreate }"
|
||||
:disabled="createForm.processing || !eventsValidCreate"
|
||||
>
|
||||
Dodaj
|
||||
</PrimaryButton>
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ const props = defineProps({
|
|||
decisions: Array,
|
||||
segments: Array,
|
||||
email_templates: { type: Array, default: () => [] },
|
||||
events: { type: Array, default: () => [] },
|
||||
archive_settings: { type: Array, default: () => [] },
|
||||
});
|
||||
|
||||
const activeTab = ref("actions");
|
||||
|
|
@ -33,6 +35,9 @@ const activeTab = ref("actions");
|
|||
:decisions="decisions"
|
||||
:actions="actions"
|
||||
:email-templates="email_templates"
|
||||
:available-events="events"
|
||||
:segments="segments"
|
||||
:archive-settings="archive_settings"
|
||||
/>
|
||||
</fwb-tab>
|
||||
</fwb-tabs>
|
||||
|
|
|
|||
|
|
@ -326,6 +326,8 @@
|
|||
Route::post('imports/{import}/mappings', [ImportController::class, 'saveMappings'])->name('imports.mappings.save');
|
||||
Route::get('imports/{import}/mappings', [ImportController::class, 'getMappings'])->name('imports.mappings.get');
|
||||
Route::get('imports/{import}/events', [ImportController::class, 'getEvents'])->name('imports.events');
|
||||
Route::get('imports/{import}/missing-keyref-rows', [ImportController::class, 'missingKeyrefRows'])->name('imports.missing-keyref-rows');
|
||||
Route::get('imports/{import}/missing-keyref-csv', [ImportController::class, 'exportMissingKeyrefCsv'])->name('imports.missing-keyref-csv');
|
||||
Route::get('imports/{import}/preview', [ImportController::class, 'preview'])->name('imports.preview');
|
||||
Route::get('imports/{import}/missing-contracts', [ImportController::class, 'missingContracts'])->name('imports.missing-contracts');
|
||||
Route::post('imports/{import}/options', [ImportController::class, 'updateOptions'])->name('imports.options');
|
||||
|
|
|
|||
131
tests/Feature/Activities/ActivityTriggersDecisionEventsTest.php
Normal file
131
tests/Feature/Activities/ActivityTriggersDecisionEventsTest.php
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
<?php
|
||||
|
||||
use App\Models\Action;
|
||||
use App\Models\ArchiveSetting;
|
||||
use App\Models\Client;
|
||||
use App\Models\ClientCase;
|
||||
use App\Models\Contract;
|
||||
use App\Models\ContractType;
|
||||
use App\Models\Decision;
|
||||
use App\Models\Segment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
it('archives the contract when creating an activity with an archive event decision', function () {
|
||||
// Auth
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user);
|
||||
|
||||
// Minimal person/client/case
|
||||
$person = \App\Models\Person\Person::factory()->create([
|
||||
'first_name' => 'Test',
|
||||
'last_name' => 'User',
|
||||
'full_name' => 'Test User',
|
||||
]);
|
||||
$client = Client::create(['person_id' => $person->id]);
|
||||
$case = ClientCase::create([
|
||||
'client_id' => $client->id,
|
||||
'person_id' => $person->id,
|
||||
]);
|
||||
|
||||
// Contract to be archived
|
||||
$ctype = ContractType::factory()->create();
|
||||
$contract = Contract::create([
|
||||
'client_case_id' => $case->id,
|
||||
'reference' => 'R-TEST',
|
||||
'start_date' => now()->toDateString(),
|
||||
'type_id' => $ctype->id,
|
||||
'description' => 'Test',
|
||||
]);
|
||||
|
||||
// ensure exists before triggering
|
||||
expect($contract->id)->toBeGreaterThan(0);
|
||||
|
||||
// Action/Decision
|
||||
$segment = Segment::factory()->create();
|
||||
$action = Action::create(['name' => 'Call', 'color_tag' => '#000000', 'segment_id' => $segment->id]);
|
||||
$decision = Decision::create(['name' => 'Archive', 'color_tag' => '#ff0000', 'auto_mail' => false]);
|
||||
$action->decisions()->attach($decision->id);
|
||||
|
||||
// Create initial and archive segments
|
||||
$initialSegment = Segment::factory()->create();
|
||||
$archiveSegment = Segment::factory()->create();
|
||||
|
||||
// Ensure case and contract have an initial segment active
|
||||
DB::table('client_case_segment')->insert([
|
||||
'client_case_id' => $case->id,
|
||||
'segment_id' => $initialSegment->id,
|
||||
'active' => true,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
DB::table('contract_segment')->insert([
|
||||
'contract_id' => $contract->id,
|
||||
'segment_id' => $initialSegment->id,
|
||||
'active' => true,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// Archive setting (focus on contracts table, soft archive) with archive segment
|
||||
$setting = ArchiveSetting::create([
|
||||
'name' => 'Test archive',
|
||||
'enabled' => true,
|
||||
'strategy' => 'immediate',
|
||||
'soft' => true,
|
||||
'reactivate' => false,
|
||||
'segment_id' => $archiveSegment->id,
|
||||
'entities' => [
|
||||
[
|
||||
'table' => 'contracts',
|
||||
'focus' => true,
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// Event: archive_contract (ensure legacy NOT NULL options is satisfied)
|
||||
$eventId = DB::table('events')->insertGetId([
|
||||
'name' => 'Archive Contract',
|
||||
'key' => 'archive_contract',
|
||||
'description' => 'Archive selected contract',
|
||||
'active' => true,
|
||||
'options' => json_encode(new stdClass),
|
||||
'config' => json_encode(new stdClass),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// Attach event to decision with required config
|
||||
DB::table('decision_event')->insert([
|
||||
'decision_id' => $decision->id,
|
||||
'event_id' => $eventId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => json_encode(['archive_setting_id' => $setting->id]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// POST activity (should synchronously trigger decision events in testing env)
|
||||
$route = route('clientCase.activity.store', $case);
|
||||
$this->post($route, [
|
||||
'action_id' => $action->id,
|
||||
'decision_id' => $decision->id,
|
||||
'contract_uuid' => $contract->uuid,
|
||||
'note' => 'Trigger archive',
|
||||
])->assertSessionHasNoErrors();
|
||||
|
||||
// Contract should now be archived (active = 0)
|
||||
$fresh = $contract->fresh();
|
||||
expect((int) $fresh->active)->toBe(0);
|
||||
|
||||
// Segment should be moved to archive segment
|
||||
$activePivots = DB::table('contract_segment')->where('contract_id', $contract->id)->where('active', true)->get();
|
||||
expect($activePivots->count())->toBe(1);
|
||||
expect($activePivots->first()->segment_id)->toBe($archiveSegment->id);
|
||||
|
||||
// Case should have archive segment attached and active
|
||||
$caseSeg = DB::table('client_case_segment')->where('client_case_id', $case->id)->where('segment_id', $archiveSegment->id)->first();
|
||||
expect($caseSeg)->not->toBeNull();
|
||||
expect((int) $caseSeg->active)->toBe(1);
|
||||
});
|
||||
122
tests/Feature/Activities/ActivityTriggersEndFieldJobTest.php
Normal file
122
tests/Feature/Activities/ActivityTriggersEndFieldJobTest.php
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
<?php
|
||||
|
||||
use App\Models\Action;
|
||||
use App\Models\Client;
|
||||
use App\Models\ClientCase;
|
||||
use App\Models\Contract;
|
||||
use App\Models\Decision;
|
||||
use App\Models\FieldJob;
|
||||
use App\Models\FieldJobSetting;
|
||||
use App\Models\Segment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
it('completes field job and moves contract to return segment when end_field_job event fires', function () {
|
||||
// Auth user
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user);
|
||||
|
||||
// Minimal person/client/case
|
||||
$person = \App\Models\Person\Person::factory()->create([
|
||||
'first_name' => 'Job',
|
||||
'last_name' => 'Runner',
|
||||
'full_name' => 'Job Runner',
|
||||
]);
|
||||
$client = Client::create(['person_id' => $person->id]);
|
||||
$case = ClientCase::create([
|
||||
'client_id' => $client->id,
|
||||
'person_id' => $person->id,
|
||||
]);
|
||||
|
||||
$returnSeg = Segment::factory()->create(['name' => 'Return']);
|
||||
$fieldSeg = Segment::factory()->create(['name' => 'Field']);
|
||||
|
||||
$action = Action::create(['name' => 'Call', 'color_tag' => '#000', 'segment_id' => $returnSeg->id]);
|
||||
$decision = Decision::create(['name' => 'Finish field job', 'color_tag' => '#00f', 'auto_mail' => false]);
|
||||
$action->decisions()->attach($decision->id);
|
||||
|
||||
// Create a contract under the case and attach field segment as active
|
||||
$contract = Contract::create([
|
||||
'reference' => 'REF-2002',
|
||||
'client_case_id' => $case->id,
|
||||
'type_id' => \Database\Factories\ContractTypeFactory::new()->create()->id,
|
||||
'start_date' => now()->toDateString(),
|
||||
]);
|
||||
// Ensure both segments exist on the case and contract
|
||||
DB::table('client_case_segment')->insert([
|
||||
['client_case_id' => $case->id, 'segment_id' => $fieldSeg->id, 'active' => true, 'created_at' => now(), 'updated_at' => now()],
|
||||
['client_case_id' => $case->id, 'segment_id' => $returnSeg->id, 'active' => true, 'created_at' => now(), 'updated_at' => now()],
|
||||
]);
|
||||
DB::table('contract_segment')->insert([
|
||||
['contract_id' => $contract->id, 'segment_id' => $fieldSeg->id, 'active' => true, 'created_at' => now(), 'updated_at' => now()],
|
||||
['contract_id' => $contract->id, 'segment_id' => $returnSeg->id, 'active' => false, 'created_at' => now(), 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
// FieldJobSetting with return segment
|
||||
$setting = FieldJobSetting::create([
|
||||
'segment_id' => $fieldSeg->id,
|
||||
'assign_decision_id' => $decision->id, // not used here
|
||||
'complete_decision_id' => $decision->id,
|
||||
'return_segment_id' => $returnSeg->id,
|
||||
'queue_segment_id' => $fieldSeg->id,
|
||||
'action_id' => $action->id,
|
||||
]);
|
||||
|
||||
// Active FieldJob for this contract (simulates assignment)
|
||||
FieldJob::create([
|
||||
'field_job_setting_id' => $setting->id,
|
||||
'assigned_user_id' => $user->id,
|
||||
'contract_id' => $contract->id,
|
||||
'assigned_at' => now()->subDay(),
|
||||
]);
|
||||
|
||||
// Insert end_field_job event (satisfy legacy options NOT NULL)
|
||||
$eventId = DB::table('events')->insertGetId([
|
||||
'name' => 'End Field Job',
|
||||
'key' => 'end_field_job',
|
||||
'description' => 'Complete a field job',
|
||||
'active' => true,
|
||||
'options' => json_encode(new stdClass),
|
||||
'config' => json_encode(new stdClass),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
DB::table('decision_event')->insert([
|
||||
'decision_id' => $decision->id,
|
||||
'event_id' => $eventId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// Spy on logs to assert EndFieldJob ran
|
||||
Log::spy();
|
||||
|
||||
$this->post(route('clientCase.activity.store', $case), [
|
||||
'action_id' => $action->id,
|
||||
'decision_id' => $decision->id,
|
||||
'contract_uuid' => $contract->uuid,
|
||||
'note' => 'Finish job',
|
||||
])->assertSessionHasNoErrors();
|
||||
|
||||
// The active field job should be marked completed
|
||||
$completedJob = FieldJob::query()
|
||||
->where('contract_id', $contract->id)
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
expect($completedJob)->not()->toBeNull();
|
||||
expect($completedJob->completed_at)->not()->toBeNull();
|
||||
|
||||
// The contract should now be in return segment
|
||||
$activeSegIds = DB::table('contract_segment')
|
||||
->where('contract_id', $contract->id)
|
||||
->where('active', true)
|
||||
->pluck('segment_id');
|
||||
|
||||
expect($activeSegIds->contains($returnSeg->id))->toBeTrue();
|
||||
});
|
||||
91
tests/Feature/Workflow/StoreDecisionEventsTest.php
Normal file
91
tests/Feature/Workflow/StoreDecisionEventsTest.php
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<?php
|
||||
|
||||
use App\Models\Segment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\WithFaker;
|
||||
|
||||
uses(WithFaker::class);
|
||||
|
||||
it('creates a decision with add_segment event when config is valid', function () {
|
||||
$user = User::factory()->create([
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
$this->actingAs($user);
|
||||
|
||||
$segment = Segment::factory()->create();
|
||||
|
||||
$addSegmentEventId = \DB::table('events')->insertGetId([
|
||||
'name' => 'Add Segment',
|
||||
'key' => 'add_segment',
|
||||
'description' => 'Attach a segment to contract',
|
||||
'active' => 1,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$payload = [
|
||||
'name' => fake()->unique()->words(2, true),
|
||||
'color_tag' => null,
|
||||
'auto_mail' => false,
|
||||
'email_template_id' => null,
|
||||
'actions' => [],
|
||||
'events' => [
|
||||
[
|
||||
'id' => $addSegmentEventId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => [
|
||||
'segment_id' => $segment->id,
|
||||
'deactivate_previous' => true,
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->post(route('settings.decisions.store'), $payload);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
$response->assertRedirect(route('settings.workflow'));
|
||||
});
|
||||
|
||||
it('validates segment_id is required for add_segment event on create', function () {
|
||||
$user = User::factory()->create([
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
$this->actingAs($user);
|
||||
|
||||
$addSegmentEventId = \DB::table('events')->insertGetId([
|
||||
'name' => 'Add Segment',
|
||||
'key' => 'add_segment',
|
||||
'description' => 'Attach a segment to contract',
|
||||
'active' => 1,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$payload = [
|
||||
'name' => fake()->unique()->words(2, true),
|
||||
'color_tag' => null,
|
||||
'auto_mail' => false,
|
||||
'email_template_id' => null,
|
||||
'events' => [
|
||||
[
|
||||
'id' => $addSegmentEventId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => [
|
||||
// missing segment_id
|
||||
'deactivate_previous' => true,
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->post(route('settings.decisions.store'), $payload);
|
||||
|
||||
$response->assertSessionHasErrors(['events.0.config.segment_id']);
|
||||
});
|
||||
139
tests/Feature/Workflow/UpdateDecisionEventsTest.php
Normal file
139
tests/Feature/Workflow/UpdateDecisionEventsTest.php
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
<?php
|
||||
|
||||
use App\Models\Decision;
|
||||
use App\Models\Event;
|
||||
use App\Models\Segment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\WithFaker;
|
||||
|
||||
uses(WithFaker::class);
|
||||
|
||||
it('validates segment_id is required for add_segment event', function () {
|
||||
$user = User::factory()->create([
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
$this->actingAs($user);
|
||||
|
||||
$decision = Decision::factory()->create();
|
||||
|
||||
// Ensure event exists (legacy schema requires non-null options)
|
||||
$addSegmentId = \DB::table('events')->insertGetId([
|
||||
'name' => 'Add Segment',
|
||||
'key' => 'add_segment',
|
||||
'description' => 'Attach a segment to contract',
|
||||
'active' => 1,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$payload = [
|
||||
'name' => $decision->name,
|
||||
'color_tag' => $decision->color_tag,
|
||||
'auto_mail' => false,
|
||||
'email_template_id' => null,
|
||||
'events' => [
|
||||
[
|
||||
'id' => $addSegmentId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => [
|
||||
// 'segment_id' => missing on purpose
|
||||
'deactivate_previous' => true,
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->put(route('settings.decisions.update', ['id' => $decision->id]), $payload);
|
||||
|
||||
$response->assertSessionHasErrors(['events.0.config.segment_id']);
|
||||
});
|
||||
|
||||
it('validates archive_setting_id is required for archive_contract event', function () {
|
||||
$user = User::factory()->create([
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
$this->actingAs($user);
|
||||
|
||||
$decision = Decision::factory()->create();
|
||||
|
||||
$archiveEventId = \DB::table('events')->insertGetId([
|
||||
'name' => 'Archive Contract',
|
||||
'key' => 'archive_contract',
|
||||
'description' => 'Archive a contract by archive setting',
|
||||
'active' => 1,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$payload = [
|
||||
'name' => $decision->name,
|
||||
'color_tag' => $decision->color_tag,
|
||||
'auto_mail' => false,
|
||||
'email_template_id' => null,
|
||||
'events' => [
|
||||
[
|
||||
'id' => $archiveEventId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => [
|
||||
// 'archive_setting_id' => missing on purpose
|
||||
'reactivate' => false,
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->put(route('settings.decisions.update', ['id' => $decision->id]), $payload);
|
||||
|
||||
$response->assertSessionHasErrors(['events.0.config.archive_setting_id']);
|
||||
});
|
||||
|
||||
it('accepts valid add_segment config and updates without validation errors', function () {
|
||||
$user = User::factory()->create([
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
$this->actingAs($user);
|
||||
|
||||
$decision = Decision::factory()->create();
|
||||
|
||||
$addSegmentId = \DB::table('events')->insertGetId([
|
||||
'name' => 'Add Segment',
|
||||
'key' => 'add_segment',
|
||||
'description' => 'Attach a segment to contract',
|
||||
'active' => 1,
|
||||
'config' => json_encode([]),
|
||||
'options' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$segment = Segment::factory()->create();
|
||||
|
||||
$payload = [
|
||||
'name' => $decision->name,
|
||||
'color_tag' => $decision->color_tag,
|
||||
'auto_mail' => false,
|
||||
'email_template_id' => null,
|
||||
'events' => [
|
||||
[
|
||||
'id' => $addSegmentId,
|
||||
'active' => true,
|
||||
'run_order' => 1,
|
||||
'config' => [
|
||||
'segment_id' => $segment->id,
|
||||
'deactivate_previous' => true,
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->put(route('settings.decisions.update', ['id' => $decision->id]), $payload);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
$response->assertRedirect(route('settings.workflow'));
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user