diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index d3217ead20..950be6e3e9 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -77,7 +77,8 @@ class CheckData extends Command } $this->checkInvoices(); - $this->checkBalances(); + $this->checkInvoiceBalances(); + $this->checkClientBalances(); $this->checkContacts(); $this->checkUserAccounts(); @@ -530,14 +531,14 @@ class CheckData extends Command { // update client paid_to_date value $clients = DB::table('clients') - ->join('payments', 'payments.client_id', '=', 'clients.id') - ->join('invoices', 'invoices.id', '=', 'payments.invoice_id') - ->where('payments.is_deleted', '=', 0) - ->where('payments.payment_status_id', '!=', 2) - ->where('payments.payment_status_id', '!=', 3) - ->where('invoices.is_deleted', '=', 0) + ->leftJoin('payments', function($join) { + $join->on('payments.client_id', '=', 'clients.id') + ->where('payments.payment_status_id', '!=', 2) + ->where('payments.payment_status_id', '!=', 3) + ->where('payments.is_deleted', '=', 0); + }) ->groupBy('clients.id') - ->havingRaw('clients.paid_to_date != sum(payments.amount - payments.refunded) and clients.paid_to_date != 999999999.9999') + ->havingRaw('clients.paid_to_date != coalesce(sum(payments.amount - payments.refunded), 0) and clients.paid_to_date != 999999999.9999') ->get(['clients.id', 'clients.paid_to_date', DB::raw('sum(payments.amount) as amount')]); $this->logMessage(count($clients) . ' clients with incorrect paid to date'); @@ -554,7 +555,28 @@ class CheckData extends Command } } - private function checkBalances() + private function checkInvoiceBalances() + { + $invoices = DB::table('invoices') + ->leftJoin('payments', function($join) { + $join->on('payments.invoice_id', '=', 'invoices.id') + ->where('payments.payment_status_id', '!=', 2) + ->where('payments.payment_status_id', '!=', 3) + ->where('payments.is_deleted', '=', 0); + }) + ->where('invoices.updated_at', '>', '2017-10-01') + ->groupBy('invoices.id') + ->havingRaw('(invoices.amount - invoices.balance) != coalesce(sum(payments.amount - payments.refunded), 0)') + ->get(['invoices.id', 'invoices.amount', 'invoices.balance', DB::raw('coalesce(sum(payments.amount - payments.refunded), 0)')]); + + $this->logMessage(count($invoices) . ' invoices with incorrect balances'); + + if (count($invoices) > 0) { + $this->isValid = false; + } + } + + private function checkClientBalances() { // find all clients where the balance doesn't equal the sum of the outstanding invoices $clients = DB::table('clients')