<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use App\Helper\TransactionCodeHelper;
|
|
use DateTime;
|
|
|
|
class FileUpload extends Controller
|
|
{
|
|
/**
|
|
* Return the csv-upload view on GET request to /
|
|
*
|
|
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
|
|
*/
|
|
public function createForm()
|
|
{
|
|
return view('csv-upload');
|
|
}
|
|
|
|
/**
|
|
* Parse and return the CSV data on POST request to /
|
|
*
|
|
* @param $request Request
|
|
* @return \Illuminate\Http\RedirectResponse
|
|
*/
|
|
public function fileUpload(Request $request)
|
|
{
|
|
$request->validate([
|
|
'file' => 'required|mimes:csv|max:4098'
|
|
]);
|
|
|
|
|
|
if (!$request->file()) {
|
|
return back();
|
|
}
|
|
|
|
$result = [];
|
|
|
|
$csv_contents = $request->file('file')->getContent();
|
|
$rows = str_getcsv($csv_contents, PHP_EOL);
|
|
|
|
$headers = null;
|
|
|
|
foreach ($rows as $index => $row) {
|
|
$columns = str_getcsv($row, ',');
|
|
|
|
if ($index === 0) {
|
|
$headers = (object) [
|
|
'Date',
|
|
'Transaction Number',
|
|
'Transaction Valid',
|
|
'Customer Number',
|
|
'Reference',
|
|
'Amount',
|
|
];
|
|
continue;
|
|
}
|
|
|
|
$date = new DateTime($columns[0] ?? null);
|
|
|
|
$valid_transaction = TransactionCodeHelper::verifyKey($columns[1]) ? 'Yes' : 'No'; $amount = sprintf(
|
|
'$%s',
|
|
number_format((float) ((int) $columns[4] / 100) ?? null, 2, '.', ''),
|
|
);
|
|
|
|
|
|
$result[$index] = (object) [
|
|
$date->format('Y/m/d h:i a'),
|
|
$columns[1] ?? null,
|
|
$valid_transaction,
|
|
$columns[2] ?? null,
|
|
$columns[3] ?? null,
|
|
$amount,
|
|
];
|
|
}
|
|
|
|
usort($result, function ($a, $b) {
|
|
return strtotime($a->{0}) < strtotime($b->{0});
|
|
});
|
|
|
|
$result[0] = $headers;
|
|
|
|
return back()
|
|
->with('results', (object) $result);
|
|
}
|
|
}
|