diff --git a/app/Models/Client.php b/app/Models/Client.php index d18127a69274..bd693ac0ac91 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -625,6 +625,29 @@ class Client extends EntityModel } } } + + public function getUsuallyPaysIn() { + $paysIn = $this->invoices() + ->with('payments') + ->where('invoice_status_id', '=', INVOICE_STATUS_PAID) + ->orderBy('invoice_date', 'desc') + ->take(20) + ->get() + ->map(function ($item) { + $payments = $item->payments()->orderBy('payment_date', 'asc')->get(); + $invoiceTotal = $item->amount; + + foreach($payments as $payment) { + if($payment->amount < $invoiceTotal) { + $invoiceTotal -= $payment->amount; + } elseif($payment->amount >= $invoiceTotal) { + return \Carbon::parse($item->invoice_date)->diffInDays($payment->payment_date); + } + } + })->avg(); + + return $paysIn; + } } Client::creating(function ($client) { diff --git a/app/Ninja/Presenters/ClientPresenter.php b/app/Ninja/Presenters/ClientPresenter.php index 5561ca9cbaa0..534e6ce0d36b 100644 --- a/app/Ninja/Presenters/ClientPresenter.php +++ b/app/Ninja/Presenters/ClientPresenter.php @@ -46,6 +46,12 @@ class ClientPresenter extends EntityPresenter return $account->formatMoney($client->paid_to_date, $client); } + public function usuallyPaysIn() { + $avgDays = $this->entity->getUsuallyPaysIn(); + + return Utils::roundSignificant($avgDays) . ' ' . trans('texts.usually_pays_in_days'); + } + public function paymentTerms() { $client = $this->entity; diff --git a/resources/lang/en/texts.php b/resources/lang/en/texts.php index 131efb5ccd47..9ccef9e741a9 100644 --- a/resources/lang/en/texts.php +++ b/resources/lang/en/texts.php @@ -3161,6 +3161,8 @@ $LANG = array( 'failed_to_find_record' => 'Failed to find record', 'valid_until_days' => 'Valid Until', 'valid_until_days_help' => 'Automatically sets the Valid Until value on quotes to this many days in the future. Leave blank to disable.', + 'usually_pays_in_days' => 'Days', + ); return $LANG; diff --git a/resources/views/clients/show.blade.php b/resources/views/clients/show.blade.php index 74b14ea53b31..2a1b08f6f418 100644 --- a/resources/views/clients/show.blade.php +++ b/resources/views/clients/show.blade.php @@ -212,6 +212,10 @@