where('created_at', '<', now()->subDays(60)->endOfDay()) ->whereHas('transactions', function($transaction) { return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); }) ->whereDoesntHave('transactions', function($transaction){ $transaction->where('type', TransactionType::PURCHASE_ORDER); $transaction->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED]); })->get(); Log::info('Bookings count: '.count($bookings)); foreach ($bookings as $booking) { $po = Transaction::where('type', TransactionType::PURCHASE_ORDER) ->where('status', ApprovalStatus::APPROVED)->where('issuer', $booking->company_id) ->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first(); if (!$po) { $po = Transaction::where('type', TransactionType::PURCHASE_ORDER) ->where('status', ApprovalStatus::APPROVED)->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first(); } $products = (App()->make(GeneratesPurchaseOrderProducts::class))->execute($po, $booking->fix_amount); $deference = $booking->fix_amount - $products->sum('total'); if($deference > -150 && $deference < 150 && $deference != 0) { $products->push([ 'description' => $deference < 0 ? 'Discount':'Shipping Fee', 'quantity' => 1, 'stockCode' => '', 'total' => $deference, 'unit_price' => $deference ]); } $billNumber = (App()->make(GeneratesTransactionBillNumber::class))->execute('XPO-'); Log::info('Single booking billNumber: '.$billNumber); $total = $products->sum('total'); $object = new TransactionObject($billNumber, TransactionType::PURCHASE_ORDER, $booking->company->id, 1, 1, PaymentMethodType::CASH, $total, $total, $booking->fix_currency_id, $booking->fix_currency_id, 1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, $products->toArray()); (App()->make(CreatePurchaseOrderTransactionProcessor::class))->execute($booking, $object); } $end = new Carbon(); $elapsedTime = $start->diff($end)->format('%H:%I:%S'); Log::info(Carbon::now() . ': End job - Auto fill up the purchase order for booking that have payment. ElapsedTime: ' . $elapsedTime . '.'); } }