import(storage_path('app/public/csv/Fixed_EJ.csv')); $array = $collection->toArray(); foreach ($array as $row) { $startDate = Carbon::parse($row['start_date'])->format('Y-m-d'); $endDate = Carbon::parse($row['end_date'])->format('Y-m-d'); $client = Client::where('customer_id', str_replace('-', '', $row['customer_id']))->first(); if ($client) { $client->update([ 'industry' => $row['industry'], ]); $salesUser = User::where('name', $row['sales'])->first(); $pic = User::where('name', $row['pic'])->first(); if ($pic) { ClientUserAssignation::updateOrCreate( [ 'client_id' => $client->id, 'role' => ClientUserAssignation::ROLE_ASSIGNED_PERSON, ], [ 'user_id' => $pic->id, ] ); } if ($salesUser) { ClientUserAssignation::updateOrCreate( [ 'client_id' => $client->id, 'role' => ClientUserAssignation::ROLE_SALES_PERSON, ], [ 'user_id' => $salesUser->id, ] ); } $row['client_id'] = $client->id; // if ($client->status != 'CANCELED') { // $campaigns = $adsService->listCampaigns($row['customer_id']); // Log::info('Hydrated client data', [ // 'campaigns' => $campaigns, // ]); // foreach ($campaigns as $campaign) { // Log::info('Hydrated client data', [ // 'campaigns' => $campaign['id'], // ]); // if (empty($invoice->start_date) || empty($invoice->end_date)) { // $totalSpend = 0; // $spend += number_format($totalSpend, 2, '.', ''); // } else { // $metrics = $adsService->listCampaignsMetricsById( // $row['customer_id'], // $campaign['id'], // $startDate, // $endDate // ); // Log::info('Hydrated client data', [ // 'metrics' => $metrics, // ]); // $totalSpend = array_sum(array_column($metrics, 'actual_spend')); // $spend += number_format($totalSpend, 2, '.', ''); // } // } // } else { $spend = 0; // } $invoice = ClientInvoice::updateOrCreate( ['invoice_no' => $row['invoice_no']], [ 'client_id' => $row['client_id'], 'is_credit_card' => intval(str_replace(',', '',$row['media_fee'])) == 0 ? 1 : 0, 'start_date' => $startDate, 'end_date' => $endDate, 'management_fee' => intval(str_replace(',', '',$row['management_fee'])) ?? 0, 'media_fee' => intval(str_replace(',', '',$row['media_fee'])) ?? 0, 'tax_percent' => 8, 'nett_amount' => intval(str_replace(',', '',$row['media_fee'])) > 0 ? intval(str_replace(',', '',$row['media_fee'])) / 1.08 : 0, 'total_spending' => $spend, ] ); $approvalService->approve($invoice); } else { Log::warning('Client not found for customer_id: '.str_replace('-', '', $row['customer_id'])); continue; // Skip this row if client not found } } DB::commit(); } catch (\Exception $e) { DB::rollBack(); Log::error('Error project linkage : '.$e->getMessage(), [ 'trace' => $e->getTraceAsString(), ]); return 1; } } }