whereDate('updated_at', '>=', Carbon::parse('01-01-2023')) ->orderBy('id') ->chunk(100, function ($bookings) use ($processed_invoice) { foreach ($bookings as $booking) { Log::channel('regenerateInvoice')->info('Counter ' . $processed_invoice); $processed_invoice += 1; if ($booking->transactions()->where('transactions.type', TransactionType::INVOICE) ->first() ->created_at ->greaterThanOrEqualTo(Carbon::parse('2023-09-06')) ) { continue; } $booking->transactions()->whereIn('transactions.type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->delete(); $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete(); $booking->status = ApprovalStatus::APPROVED; $booking->save(); $deletedInvoice = $booking->transactions() ->whereIn('type', [TransactionType::INVOICE]) ->onlyTrashed() ->orderBy('created_at', 'asc') ->first(); if ($deletedInvoice) { $bill_no = $deletedInvoice->bill_no; // check if bill_no ends with '-deleted' if (str_ends_with($bill_no, '-deleted')) { $bill_no = str_replace('-deleted', '', $bill_no); } $deletedInvoice->bill_no = $bill_no . '-deleted'; $deletedInvoice->save(); $existing_invoice_bill_no = Transaction::where('bill_no', $bill_no)->first(); if ($existing_invoice_bill_no) { Log::channel('regenerateInvoice')->info('Delete existing bill_no'); Log::channel('regenerateInvoice')->info(json_encode($existing_invoice_bill_no)); $existing_invoice_bill_no->forceDelete(); } (App()->make(CreateInvoiceTransactionProcessorWithInvoiceNo::class))->execute($booking, $bill_no); dump('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no); Log::channel('regenerateInvoice')->info('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no); } else { (App()->make(CreateInvoiceTransactionProcessor::class))->execute($booking); dump('regenerated new invoice. Booking Marking - ' . $booking->marking); Log::channel('regenerateInvoice')->info('regenerated new invoice. Booking Marking - ' . $booking->marking); } } }); } }