Fixes to client case show

This commit is contained in:
Simon Pocrnjič 2025-10-07 19:47:54 +02:00
parent f976b4d6ef
commit 175111bed4
8 changed files with 369 additions and 237 deletions

View File

@ -198,8 +198,10 @@ public function updateContract(ClientCase $clientCase, string $uuid, UpdateContr
// After update/create, if balance_amount changed (and not through a payment), log an activity with before/after
if (array_key_exists('balance_amount', $accountData)) {
$newBalance = (float) optional($contract->account)->fresh()->balance_amount;
if ($newBalance !== $oldBalance) {
// Guard against null account (e.g., if creation failed silently earlier)
$newAccount = $contract->account; // single relationship access
$newBalance = $newAccount ? (float) optional($newAccount->fresh())->balance_amount : $oldBalance;
if ($newAccount && $newBalance !== $oldBalance) {
try {
$currency = optional(\App\Models\PaymentSetting::query()->first())->default_currency ?? 'EUR';
$beforeStr = number_format($oldBalance, 2, ',', '.').' '.$currency;
@ -244,12 +246,9 @@ public function storeActivity(ClientCase $clientCase, Request $request)
// Map contract_uuid to contract_id within the same client case, if provided
$contractId = null;
if (! empty($attributes['contract_uuid'])) {
$contract = $clientCase->contracts()->where('uuid', $attributes['contract_uuid'])->firstOrFail('id');
$contract = $clientCase->contracts()->where('uuid', $attributes['contract_uuid'])->firstOrFail(['id']);
if ($contract) {
// Prevent attaching a new activity specifically to an archived contract
if (! $contract->active) {
return back()->with('warning', __('contracts.activity_not_allowed_archived'));
}
// Archived contracts are now allowed: link activity regardless of active flag
$contractId = $contract->id;
}
}
@ -1049,7 +1048,22 @@ public function show(ClientCase $clientCase)
// Prepare contracts and a reference map.
// Only apply active/inactive filtering IF a segment filter is provided.
$contractsQuery = $case->contracts()
->with(['type', 'account', 'objects', 'segments:id,name']);
// Only select lean columns to avoid oversize JSON / headers
->select(['id', 'uuid', 'reference', 'start_date', 'end_date', 'active', 'type_id', 'client_case_id', 'created_at'])
->with([
'type:id,name',
// Use closure for account to avoid ambiguous column names with latestOfMany join
'account' => function ($q) {
$q->select([
'accounts.id',
'accounts.contract_id',
'accounts.type_id',
'accounts.initial_amount',
'accounts.balance_amount',
]);
},
'segments:id,name',
]);
$contractsQuery->orderByDesc('created_at');
@ -1070,7 +1084,10 @@ public function show(ClientCase $clientCase)
});
}
$contracts = $contractsQuery->get();
// NOTE: If a case has an extremely large number of contracts this can still be heavy.
// Consider pagination or deferred (Inertia lazy) loading. For now, hard-cap to 500 to prevent
// pathological memory / header growth. Frontend can request more via future endpoint.
$contracts = $contractsQuery->limit(500)->get();
$contractRefMap = [];
foreach ($contracts as $c) {
@ -1080,22 +1097,27 @@ public function show(ClientCase $clientCase)
// Merge client case and contract documents into a single array and include contract reference when applicable
$contractIds = $contracts->pluck('id');
$contractDocs = Document::query()
->select(['id', 'documentable_id', 'documentable_type', 'name', 'file_name', 'original_name', 'extension', 'mime_type', 'size', 'created_at'])
->where('documentable_type', Contract::class)
->when($contractIds->isNotEmpty(), fn ($q) => $q->whereIn('documentable_id', $contractIds))
->orderByDesc('created_at')
->limit(300) // cap to prevent excessive payload; add pagination later if needed
->get()
->map(function ($d) use ($contractRefMap) {
$arr = method_exists($d, 'toArray') ? $d->toArray() : (array) $d;
$arr['contract_reference'] = $contractRefMap[$d->documentable_id] ?? null;
$arr['documentable_type'] = Contract::class;
$arr['contract_uuid'] = optional(Contract::withTrashed()->find($d->documentable_id))->uuid;
return $arr;
});
$caseDocs = $case->documents()->orderByDesc('created_at')->get()->map(function ($d) use ($case) {
$caseDocs = $case->documents()
->select(['id', 'documentable_id', 'documentable_type', 'name', 'file_name', 'original_name', 'extension', 'mime_type', 'size', 'created_at'])
->orderByDesc('created_at')
->limit(200)
->get()
->map(function ($d) use ($case) {
$arr = method_exists($d, 'toArray') ? $d->toArray() : (array) $d;
$arr['documentable_type'] = ClientCase::class;
$arr['client_case_uuid'] = $case->uuid;
return $arr;

11
package-lock.json generated
View File

@ -4,7 +4,6 @@
"requires": true,
"packages": {
"": {
"name": "Teren-app",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.6.0",
"@fortawesome/free-brands-svg-icons": "^6.6.0",
@ -24,6 +23,7 @@
"reka-ui": "^2.5.1",
"tailwindcss-inner-border": "^0.2.0",
"v-calendar": "^3.1.2",
"vue-currency-input": "^3.2.1",
"vue-multiselect": "^3.1.0",
"vue-search-input": "^1.1.16",
"vue3-apexcharts": "^1.7.0",
@ -3931,6 +3931,15 @@
}
}
},
"node_modules/vue-currency-input": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/vue-currency-input/-/vue-currency-input-3.2.1.tgz",
"integrity": "sha512-Osfxzdu5cdZSCS4Cm0vuk7LwNeSdHWGIWK8gtDBC1kU0UtAKz7iU/8dyJ0KDJKxbAYiKeovoQTRfYxCH82I0EA==",
"license": "MIT",
"peerDependencies": {
"vue": "^2.7 || ^3.0.0"
}
},
"node_modules/vue-multiselect": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/vue-multiselect/-/vue-multiselect-3.3.1.tgz",

View File

@ -41,6 +41,7 @@
"vue-multiselect": "^3.1.0",
"vue-search-input": "^1.1.16",
"vue3-apexcharts": "^1.7.0",
"vuedraggable": "^4.1.0"
"vuedraggable": "^4.1.0",
"vue-currency-input": "^3.2.1"
}
}

View File

@ -0,0 +1,71 @@
<script setup>
import { watch, onMounted } from 'vue'
import { useCurrencyInput } from 'vue-currency-input'
const props = defineProps({
modelValue: { type: [Number, String, null], default: null },
id: String,
name: String,
placeholder: { type: String, default: '0,00' },
disabled: Boolean,
required: Boolean,
currency: { type: String, default: 'EUR' },
locale: { type: String, default: 'sl-SI' },
precision: { type: [Number, Object], default: 2 },
allowNegative: { type: Boolean, default: false },
useGrouping: { type: Boolean, default: true },
})
const emit = defineEmits(['update:modelValue'])
const { inputRef, numberValue, setValue, setOptions } = useCurrencyInput({
currency: props.currency,
locale: props.locale,
precision: props.precision,
useGrouping: props.useGrouping,
valueRange: props.allowNegative ? {} : { min: 0 },
})
watch(() => props.modelValue, (val) => {
const numeric = typeof val === 'string' ? parseFloat(val) : val
if (numeric !== numberValue.value) {
setValue(isNaN(numeric) ? null : numeric)
}
}, { immediate: true })
watch(numberValue, (val) => {
emit('update:modelValue', val)
})
watch(() => [props.currency, props.locale, props.precision, props.useGrouping, props.allowNegative], () => {
setOptions({
currency: props.currency,
locale: props.locale,
precision: props.precision,
useGrouping: props.useGrouping,
valueRange: props.allowNegative ? {} : { min: 0 },
})
})
onMounted(() => {
if (props.modelValue != null) {
const numeric = typeof props.modelValue === 'string' ? parseFloat(props.modelValue) : props.modelValue
setValue(isNaN(numeric) ? null : numeric)
}
})
</script>
<template>
<input
ref="inputRef"
:id="id"
:name="name"
type="text"
inputmode="decimal"
:placeholder="placeholder"
:disabled="disabled"
:required="required"
class="mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-800 dark:border-gray-600"
autocomplete="off"
/>
</template>

View File

@ -1,16 +1,19 @@
<script setup>
import { onMounted, ref } from 'vue';
import { onMounted, ref } from "vue";
defineProps({
modelValue: String,
modelValue: {
type: [String, Number],
default: "",
},
});
defineEmits(['update:modelValue']);
defineEmits(["update:modelValue"]);
const input = ref(null);
onMounted(() => {
if (input.value.hasAttribute('autofocus')) {
if (input.value.hasAttribute("autofocus")) {
input.value.focus();
}
});
@ -24,5 +27,5 @@ defineExpose({ focus: () => input.value.focus() });
class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
>
/>
</template>

View File

@ -5,6 +5,7 @@ import DialogModal from "@/Components/DialogModal.vue";
import InputLabel from "@/Components/InputLabel.vue";
import DatePickerField from "@/Components/DatePickerField.vue";
import TextInput from "@/Components/TextInput.vue";
import CurrencyInput from "@/Components/CurrencyInput.vue";
import { useForm } from "@inertiajs/vue3";
import { FwbTextarea } from "flowbite-vue";
import { ref, watch } from "vue";
@ -170,13 +171,12 @@ watch(
/>
<div class="col-span-6 sm:col-span-4">
<InputLabel for="activityAmount" value="Znesek" />
<TextInput
<CurrencyInput
id="activityAmount"
ref="activityAmountinput"
v-model="form.amount"
type="number"
class="mt-1 block w-full"
autocomplete="0.00"
:precision="{ min: 0, max: 4 }"
placeholder="0,00"
/>
</div>
<div class="flex justify-end mt-4">

View File

@ -1,14 +1,15 @@
<script setup>
import ActionMessage from '@/Components/ActionMessage.vue';
import DialogModal from '@/Components/DialogModal.vue';
import InputLabel from '@/Components/InputLabel.vue';
import InputError from '@/Components/InputError.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import SectionTitle from '@/Components/SectionTitle.vue';
import TextInput from '@/Components/TextInput.vue';
import DatePickerField from '@/Components/DatePickerField.vue';
import { useForm } from '@inertiajs/vue3';
import { watch, nextTick, ref as vRef } from 'vue';
import ActionMessage from "@/Components/ActionMessage.vue";
import DialogModal from "@/Components/DialogModal.vue";
import InputLabel from "@/Components/InputLabel.vue";
import InputError from "@/Components/InputError.vue";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import SectionTitle from "@/Components/SectionTitle.vue";
import TextInput from "@/Components/TextInput.vue";
import CurrencyInput from "@/Components/CurrencyInput.vue";
import DatePickerField from "@/Components/DatePickerField.vue";
import { useForm } from "@inertiajs/vue3";
import { watch, nextTick, ref as vRef } from "vue";
const props = defineProps({
client_case: Object,
@ -21,23 +22,23 @@ const props = defineProps({
console.log(props.types);
const emit = defineEmits(['close']);
const emit = defineEmits(["close"]);
const close = () => {
// Clear any previous validation warnings when closing
formContract.clearErrors()
formContract.recentlySuccessful = false
emit('close')
}
formContract.clearErrors();
formContract.recentlySuccessful = false;
emit("close");
};
// form state for create or edit
const formContract = useForm({
client_case_uuid: props.client_case.uuid,
uuid: props.contract?.uuid ?? null,
reference: props.contract?.reference ?? '',
reference: props.contract?.reference ?? "",
start_date: props.contract?.start_date ?? new Date().toISOString(),
type_id: (props.contract?.type_id ?? props.contract?.type?.id) ?? props.types[0].id,
description: props.contract?.description ?? '',
type_id: props.contract?.type_id ?? props.contract?.type?.id ?? props.types[0].id,
description: props.contract?.description ?? "",
// nested account fields, if exists
initial_amount: props.contract?.account?.initial_amount ?? null,
balance_amount: props.contract?.account?.balance_amount ?? null,
@ -46,98 +47,123 @@ const formContract = useForm({
// keep form in sync when switching between create and edit
const applyContract = (c) => {
formContract.uuid = c?.uuid ?? null
formContract.reference = c?.reference ?? ''
formContract.start_date = c?.start_date ?? new Date().toISOString()
formContract.type_id = (c?.type_id ?? c?.type?.id) ?? props.types[0].id
formContract.description = c?.description ?? ''
formContract.initial_amount = c?.account?.initial_amount ?? null
formContract.balance_amount = c?.account?.balance_amount ?? null
formContract.account_type_id = c?.account?.type_id ?? null
}
formContract.uuid = c?.uuid ?? null;
formContract.reference = c?.reference ?? "";
formContract.start_date = c?.start_date ?? new Date().toISOString();
formContract.type_id = c?.type_id ?? c?.type?.id ?? props.types[0].id;
formContract.description = c?.description ?? "";
formContract.initial_amount = c?.account?.initial_amount ?? null;
formContract.balance_amount = c?.account?.balance_amount ?? null;
formContract.account_type_id = c?.account?.type_id ?? null;
};
watch(() => props.contract, (c) => {
applyContract(c)
})
watch(
() => props.contract,
(c) => {
applyContract(c);
}
);
watch(() => props.show, (open) => {
watch(
() => props.show,
(open) => {
if (open && !props.contract) {
// reset for create
applyContract(null)
applyContract(null);
}
if (!open) {
// Ensure warnings are cleared when dialog hides
formContract.clearErrors()
formContract.recentlySuccessful = false
formContract.clearErrors();
formContract.recentlySuccessful = false;
}
})
}
);
// optional: focus the reference input when a reference validation error appears
const contractRefInput = vRef(null)
watch(() => formContract.errors.reference, async (err) => {
const contractRefInput = vRef(null);
watch(
() => formContract.errors.reference,
async (err) => {
if (err && props.show) {
await nextTick()
try { contractRefInput.value?.focus?.() } catch (e) {}
await nextTick();
try {
contractRefInput.value?.focus?.();
} catch (e) {}
}
})
}
);
const storeOrUpdate = () => {
const isEdit = !!formContract.uuid
const isEdit = !!formContract.uuid;
const options = {
onBefore: () => {
formContract.start_date = formContract.start_date
formContract.start_date = formContract.start_date;
},
onSuccess: () => {
close()
close();
// keep state clean; reset to initial
if (!isEdit) formContract.reset()
if (!isEdit) formContract.reset();
},
preserveScroll: true,
}
const params = {}
};
const params = {};
try {
const url = new URL(window.location.href)
const seg = url.searchParams.get('segment')
if (seg) params.segment = seg
const url = new URL(window.location.href);
const seg = url.searchParams.get("segment");
if (seg) params.segment = seg;
} catch (e) {}
if (isEdit) {
formContract.put(route('clientCase.contract.update', { client_case: props.client_case.uuid, uuid: formContract.uuid, ...params }), options)
formContract.put(
route("clientCase.contract.update", {
client_case: props.client_case.uuid,
uuid: formContract.uuid,
...params,
}),
options
);
} else {
// route helper merges params for GET; for POST we can append query manually if needed
let postUrl = route('clientCase.contract.store', props.client_case)
let postUrl = route("clientCase.contract.store", props.client_case);
if (params.segment) {
postUrl += (postUrl.includes('?') ? '&' : '?') + 'segment=' + encodeURIComponent(params.segment)
postUrl +=
(postUrl.includes("?") ? "&" : "?") +
"segment=" +
encodeURIComponent(params.segment);
}
formContract.post(postUrl, options)
formContract.post(postUrl, options);
}
}
};
</script>
<template>
<DialogModal
:show="show"
@close="close"
>
<template #title>{{ formContract.uuid ? 'Uredi pogodbo' : 'Dodaj pogodbo' }}</template>
<DialogModal :show="show" @close="close">
<template #title>{{
formContract.uuid ? "Uredi pogodbo" : "Dodaj pogodbo"
}}</template>
<template #content>
<form @submit.prevent="storeOrUpdate">
<div v-if="formContract.errors.reference" class="mb-4 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
<div
v-if="formContract.errors.reference"
class="mb-4 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"
>
{{ formContract.errors.reference }}
</div>
<SectionTitle class="mt-4 border-b mb-4">
<template #title>
Pogodba
</template>
<template #title> Pogodba </template>
</SectionTitle>
<div class="col-span-6 sm:col-span-4">
<InputLabel for="contractRef" value="Referenca"/>
<InputLabel for="contractRef" value="Referenca" />
<TextInput
id="contractRef"
ref="contractRefInput"
v-model="formContract.reference"
type="text"
:class="['mt-1 block w-full', formContract.errors.reference ? 'border-red-500 focus:border-red-500 focus:ring-red-500' : '']"
:class="[
'mt-1 block w-full',
formContract.errors.reference
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
: '',
]"
autocomplete="contract-reference"
/>
<InputError :message="formContract.errors.reference" />
@ -150,7 +176,7 @@ const storeOrUpdate = () => {
:enable-time-picker="false"
/>
<div class="col-span-6 sm:col-span-4">
<InputLabel for="contractTypeSelect" value="Tip"/>
<InputLabel for="contractTypeSelect" value="Tip" />
<select
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
id="contractTypeSelect"
@ -161,7 +187,7 @@ const storeOrUpdate = () => {
</select>
</div>
<div class="col-span-6 sm:col-span-4 mt-4">
<InputLabel for="contractDescription" value="Opis"/>
<InputLabel for="contractDescription" value="Opis" />
<textarea
id="contractDescription"
v-model="formContract.description"
@ -170,44 +196,30 @@ const storeOrUpdate = () => {
/>
</div>
<SectionTitle class="mt-6 border-b mb-4">
<template #title>
Račun
</template>
<template #title> Račun </template>
</SectionTitle>
<div class="col-span-6 sm:col-span-4">
<InputLabel for="accountTypeSelect" value="Tip računa"/>
<InputLabel for="accountTypeSelect" value="Tip računa" />
<select
id="accountTypeSelect"
v-model="formContract.account_type_id"
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
>
<option :value="null"></option>
<option v-for="at in account_types" :key="at.id" :value="at.id">{{ at.name ?? ('#' + at.id) }}</option>
<option v-for="at in account_types" :key="at.id" :value="at.id">
{{ at.name ?? "#" + at.id }}
</option>
</select>
<InputError :message="formContract.errors.account_type_id" />
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<InputLabel for="initialAmount" value="Predani znesek"/>
<TextInput
id="initialAmount"
v-model.number="formContract.initial_amount"
type="number"
step="0.01"
class="mt-1 block w-full"
autocomplete="off"
/>
<InputLabel for="initialAmount" value="Predani znesek" />
<CurrencyInput id="initialAmount" v-model="formContract.initial_amount" />
</div>
<div>
<InputLabel for="balanceAmount" value="Odprti znesek"/>
<TextInput
id="balanceAmount"
v-model.number="formContract.balance_amount"
type="number"
step="0.01"
class="mt-1 block w-full"
autocomplete="off"
/>
<InputLabel for="balanceAmount" value="Odprti znesek" />
<CurrencyInput id="balanceAmount" v-model="formContract.balance_amount" />
</div>
</div>
<div class="flex justify-end mt-4">
@ -215,12 +227,14 @@ const storeOrUpdate = () => {
Shranjuje.
</ActionMessage>
<PrimaryButton :class="{ 'opacity-25': formContract.processing }" :disabled="formContract.processing">
{{ formContract.uuid ? 'Posodobi' : 'Shrani' }}
<PrimaryButton
:class="{ 'opacity-25': formContract.processing }"
:disabled="formContract.processing"
>
{{ formContract.uuid ? "Posodobi" : "Shrani" }}
</PrimaryButton>
</div>
</form>
</template>
</DialogModal>
</template>

View File

@ -1,5 +1,6 @@
<script setup>
import DialogModal from "@/Components/DialogModal.vue";
import CurrencyInput from "@/Components/CurrencyInput.vue";
const props = defineProps({
show: { type: Boolean, default: false },
@ -19,12 +20,12 @@ const onSubmit = () => emit("submit");
<div class="space-y-3">
<div>
<label class="block text-sm text-gray-700 mb-1">Znesek</label>
<input
type="number"
step="0.01"
min="0"
v-model.number="form.amount"
class="w-full rounded border-gray-300"
<CurrencyInput
id="paymentAmount"
v-model="form.amount"
:precision="{ min: 0, max: 2 }"
placeholder="0,00"
class="w-full"
/>
<div v-if="form.errors?.amount" class="text-sm text-red-600 mt-0.5">
{{ form.errors.amount }}
@ -45,7 +46,11 @@ const onSubmit = () => emit("submit");
</div>
<div class="flex-1">
<label class="block text-sm text-gray-700 mb-1">Datum</label>
<input type="date" v-model="form.paid_at" class="w-full rounded border-gray-300" />
<input
type="date"
v-model="form.paid_at"
class="w-full rounded border-gray-300"
/>
<div v-if="form.errors?.paid_at" class="text-sm text-red-600 mt-0.5">
{{ form.errors.paid_at }}
</div>
@ -53,7 +58,11 @@ const onSubmit = () => emit("submit");
</div>
<div>
<label class="block text-sm text-gray-700 mb-1">Sklic</label>
<input type="text" v-model="form.reference" class="w-full rounded border-gray-300" />
<input
type="text"
v-model="form.reference"
class="w-full rounded border-gray-300"
/>
<div v-if="form.errors?.reference" class="text-sm text-red-600 mt-0.5">
{{ form.errors.reference }}
</div>
@ -61,7 +70,11 @@ const onSubmit = () => emit("submit");
</div>
</template>
<template #footer>
<button type="button" class="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300" @click="onClose">
<button
type="button"
class="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300"
@click="onClose"
>
Prekliči
</button>
<button
@ -74,5 +87,4 @@ const onSubmit = () => emit("submit");
</button>
</template>
</DialogModal>
</template>