Update Handle Multi Sheet Plan & Benefit

This commit is contained in:
2022-07-27 11:04:44 +07:00
parent afc574d501
commit dd97ba2e25
8 changed files with 355 additions and 25 deletions

View File

@@ -2,9 +2,12 @@
namespace Modules\Internal\Http\Controllers\Api;
use App\Exceptions\ImportRowException;
use App\Imports\PlansImport;
use App\Models\Benefit;
use App\Models\Corporate;
use App\Models\Plan;
use App\Services\ImportService;
use DB;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
@@ -12,6 +15,7 @@ use Illuminate\Routing\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Support\Facades\Storage;
use Modules\Internal\Services\CorporateService;
class CorporateController extends Controller
{
@@ -169,4 +173,109 @@ class CorporateController extends Controller
{
//
}
public function importPlanBenefit(Request $request, $corporate_id)
{
$request->validate([
'file' => 'required|file|mimes:xls,xlsx,csv,txt',
]);
// dd($request->toArray());
$file_name = now()->getPreciseTimestamp(3).'-'.$request->file('file')->getClientOriginalName();
$file = $request->file('file')->storeAs('temp', $file_name);
$corporate = Corporate::findOrFail($corporate_id);
$import = new ImportService();
$import->read(Storage::path('temp/'.$file_name));
$import->write(Storage::disk('public')->path('temp/result-'.$file_name), 'xsls');
foreach ($import->sheetsIterator() as $sheetIndex => $sheet) {
if ( !in_array($sheet->getName(), ['Plan', 'Benefit']) ) {
continue;
} else {
if ($sheetIndex == 1) { // Rename First Sheet to Writer
$firstWriterSheet = $import->writer->getCurrentSheet();
$firstWriterSheet->setName($sheet->getName());
} else { // Add New Sheet to Writer
$nextWriterSheet = $import->writer->addNewSheetAndMakeItCurrent();
$nextWriterSheet->setName($sheet->getName());
}
if ( $sheet->getName() == 'Plan' ) {
$headers_map_to_table_fields = Plan::$doc_headers_to_field_map;
} else if ( $sheet->getName() == 'Benefit' ) {
$headers_map_to_table_fields = Benefit::$doc_headers_to_field_map;
}
// Write Header to File
$result_headers = array_keys($headers_map_to_table_fields);
$result_headers = array_merge($result_headers, ['Ingest Code', 'Ingest Note']);
$import->addArrayToRow($result_headers);
}
$doc_headers_indexes = [];
foreach ($sheet->getRowIterator() as $index => $row) {
if ($index == 1) { // First Row Must be Header
foreach ($row->getCells() as $index => $cell) {
$title = $cell->getValue();
$title = preg_replace( "/\r|\n/", " ", $title );
$title = preg_replace('/\xc2\xa0/', " ", $title );
$title = rtrim($title);
$title = ltrim($title);
$doc_headers_indexes[$index] = $title;
}
// TODO Validate if First Row not Header
} else { // Next Row Should be Data
$row_data = [];
foreach ($row->getCells() as $header_index => $cell) {
if (isset($headers_map_to_table_fields[$doc_headers_indexes[$header_index]]))
$row_data[$headers_map_to_table_fields[$doc_headers_indexes[$header_index]]] = $cell->getValue();
}
try { // Process the Row Data
$corporateService = new CorporateService();
if ( $sheet->getName() == 'Plan' ) {
$corporateService->handlePlanRow($corporate, $row_data);
} else if ( $sheet->getName() == 'Benefit' ) {
$corporateService->handleBenefitRow($corporate, $row_data);
}
// Write Success Result to File
$import->addArrayToRow(array_merge($row_data, [
'Ingest Code' => 200,
'Ingest Note' => 'Success',
]), $sheet->getName());
} catch (ImportRowException $e) {
// Write Data Validation Error to File
$import->addArrayToRow(array_merge($row_data, [
'Ingest Code' => $e->getCode(),
'Ingest Note' => $e->getMessage(),
]), $sheet->getName());
} catch (\Exception $e) {
// throw new \Exception($e);
// Write Server Error to File
$import->addArrayToRow(array_merge($row_data, [
'Ingest Code' => 500,
'Ingest Note' => env('APP_DEBUG') ? $e->getMessage() : 'Server Error',
]), $sheet->getName());
}
}
}
}
$import->reader->close();
Storage::delete('temp/'.$file_name);
$import->writer->close();
return [
// 'total_successed_row' => $imported_plan_data,
// 'total_failed_row' => count($failed_plan_data),
// 'failed_row' => $failed_plan_data,
'result_file' => [
'url' => Storage::disk('public')->url('temp/result-'.$file_name),
'name' => 'result-'.$file_name,
]
];
}
}

