initial commit
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Imports;
|
||||
|
||||
use App\Models\WeightHistory;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Maatwebsite\Excel\Concerns\ToCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithStartRow;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
||||
|
||||
class CatWeightImport implements ToCollection, WithStartRow
|
||||
{
|
||||
// Tambahkan variabel untuk menghitung data yang sukses
|
||||
private int $importedCount = 0;
|
||||
|
||||
public function startRow(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function collection(Collection $rows)
|
||||
{
|
||||
foreach ($rows as $row) {
|
||||
$catId = $row[0] ?? null;
|
||||
$berat = $row[2] ?? null;
|
||||
$tanggalExcel = $row[3] ?? null;
|
||||
|
||||
if (empty($catId) || empty($berat) || empty($tanggalExcel)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parsedDate = null;
|
||||
try {
|
||||
if (is_numeric($tanggalExcel)) {
|
||||
$parsedDate = Date::excelToDateTimeObject($tanggalExcel);
|
||||
} else {
|
||||
$tanggalExcel = str_ireplace(
|
||||
['januari', 'februari', 'maret', 'april', 'mei', 'juni', 'juli', 'agustus', 'september', 'oktober', 'november', 'desember'],
|
||||
['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'],
|
||||
$tanggalExcel
|
||||
);
|
||||
$parsedDate = Carbon::parse($tanggalExcel);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$carbonDate = Carbon::instance($parsedDate);
|
||||
$dateOnly = $carbonDate->format('Y-m-d');
|
||||
$timeOnly = $carbonDate->format('H:i:s');
|
||||
|
||||
$existingRecord = WeightHistory::where('cat_id', $catId)
|
||||
->whereDate('tanggal_timbang', $dateOnly)
|
||||
->first();
|
||||
|
||||
if ($existingRecord) {
|
||||
$finalTime = ($timeOnly === '00:00:00') ? Carbon::parse($existingRecord->tanggal_timbang)->format('H:i:s') : $timeOnly;
|
||||
|
||||
$existingRecord->update([
|
||||
'berat' => $berat,
|
||||
'tanggal_timbang' => $dateOnly . ' ' . $finalTime,
|
||||
]);
|
||||
|
||||
// Tambah hitungan jika berhasil update
|
||||
$this->importedCount++;
|
||||
} else {
|
||||
$finalTime = ($timeOnly === '00:00:00') ? now()->format('H:i:s') : $timeOnly;
|
||||
|
||||
WeightHistory::create([
|
||||
'cat_id' => $catId,
|
||||
'berat' => $berat,
|
||||
'tanggal_timbang' => $dateOnly . ' ' . $finalTime,
|
||||
]);
|
||||
|
||||
// Tambah hitungan jika berhasil insert baru
|
||||
$this->importedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fungsi untuk melempar total hitungan ke Controller
|
||||
public function getImportedCount(): int
|
||||
{
|
||||
return $this->importedCount;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user