Big changes added events for decisions

This commit is contained in:
Simon Pocrnjič
2025-10-22 23:20:04 +02:00
parent 872b76b012
commit 67ebe4b225
36 changed files with 2240 additions and 189 deletions
+84
View File
@@ -489,6 +489,90 @@ public function getEvents(Import $import)
return response()->json(['events' => $events]);
}
// List unresolved keyref contract rows (based on events containing keyref-not-found)
public function missingKeyrefRows(Import $import)
{
// Identify row IDs from events. Prefer specific event key, fallback to message pattern
$rowIds = \App\Models\ImportEvent::query()
->where('import_id', $import->id)
->where(function ($q) {
$q->where('event', 'contract_keyref_not_found')
->orWhereRaw('LOWER(message) LIKE ?', ['%keyref%not found%']);
})
->whereNotNull('import_row_id')
->pluck('import_row_id')
->filter()
->unique()
->values();
if ($rowIds->isEmpty()) {
return response()->json([
'columns' => (array) ($import->meta['columns'] ?? []),
'rows' => [],
]);
}
$rows = \App\Models\ImportRow::query()
->where('import_id', $import->id)
->whereIn('id', $rowIds)
->orderBy('row_number')
->get(['id', 'row_number', 'raw_data']);
$columns = (array) ($import->meta['columns'] ?? []);
// If no stored header, derive from first row raw_data keys
if (empty($columns)) {
$first = $rows->first();
if ($first && is_array($first->raw_data)) {
$columns = array_keys($first->raw_data);
}
}
// Normalize each row to ordered array by $columns
$dataRows = [];
foreach ($rows as $r) {
$line = [];
foreach ($columns as $col) {
$line[] = (string) ($r->raw_data[$col] ?? '');
}
$dataRows[] = [
'id' => $r->id,
'row_number' => $r->row_number,
'values' => $line,
];
}
return response()->json([
'columns' => $columns,
'rows' => $dataRows,
]);
}
// Export unresolved keyref rows as CSV (includes header if available)
public function exportMissingKeyrefCsv(Import $import)
{
$json = $this->missingKeyrefRows($import)->getData(true);
$columns = $json['columns'] ?? [];
$rows = $json['rows'] ?? [];
$fh = fopen('php://temp', 'r+');
if (! empty($columns)) {
fputcsv($fh, $columns);
}
foreach ($rows as $r) {
fputcsv($fh, $r['values'] ?? []);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
$filename = 'missing-keyref-rows-'.$import->id.'.csv';
return response($csv, 200, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
}
// Preview (up to N) raw CSV rows for an import for mapping review
public function preview(Import $import, Request $request)
{
+33 -3
View File
@@ -48,6 +48,7 @@ public function show(\App\Models\Segment $segment)
{
// Retrieve contracts that are active in this segment, eager-loading required relations
$search = request('search');
$clientFilter = request('client') ?? request('client_id'); // support either ?client=<uuid|id> or ?client_id=<id>
$contractsQuery = \App\Models\Contract::query()
->whereHas('segments', function ($q) use ($segment) {
$q->where('segments.id', $segment->id)
@@ -61,7 +62,18 @@ public function show(\App\Models\Segment $segment)
])
->latest('id');
if (!empty($search)) {
// Optional filter by client (accepts numeric id or client uuid)
if (! empty($clientFilter)) {
$contractsQuery->whereHas('clientCase.client', function ($q) use ($clientFilter) {
if (is_numeric($clientFilter)) {
$q->where('clients.id', (int) $clientFilter);
} else {
$q->where('clients.uuid', $clientFilter);
}
});
}
if (! empty($search)) {
$contractsQuery->where(function ($qq) use ($search) {
$qq->where('contracts.reference', 'ilike', '%'.$search.'%')
->orWhereHas('clientCase.person', function ($p) use ($search) {
@@ -88,9 +100,27 @@ public function show(\App\Models\Segment $segment)
$contracts->setCollection($items);
}
// Build a full client list for this segment (not limited to current page) for the dropdown
$clients = \App\Models\Client::query()
->whereHas('clientCases.contracts.segments', function ($q) use ($segment) {
$q->where('segments.id', $segment->id)
->where('contract_segment.active', '=', 1);
})
->with(['person:id,full_name'])
->get(['uuid', 'person_id'])
->map(function ($c) {
return [
'uuid' => (string) $c->uuid,
'name' => (string) optional($c->person)->full_name,
];
})
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
->values();
return Inertia::render('Segments/Show', [
'segment' => $segment->only(['id','name','description']),
'segment' => $segment->only(['id', 'name', 'description']),
'contracts' => $contracts,
'clients' => $clients,
]);
}
@@ -120,7 +150,7 @@ public function update(UpdateSegmentRequest $request, Segment $segment)
'name' => $data['name'],
'description' => $data['description'] ?? null,
'active' => $data['active'] ?? $segment->active,
'exclude' => $data['exclude'] ?? $segment->exclude
'exclude' => $data['exclude'] ?? $segment->exclude,
]);
return to_route('settings.segments')->with('success', 'Segment updated');
+130 -3
View File
@@ -3,10 +3,12 @@
namespace App\Http\Controllers;
use App\Models\Action;
use App\Models\ArchiveSetting;
use App\Models\Decision;
use App\Models\EmailTemplate;
use App\Models\Segment;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
class WorkflowController extends Controller
@@ -15,9 +17,11 @@ public function index(Request $request)
{
return Inertia::render('Settings/Workflow/Index', [
'actions' => Action::query()->with(['decisions', 'segment'])->withCount('activities')->orderBy('id')->get(),
'decisions' => Decision::query()->with('actions')->withCount('activities')->orderBy('id')->get(),
'decisions' => Decision::query()->with(['actions', 'events'])->withCount('activities')->orderBy('id')->get(),
'segments' => Segment::query()->get(),
'email_templates' => EmailTemplate::query()->where('active', true)->get(['id', 'name', 'entity_types']),
'events' => \App\Models\Event::query()->orderBy('name')->get(['id', 'name', 'key', 'description', 'active']),
'archive_settings' => ArchiveSetting::query()->where('enabled', true)->orderBy('id')->get(['id', 'name']),
]);
}
@@ -87,11 +91,43 @@ public function storeDecision(Request $request)
'actions' => 'nullable|array',
'actions.*.id' => 'required_with:actions.*|integer|exists:actions,id',
'actions.*.name' => 'required_with:actions.*|string|max:50',
'events' => 'nullable|array',
'events.*.id' => 'required_with:events.*|integer|exists:events,id',
'events.*.active' => 'sometimes|boolean',
'events.*.run_order' => 'nullable|integer',
'events.*.config' => 'nullable|array',
]);
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
$eventsPayload = collect($attributes['events'] ?? []);
\DB::transaction(function () use ($attributes, $actionIds) {
// Extra server-side validation for event-specific config keys
$validationErrors = [];
foreach ($eventsPayload as $i => $ev) {
$idEv = isset($ev['id']) ? (int) $ev['id'] : null;
if (! $idEv) {
continue;
}
$eventModel = \App\Models\Event::find($idEv);
$key = $eventModel?->key ?? ($ev['key'] ?? null);
if ($key === 'add_segment') {
$seg = $ev['config']['segment_id'] ?? null;
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
}
} elseif ($key === 'archive_contract') {
$as = $ev['config']['archive_setting_id'] ?? null;
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
}
}
}
if (! empty($validationErrors)) {
throw ValidationException::withMessages($validationErrors);
}
\DB::transaction(function () use ($attributes, $actionIds, $eventsPayload) {
/** @var \App\Models\Decision $row */
$row = Decision::create([
'name' => $attributes['name'],
@@ -103,6 +139,32 @@ public function storeDecision(Request $request)
if (! empty($actionIds)) {
$row->actions()->sync($actionIds);
}
// Attach decision events with pivot attributes
if ($eventsPayload->isNotEmpty()) {
$sync = [];
foreach ($eventsPayload as $ev) {
$id = (int) ($ev['id'] ?? 0);
if ($id <= 0) {
continue;
}
$cfg = $ev['config'] ?? null;
if (is_array($cfg)) {
$cfg = json_encode($cfg);
} elseif (is_string($cfg)) {
$trim = trim($cfg);
$cfg = $trim === '' ? null : $cfg;
} else {
$cfg = null;
}
$sync[$id] = [
'active' => (bool) ($ev['active'] ?? true),
'run_order' => isset($ev['run_order']) ? (int) $ev['run_order'] : null,
'config' => $cfg,
];
}
$row->events()->sync($sync);
}
});
return to_route('settings.workflow')->with('success', 'Decision created successfully!');
@@ -120,11 +182,43 @@ public function updateDecision(int $id, Request $request)
'actions' => 'nullable|array',
'actions.*.id' => 'required_with:actions.*|integer|exists:actions,id',
'actions.*.name' => 'required_with:actions.*|string|max:50',
'events' => 'nullable|array',
'events.*.id' => 'required_with:events.*|integer|exists:events,id',
'events.*.active' => 'sometimes|boolean',
'events.*.run_order' => 'nullable|integer',
'events.*.config' => 'nullable|array',
]);
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
$eventsPayload = collect($attributes['events'] ?? []);
\DB::transaction(function () use ($attributes, $actionIds, $row) {
// Extra server-side validation for event-specific config keys
$validationErrors = [];
foreach ($eventsPayload as $i => $ev) {
$idEv = isset($ev['id']) ? (int) $ev['id'] : null;
if (! $idEv) {
continue;
}
$eventModel = \App\Models\Event::find($idEv);
$key = $eventModel?->key ?? ($ev['key'] ?? null);
if ($key === 'add_segment') {
$seg = $ev['config']['segment_id'] ?? null;
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
}
} elseif ($key === 'archive_contract') {
$as = $ev['config']['archive_setting_id'] ?? null;
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
}
}
}
if (! empty($validationErrors)) {
throw ValidationException::withMessages($validationErrors);
}
\DB::transaction(function () use ($attributes, $actionIds, $eventsPayload, $row) {
$row->update([
'name' => $attributes['name'],
'color_tag' => $attributes['color_tag'] ?? null,
@@ -132,6 +226,39 @@ public function updateDecision(int $id, Request $request)
'email_template_id' => $attributes['email_template_id'] ?? null,
]);
$row->actions()->sync($actionIds);
// Sync decision events with pivot attributes
if ($eventsPayload->isNotEmpty()) {
$sync = [];
foreach ($eventsPayload as $ev) {
$id = (int) ($ev['id'] ?? 0);
if ($id <= 0) {
continue;
}
$cfg = $ev['config'] ?? null;
// ensure string JSON stored; accept already-JSON strings
if (is_array($cfg)) {
$cfg = json_encode($cfg);
} elseif (is_string($cfg)) {
$trim = trim($cfg);
// If not valid JSON, keep raw string (handler side can parse/ignore)
$cfg = $trim === '' ? null : $cfg;
} else {
$cfg = null;
}
$sync[$id] = [
'active' => (bool) ($ev['active'] ?? true),
'run_order' => isset($ev['run_order']) ? (int) $ev['run_order'] : null,
'config' => $cfg,
];
}
$row->events()->sync($sync);
} else {
// If empty provided explicitly, detach all to reflect UI intent
if (array_key_exists('events', $attributes)) {
$row->events()->detach();
}
}
});
return to_route('settings.workflow')->with('success', 'Decision updated successfully!');