Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.1 kB
5
Indexable
Never
        $journal = Journal::with(['cashbank', 'ccLog', 'mutation'])->where('user_id', $userID)
            ->where('id', $id)
            ->firstOrFail();

        // berarti pemasukan
        if($journal->status_credit > 0) {
            $totalSaldoJikaDihapus = Journal::where('user_id', '=', $userID)
                ->where('id', '!=', $journal->id)
                ->where('cashbank_id', $journal->cashbank_id)
                ->lockForUpdate()
                ->sum(DB::raw('amount * status_credit'));

            // ini validasi pertama, jika keseluruhan saldo kurang dari 0, langsung errorin
            if ($totalSaldoJikaDihapus < 0) {
                throw new \Exception('Data tidak bisa dihapus, karena jika dihapus, jadinya saldonya minus.');
            }

            $saldoSebelumDihapus = Journal::where('user_id', '=', $userID)
                ->where('created_at', '<', $journal->created_at)
                ->where('cashbank_id', $journal->cashbank_id)
                ->where('id', '!=', $journal->id)
                ->lockForUpdate()
                ->sum(DB::raw('amount * status_credit'));

            // ini validasi kedua, ambil data setelah dihapus, di validasi
            $journals = Journal::select([
                'id', 'user_id', 'created_at', 'cashbank_id', 'created_at', 'amount', 'status_credit'
            ])->where('user_id', '=', $userID)
                ->where('created_at', '>', $journal->created_at)
                ->where('cashbank_id', $journal->cashbank_id)
                ->where('id', '!=', $journal->id)
                ->orderBy('created_at')
                ->get();

            $balance = $saldoSebelumDihapus;
            foreach ($journals as $journal) {
                $amount = $journal->amount * $journal->status_credit;
                $balance -= $amount;
                
                if ($balance < 0) {
                    throw new \Exception('Gagal dihapus, saldo tidak boleh minus.');
                }
            }
        }

        $cashbank = $journal->cashbank;