33namespace Coderflex \LaravelCsv \Http \Livewire ;
44
55use Coderflex \LaravelCsv \Concerns ;
6+ use Coderflex \LaravelCsv \Jobs \ImportCsv ;
67use Coderflex \LaravelCsv \Utilities \ChunkIterator ;
8+ use Illuminate \Support \Facades \Bus ;
79use Illuminate \Support \MessageBag ;
810use Illuminate \Validation \Validator ;
911use Livewire \Component ;
1012use Livewire \WithFileUploads ;
1113
12- class ImportCsv extends Component
14+ class CsvImporter extends Component
1315{
1416 use WithFileUploads;
1517 use Concerns \InteractsWithColumns;
@@ -36,6 +38,12 @@ class ImportCsv extends Component
3638 /** @var int */
3739 public int $ fileRowCount = 0 ;
3840
41+ /** @var array */
42+ protected $ exception = [
43+ 'mode ' , 'columnsToMap ' , 'open ' ,
44+ 'columnLabels ' , 'requiredColumns ' ,
45+ ];
46+
3947 public function mount ()
4048 {
4149 // map and coverts the columnsToMap property into an associative array
@@ -61,9 +69,11 @@ public function import()
6169 {
6270 $ this ->validate ();
6371
64- $ import = $ this ->createNewImport ();
72+ $ this ->importCsv ();
6573
66- $ chunks = (new ChunkIterator ($ this ->csvRecords ->getIterator (), 10 ))->get ();
74+ $ this ->resetExcept ($ this ->exceptions );
75+
76+ $ this ->emitTo ('csv-imports ' , 'imports.refresh ' );
6777 }
6878
6979 public function render ()
@@ -107,4 +117,25 @@ protected function createNewImport()
107117 'total_rows ' => $ this ->fileRowCount ,
108118 ]);
109119 }
120+
121+ protected function importCsv ()
122+ {
123+ $ import = $ this ->createNewImport ();
124+ $ chunks = (new ChunkIterator ($ this ->csvRecords ->getIterator (), 10 ))->get ();
125+
126+ $ jobs = collect ($ chunks )
127+ ->map (
128+ fn ($ chunk ) => new ImportCsv (
129+ $ import ,
130+ $ this ->model ,
131+ $ chunk ,
132+ $ this ->columnsToMap
133+ )
134+ );
135+
136+ Bus::batch ($ jobs )
137+ ->finally (
138+ fn () => $ import ->touch ('compoleted_at ' )
139+ )->dispatch ();
140+ }
110141}
0 commit comments