View File

@@ -2,15 +2,25 @@
namespace Modules\Internal\Http\Controllers\Api;
use App\Exceptions\ImportRowException;
use App\Models\Corporate;
use App\Models\Plan;
use App\Services\ImportService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Modules\Internal\Services\CorporateService;
class PlanController extends Controller
{
public function __construct(CorporateService $corporateService, ImportService $importService)
{
$this->corporateService = $corporateService;
$this->importService = $importService;
}
/**
* Display a listing of the resource.
* @return Renderable
@@ -19,10 +29,11 @@ class PlanController extends Controller
{
$plans = Plan::query()
->filter($request->all())
->whereHas('corporatePlan', function ($corporatePlan) use ($corporate_id) {
$corporatePlan->where('corporate_id', $corporate_id);
})
->with('corporatePlan')
->where('corporate_id', $corporate_id)
// ->whereHas('corporatePlan', function ($corporatePlan) use ($corporate_id) {
// $corporatePlan->where('corporate_id', $corporate_id);
// })
// ->with('corporatePlan')
->paginate(0)
->appends($request->all());
@@ -96,17 +107,23 @@ class PlanController extends Controller
]);
$file_name = now()->getPreciseTimestamp(3).'-'.$request->file('file')->getClientOriginalName();
$file = $request->file('file')->storeAs('temp', $file_name);
// return false;
$reader = ReaderEntityFactory::createReaderFromFile(Storage::path('temp/'.$file_name));
$reader->open(Storage::path('temp/'.$file_name));
$corporate = Corporate::findOrFail($corporate_id);
$import = $this->importService;
$import->read(Storage::path('temp/'.$file_name));
$import->write(Storage::disk('public')->path('temp/result-'.$file_name), 'xsls');
$headers_map_to_table_fields = Plan::$doc_headers_to_field_map;
// Write Header to File
$result_headers = array_keys($headers_map_to_table_fields);
array_push($result_headers, ['Ingest Code', 'Ingest Note']);
$import->addArrayToRow($result_headers);
die('fuck');
$imported_plan_data = 0;
$failed_plan_data = [];
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($import->reader->getSheetIterator() as $sheet) {
$doc_headers_indexes = [];
foreach ($sheet->getRowIterator() as $index => $row) {
if ($index == 1) { // First Row Must be Header
@@ -114,35 +131,50 @@ class PlanController extends Controller
$doc_headers_indexes[$index] = $cell->getValue();
}
} else { // Next Row Should be Data
$new_plan_data = [];
foreach ($row->getCells() as $index => $cell) {
$new_plan_data[$headers_map_to_table_fields[$doc_headers_indexes[$index]]] = $cell->getValue();
$plan_row = [];
foreach ($row->getCells() as $header_index => $cell) {
if (isset($headers_map_to_table_fields[$doc_headers_indexes[$header_index]]))
$plan_row[$headers_map_to_table_fields[$doc_headers_indexes[$header_index]]] = $cell->getValue();
}
// $imported_plan_data[] = $new_row; // Insert to Array
// Create Directly
try {
Plan::updateOrCreate([
'code' => $new_plan_data['code']
], $new_plan_data);
$rowResponse = $this->corporateService->handlePlanRow($corporate, $plan_row);
// Write Success Result to File
array_push($plan_row, 'SUCCESS');
$import->addArrayToRow($plan_row);
$imported_plan_data++;
} catch(\Exception $e) {
$failed_plan_data[] = $new_plan_data;
} catch (ImportRowException $e) {
// Write Data Validation Error to File
array_push($plan_row, $e->getMessage());
$import->addArrayToRow($plan_row);
$failed_plan_data[] = ['row_number' => $index, 'error' => $e->getMessage()];
} catch (\Exception $e) {
// Write Server Error to File
array_push($plan_row, "Server Error");
$import->addArrayToRow($plan_row);
$failed_plan_data[] = ['row_number' => $index, 'error' => $e->getMessage()];
}
}
}
break; //only read first sheet
}
$reader->close();
$import->reader->close();
Storage::delete('temp/'.$file_name);
$import->writer->close();
// throw(404);
return [
'total_successed_row' => $imported_plan_data,
'total_failed_row' => count($failed_plan_data),
'failed_row' => $failed_plan_data
'failed_row' => $failed_plan_data,
'result_file' => [
'url' => Storage::disk('public')->url('temp/result-'.$file_name),
'name' => 'result-'.$file_name,
]
];
}
}