Fixed some field job problem where field operator could still see archived contracts

This commit is contained in:
Simon Pocrnjič
2025-12-21 21:00:49 +01:00
parent 11206fb4f7
commit adc2a64687
10 changed files with 919 additions and 319 deletions
+108 -155
View File
@@ -252,11 +252,14 @@ public function storeActivity(ClientCase $clientCase, Request $request)
'action_id' => 'exists:\App\Models\Action,id',
'decision_id' => 'exists:\App\Models\Decision,id',
'contract_uuid' => 'nullable|uuid',
'phone_view' => 'nullable|boolean',
'send_auto_mail' => 'sometimes|boolean',
'attachment_document_ids' => 'sometimes|array',
'attachment_document_ids.*' => 'integer',
]);
$isPhoneView = $attributes['phone_view'] ?? false;
// Map contract_uuid to contract_id within the same client case, if provided
$contractId = null;
if (! empty($attributes['contract_uuid'])) {
@@ -279,10 +282,23 @@ public function storeActivity(ClientCase $clientCase, Request $request)
'decision_id' => $attributes['decision_id'],
'contract_id' => $contractId,
]);
/*foreach ($activity->decision->events as $e) {
$class = '\\App\\Events\\' . $e->name;
event(new $class($clientCase));
}*/
if ($isPhoneView && $contractId) {
$fieldJob = $contract->fieldJobs()
->whereNull('completed_at')
->whereNull('cancelled_at')
->where('assigned_user_id', \Auth::id())
->orderByDesc('id')
->first();
if ($fieldJob) {
$fieldJob->update([
'added_activity' => true,
'last_activity' => $row->created_at,
]);
}
}
logger()->info('Activity successfully inserted', $attributes);
@@ -297,8 +313,8 @@ public function storeActivity(ClientCase $clientCase, Request $request)
->values();
$validAttachmentIds = collect();
if ($attachmentIds->isNotEmpty() && $contractId) {
$validAttachmentIds = \App\Models\Document::query()
->where('documentable_type', \App\Models\Contract::class)
$validAttachmentIds = Document::query()
->where('documentable_type', Contract::class)
->where('documentable_id', $contractId)
->whereIn('id', $attachmentIds)
->pluck('id');
@@ -1458,178 +1474,115 @@ public function archiveContract(ClientCase $clientCase, string $uuid, Request $r
{
$contract = Contract::query()->where('uuid', $uuid)->firstOrFail();
if ($contract->client_case_id !== $clientCase->id) {
\Log::warning('Contract not found uuid: {uuid}', ['uuid' => $uuid]);
abort(404);
}
$reactivateRequested = (bool) $request->boolean('reactivate');
// Determine applicable settings based on intent (archive vs reactivate)
if ($reactivateRequested) {
$latestReactivate = \App\Models\ArchiveSetting::query()
->where('enabled', true)
->where('reactivate', true)
->whereIn('strategy', ['immediate', 'manual'])
->orderByDesc('id')
->first();
if (! $latestReactivate) {
return back()->with('warning', __('contracts.reactivate_not_allowed'));
}
$settings = collect([$latestReactivate]);
$hasReactivateRule = true;
} else {
$settings = \App\Models\ArchiveSetting::query()
->where('enabled', true)
->whereIn('strategy', ['immediate', 'manual'])
->where(function ($q) { // exclude reactivate-only rules from archive run
$q->whereNull('reactivate')->orWhere('reactivate', false);
})
->get();
if ($settings->isEmpty()) {
return back()->with('warning', __('contracts.no_archive_settings'));
}
$hasReactivateRule = false;
$attr = $request->validate([
'reactivate' => 'boolean',
]);
$reactivate = $attr['reactivate'] ?? false;
$setting = \App\Models\ArchiveSetting::query()
->where('enabled', true)
->whereIn('strategy', ['immediate', 'manual'])
->where('reactivate', $reactivate)
->orderByDesc('id')
->first();
if (! $setting->exists()) {
\Log::warning('No archive settings found!');
return back()->with('warning', 'No settings found');
}
// Service archive executor
$executor = app(\App\Services\Archiving\ArchiveExecutor::class);
$result = null;
$context = [
'contract_id' => $contract->id,
'client_case_id' => $clientCase->id,
'account_id' => $contract->account->id ?? null,
];
if ($contract->account) {
$context['account_id'] = $contract->account->id;
try {
$result = $executor->executeSetting($setting, $context, \Auth::id());
} catch (Exception $e) {
\Log::error('There was an error executing ArchiveExecutor::executeSetting {msg}', ['msg' => $e->getMessage()]);
return back()->with('warning', 'Something went wrong!');
}
$overall = [];
$hadAnyEffect = false;
foreach ($settings as $setting) {
$res = $executor->executeSetting($setting, $context, optional($request->user())->id);
foreach ($res as $table => $count) {
$overall[$table] = ($overall[$table] ?? 0) + $count;
if ($count > 0) {
$hadAnyEffect = true;
}
}
}
if ($reactivateRequested && $hasReactivateRule) {
// Reactivation path: ensure contract becomes active and soft-delete cleared.
if ($contract->active == 0 || $contract->deleted_at) {
$contract->forceFill(['active' => 1, 'deleted_at' => null])->save();
$overall['contracts_reactivated'] = ($overall['contracts_reactivated'] ?? 0) + 1;
$hadAnyEffect = true;
}
} else {
// Ensure the contract itself is archived even if rule conditions would have excluded it
if (! empty($contract->getAttributes()) && $contract->active) {
if (! array_key_exists('contracts', $overall)) {
$contract->update(['active' => 0]);
$overall['contracts'] = ($overall['contracts'] ?? 0) + 1;
} else {
$contract->refresh();
}
$hadAnyEffect = true;
}
}
// Create an Activity record logging this archive if an action or decision is tied to any setting
if ($hadAnyEffect) {
$activitySetting = $settings->first(fn ($s) => ! is_null($s->action_id) || ! is_null($s->decision_id));
if ($activitySetting) {
try {
if ($reactivateRequested) {
$note = 'Ponovna aktivacija pogodba '.$contract->reference;
} else {
$noteKey = 'contracts.archived_activity_note';
$note = __($noteKey, ['reference' => $contract->reference]);
if ($note === $noteKey) {
$note = \Illuminate\Support\Facades\Lang::get($noteKey, ['reference' => $contract->reference], 'sl');
}
}
try {
\DB::transaction(function () use ($contract, $clientCase, $setting, $reactivate) {
// Create an Activity record logging this archive if an action or decision is tied to any setting
if ($setting->action_id && $setting->decision_id) {
$activityData = [
'client_case_id' => $clientCase->id,
'action_id' => $activitySetting->action_id,
'decision_id' => $activitySetting->decision_id,
'note' => $note,
'active' => 1,
'user_id' => optional($request->user())->id,
'action_id' => $setting->action_id,
'decision_id' => $setting->decision_id,
'note' => ($reactivate)
? "Ponovno aktivirana pogodba $contract->reference"
: "Arhivirana pogodba $contract->reference",
];
if ($reactivateRequested) {
// Attach the contract_id when reactivated as per requirement
$activityData['contract_id'] = $contract->id;
try {
\App\Models\Activity::create($activityData);
} catch (Exception $e) {
\Log::warning('Activity could not be created!');
}
\App\Models\Activity::create($activityData);
} catch (\Throwable $e) {
logger()->warning('Failed to create archive/reactivate activity', [
'error' => $e->getMessage(),
'contract_id' => $contract->id,
'setting_id' => optional($activitySetting)->id,
'reactivate' => $reactivateRequested,
]);
}
}
}
// If any archive setting specifies a segment_id, move the contract to that segment (archive bucket)
$segmentSetting = $settings->first(fn ($s) => ! is_null($s->segment_id)); // for reactivation this is the single reactivation setting if segment specified
if ($segmentSetting && $segmentSetting->segment_id) {
try {
$segmentId = $segmentSetting->segment_id;
\DB::transaction(function () use ($contract, $segmentId, $clientCase) {
// 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,
// If any archive setting specifies a segment_id, move the contract to that segment (archive bucket)
if ($setting->segment_id) {
$segmentId = $setting->segment_id;
$contract->segments()
->allRelatedIds()
->map(fn (int $val, int|string $key) => $contract->segments()->updateExistingPivot($val, [
'active' => false,
'updated_at' => now(),
])
);
if ($contract->attachedSegments()->find($segmentId)->pluck('id')->isNotEmpty()) {
$contract->attachedSegments()->updateExistingPivot($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 archive 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(),
]);
$contract->segments()->attach(
$segmentId,
[
'active' => true,
'created_at' => now(),
'updated_at' => now(),
]
);
}
});
} catch (\Throwable $e) {
logger()->warning('Failed to move contract to archive segment', [
'error' => $e->getMessage(),
'contract_id' => $contract->id,
'segment_id' => $segmentSetting->segment_id,
'setting_id' => $segmentSetting->id,
]);
}
}
$contract->fieldJobs()
->whereNull('completed_at')
->whereNull('cancelled_at')
->update([
'cancelled_at' => date('Y-m-d'),
'updated_at' => now(),
]);
});
} catch (Exception $e) {
\Log::warning('Something went wrong with inserting / updating archive setting partials!');
return back()->with('warning', 'Something went wrong!');
}
$message = $reactivateRequested ? __('contracts.reactivated') : __('contracts.archived');
return back()->with('success', $message);
return back()->with('success', $reactivate
? __('contracts.reactivated')
: __('contracts.archived')
);
}
/**
+56 -144
View File
@@ -76,169 +76,81 @@ public function completedToday(Request $request)
public function showCase(\App\Models\ClientCase $clientCase, Request $request)
{
$userId = $request->user()->id;
$completedMode = (bool) $request->boolean('completed');
$completedMode = $request->boolean('completed');
// Eager load client case with person details
$case = \App\Models\ClientCase::query()
->with(['person' => fn ($q) => $q->with(['addresses', 'phones', 'emails', 'bankAccounts'])])
->findOrFail($clientCase->id);
// Eager load case with person details
$case = $clientCase->load('person.addresses', 'person.phones', 'person.emails', 'person.bankAccounts');
// Determine contracts of this case relevant to the current user
// - Normal mode: contracts assigned to me and still active (not completed/cancelled)
// - Completed mode (?completed=1): contracts where my field job was completed today
if ($completedMode) {
$start = now()->startOfDay();
$end = now()->endOfDay();
$contractIds = FieldJob::query()
->where('assigned_user_id', $userId)
->whereNull('cancelled_at')
->whereBetween('completed_at', [$start, $end])
->whereHas('contract', fn ($q) => $q->where('client_case_id', $case->id))
->pluck('contract_id')
->unique()
->values();
} else {
$contractIds = FieldJob::query()
->where('assigned_user_id', $userId)
->whereNull('completed_at')
->whereNull('cancelled_at')
->whereHas('contract', fn ($q) => $q->where('client_case_id', $case->id))
->pluck('contract_id')
->unique()
->values();
}
// Query contracts based on field jobs
$contractsQuery = FieldJob::query()
->where('assigned_user_id', $userId)
->whereHas('contract', fn ($q) => $q->where('client_case_id', $case->id))
->when($completedMode,
fn ($q) => $q->whereNull('cancelled_at')->whereBetween('completed_at', [now()->startOfDay(), now()->endOfDay()]),
fn ($q) => $q->whereNull('completed_at')->whereNull('cancelled_at')
);
// Get contracts with relationships
$contracts = \App\Models\Contract::query()
->where('client_case_id', $case->id)
->whereIn('id', $contractIds)
->with(['type:id,name', 'account'])
->whereIn('id', $contractsQuery->pluck('contract_id')->unique())
->with(['type:id,name', 'account', 'latestObject'])
->orderByDesc('created_at')
->get();
// Attach latest object (if any) to each contract as last_object for display
if ($contracts->isNotEmpty()) {
$byId = $contracts->keyBy('id');
$latestObjects = \App\Models\CaseObject::query()
->whereIn('contract_id', $byId->keys())
->whereNull('deleted_at')
->select('id', 'reference', 'name', 'description', 'type', 'contract_id', 'created_at')
->orderByDesc('created_at')
->get()
->groupBy('contract_id')
->map(function ($group) {
return $group->first();
});
foreach ($latestObjects as $cid => $obj) {
if (isset($byId[$cid])) {
$byId[$cid]->setAttribute('last_object', $obj);
}
}
}
// Build merged documents: case documents + documents of assigned contracts
$contractRefMap = [];
foreach ($contracts as $c) {
$contractRefMap[$c->id] = $c->reference;
}
$contractDocs = \App\Models\Document::query()
->where('documentable_type', \App\Models\Contract::class)
->whereIn('documentable_id', $contractIds)
// Build merged documents
$documents = $case->documents()
->orderByDesc('created_at')
->get()
->map(function ($d) use ($contractRefMap) {
$arr = $d->toArray();
$arr['contract_reference'] = $contractRefMap[$d->documentable_id] ?? null;
$arr['documentable_type'] = \App\Models\Contract::class;
$arr['contract_uuid'] = optional(\App\Models\Contract::withTrashed()->find($d->documentable_id))->uuid;
return $arr;
});
$caseDocs = $case->documents()->orderByDesc('created_at')->get()->map(function ($d) use ($case) {
$arr = $d->toArray();
$arr['documentable_type'] = \App\Models\ClientCase::class;
$arr['client_case_uuid'] = $case->uuid;
return $arr;
});
$documents = $caseDocs->concat($contractDocs)->sortByDesc('created_at')->values();
// Provide minimal types for PersonInfoGrid
$types = [
'address_types' => \App\Models\Person\AddressType::all(),
'phone_types' => \App\Models\Person\PhoneType::all(),
];
// Case activities (compact for phone): latest 20 with relations
$activities = $case->activities()
->with(['action', 'decision', 'contract:id,uuid,reference', 'user:id,name'])
->orderByDesc('created_at')
->limit(20)
->get()
->map(function ($a) {
$a->setAttribute('user_name', optional($a->user)->name);
return $a;
});
// Determine segment filters from FieldJobSettings for this case/user context
$settingIds = FieldJob::query()
->where('assigned_user_id', $userId)
->whereHas('contract', fn ($q) => $q->where('client_case_id', $case->id))
->when(
$completedMode,
function ($q) {
$q->whereNull('cancelled_at')
->whereBetween('completed_at', [now()->startOfDay(), now()->endOfDay()]);
},
function ($q) {
$q->whereNull('completed_at')->whereNull('cancelled_at');
}
->map(fn ($d) => array_merge($d->toArray(), [
'documentable_type' => \App\Models\ClientCase::class,
'client_case_uuid' => $case->uuid,
]))
->concat(
\App\Models\Document::query()
->where('documentable_type', \App\Models\Contract::class)
->whereIn('documentable_id', $contracts->pluck('id'))
->with('documentable:id,uuid,reference')
->orderByDesc('created_at')
->get()
->map(fn ($d) => array_merge($d->toArray(), [
'contract_reference' => $d->documentable?->reference,
'contract_uuid' => $d->documentable?->uuid,
]))
)
->pluck('field_job_setting_id')
->filter()
->unique()
->sortByDesc('created_at')
->values();
$segmentIds = collect();
if ($settingIds->isNotEmpty()) {
$segmentIds = \App\Models\FieldJobSetting::query()
->whereIn('id', $settingIds)
->pluck('segment_id')
->filter()
->unique()
->values();
}
// Filter actions and their decisions by the derived segment ids (decisions.segment_id)
$actions = \App\Models\Action::query()
->when($segmentIds->isNotEmpty(), function ($q) use ($segmentIds) {
// Filter actions by their segment_id matching the FieldJobSetting segment(s)
$q->whereIn('segment_id', $segmentIds);
})
->with([
'decisions' => function ($q) {
$q->select('decisions.id', 'decisions.name', 'decisions.color_tag', 'decisions.auto_mail', 'decisions.email_template_id');
},
'decisions.emailTemplate' => function ($q) {
$q->select('id', 'name', 'entity_types', 'allow_attachments');
},
])
->get(['id', 'name', 'color_tag', 'segment_id']);
// Get segment IDs for filtering actions
$segmentIds = \App\Models\FieldJobSetting::query()
->whereIn('id', $contractsQuery->pluck('field_job_setting_id')->filter()->unique())
->pluck('segment_id')
->filter()
->unique();
return Inertia::render('Phone/Case/Index', [
'client' => $case->client()->with('person', fn ($q) => $q->with(['addresses', 'phones', 'emails', 'bankAccounts']))->firstOrFail(),
'client' => $case->client->load('person.addresses', 'person.phones', 'person.emails', 'person.bankAccounts'),
'client_case' => $case,
'contracts' => $contracts,
'documents' => $documents,
'types' => $types,
'types' => [
'address_types' => \App\Models\Person\AddressType::all(),
'phone_types' => \App\Models\Person\PhoneType::all(),
],
'account_types' => \App\Models\AccountType::all(),
// Provide decisions (filtered by segment) with linked email template metadata (entity_types, allow_attachments)
'actions' => $actions,
'activities' => $activities,
'actions' => \App\Models\Action::query()
->when($segmentIds->isNotEmpty(), fn ($q) => $q->whereIn('segment_id', $segmentIds))
->with([
'decisions:id,name,color_tag,auto_mail,email_template_id',
'decisions.emailTemplate:id,name,entity_types,allow_attachments',
])
->get(['id', 'name', 'color_tag', 'segment_id']),
'activities' => $case->activities()
->with(['action', 'decision', 'contract:id,uuid,reference', 'user:id,name'])
->orderByDesc('created_at')
->limit(20)
->get()
->map(fn ($a) => $a->setAttribute('user_name', $a->user?->name)),
'completed_mode' => $completedMode,
]);
}