1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 21:22:58 +01:00
invoiceninja/app/Http/Controllers/ImportController.php

263 lines
7.9 KiB
PHP
Raw Normal View History

2020-12-12 11:01:53 +01:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2023-01-28 23:21:40 +01:00
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
2020-12-12 11:01:53 +01:00
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2020-12-12 11:01:53 +01:00
*/
namespace App\Http\Controllers;
2020-12-14 23:59:41 +01:00
use App\Http\Requests\Import\ImportRequest;
2020-12-12 11:01:53 +01:00
use App\Http\Requests\Import\PreImportRequest;
2022-02-17 03:27:21 +01:00
use App\Jobs\Import\CSVIngest;
2021-02-13 01:20:15 +01:00
use Illuminate\Http\UploadedFile;
2020-12-12 11:01:53 +01:00
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
2020-12-14 05:59:15 +01:00
use League\Csv\Reader;
use League\Csv\Statement;
2020-12-12 11:01:53 +01:00
class ImportController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @param PreImportRequest $request
*
* @return \Illuminate\Http\JsonResponse
*
* @OA\Post(
* path="/api/v1/preimport",
* operationId="preimport",
* tags={"imports"},
* summary="Pre Import checks - returns a reference to the job and the headers of the CSV",
* description="Pre Import checks - returns a reference to the job and the headers of the CSV",
2023-02-10 10:21:10 +01:00
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),
* @OA\RequestBody(
* description="The CSV file",
* required=true,
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* type="string",
* format="binary"
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Returns a reference to the file",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
*
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
*/
public function preimport(PreImportRequest $request)
{
// Create a reference
$hash = Str::random(32);
$data = [
'hash' => $hash,
'mappings' => [],
];
/** @var UploadedFile $file */
foreach ($request->files->get('files') as $entityType => $file) {
$contents = file_get_contents($file->getPathname());
2023-07-22 08:00:57 +02:00
$contents = $this->convertEncoding($contents);
// Store the csv in cache with an expiry of 10 minutes
Cache::put($hash.'-'.$entityType, base64_encode($contents), 600);
2024-01-14 05:05:00 +01:00
// Parse CSV
$csv_array = $this->getCsvData($contents);
$class_map = $this->getEntityMap($entityType);
2024-01-14 05:05:00 +01:00
2023-09-05 09:29:36 +02:00
$hints = $this->setImportHints($entityType, $class_map::importable(), $csv_array[0]);
$data['mappings'][$entityType] = [
'available' => $class_map::importable(),
'headers' => array_slice($csv_array, 0, 2),
2023-09-05 09:29:36 +02:00
'hints' => $hints,
];
}
return response()->json($data);
}
2023-09-05 09:29:36 +02:00
private function setImportHints($entity_type, $available_keys, $headers): array
{
$hints = [];
2023-10-26 04:57:44 +02:00
$translated_keys = collect($available_keys)->map(function ($value, $key) {
2024-01-14 05:05:00 +01:00
2023-09-05 09:29:36 +02:00
$parts = explode(".", $value);
$index = $parts[0];
$label = $parts[1] ?? $parts[0];
return ['key' => $key, 'index' => ctrans("texts.{$index}"), 'label' => ctrans("texts.{$label}")];
})->toArray();
foreach($headers as $key => $value) {
2024-01-14 05:05:00 +01:00
2023-10-26 04:57:44 +02:00
foreach($translated_keys as $tkey => $tvalue) {
2024-01-14 05:05:00 +01:00
2023-09-05 09:29:36 +02:00
if($this->testMatch($value, $tvalue['label'])) {
2023-09-07 05:43:22 +02:00
$hit = $tvalue['key'];
$hints[$key] = $hit;
unset($translated_keys[$tkey]);
break;
2023-10-26 04:57:44 +02:00
} else {
2023-09-07 05:43:22 +02:00
$hints[$key] = null;
2023-09-05 09:29:36 +02:00
}
2024-01-14 05:05:00 +01:00
2023-09-05 09:29:36 +02:00
}
2024-01-14 05:05:00 +01:00
2023-09-07 05:43:22 +02:00
}
//second pass using the index of the translation here
2023-10-26 04:57:44 +02:00
foreach($headers as $key => $value) {
2023-09-07 05:43:22 +02:00
if(isset($hints[$key])) {
continue;
2023-09-05 09:29:36 +02:00
}
2023-10-26 04:57:44 +02:00
foreach($translated_keys as $tkey => $tvalue) {
2023-09-07 05:43:22 +02:00
if($this->testMatch($value, $tvalue['index'])) {
$hit = $tvalue['key'];
$hints[$key] = $hit;
unset($translated_keys[$tkey]);
break;
} else {
$hints[$key] = null;
}
}
2024-01-14 05:05:00 +01:00
2023-09-05 09:29:36 +02:00
}
return $hints;
}
private function testMatch($haystack, $needle): bool
2023-10-26 04:57:44 +02:00
{
2023-09-05 09:29:36 +02:00
return stripos($haystack, $needle) !== false;
}
2023-07-22 08:00:57 +02:00
private function convertEncoding($data)
{
2024-01-14 05:05:00 +01:00
2023-07-22 08:00:57 +02:00
$enc = mb_detect_encoding($data, mb_list_encodings(), true);
2024-01-14 05:05:00 +01:00
2023-07-22 08:00:57 +02:00
if($enc !== false) {
$data = mb_convert_encoding($data, "UTF-8", $enc);
}
return $data;
}
public function import(ImportRequest $request)
{
2023-09-06 06:41:15 +02:00
/** @var \App\Models\User $user */
$user = auth()->user();
$data = $request->all();
2022-07-31 11:11:32 +02:00
if (empty($data['hash'])) {
// Create a reference
$data['hash'] = $hash = Str::random(32);
/** @var UploadedFile $file */
foreach ($request->files->get('files') as $entityType => $file) {
$contents = file_get_contents($file->getPathname());
// Store the csv in cache with an expiry of 10 minutes
Cache::put($hash.'-'.$entityType, base64_encode($contents), 600);
}
}
unset($data['files']);
2023-09-06 06:41:15 +02:00
CSVIngest::dispatch($data, $user->company());
return response()->json(['message' => ctrans('texts.import_started')], 200);
}
private function getEntityMap($entity_type)
{
2022-11-02 21:54:34 +01:00
return sprintf('App\\Import\\Definitions\%sMap', ucfirst(Str::camel($entity_type)));
}
private function getCsvData($csvfile)
{
if (! ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
2020-12-12 11:01:53 +01:00
}
$csv = Reader::createFromString($csvfile);
$csvdelimiter = self::detectDelimiter($csvfile);
$csv->setDelimiter($csvdelimiter);
2020-12-12 11:01:53 +01:00
$stmt = new Statement();
$data = iterator_to_array($stmt->process($csv));
if (count($data) > 0) {
$headers = $data[0];
// Remove Invoice Ninja headers
if (count($headers) && count($data) > 4) {
$firstCell = $headers[0];
2020-12-18 01:31:27 +01:00
if (strstr($firstCell, (string) config('ninja.app_name'))) {
array_shift($data); // Invoice Ninja...
array_shift($data); // <blank line>
array_shift($data); // Entity Type Header
}
2020-12-12 11:01:53 +01:00
}
}
return $data;
}
2023-07-26 06:44:39 +02:00
/**
* Returns the best delimiter
*
* @param string $csvfile
* @return string
*/
public function detectDelimiter($csvfile): string
{
2023-02-16 02:36:09 +01:00
$delimiters = [',', '.', ';'];
2023-01-11 23:20:24 +01:00
$bestDelimiter = ' ';
$count = 0;
2023-07-04 01:07:31 +02:00
2023-02-16 02:36:09 +01:00
foreach ($delimiters as $delimiter) {
2023-07-26 06:44:39 +02:00
if (substr_count(strstr($csvfile, "\n", true), $delimiter) >= $count) {
2023-07-26 06:44:39 +02:00
$count = substr_count(strstr($csvfile, "\n", true), $delimiter);
2023-10-26 04:57:44 +02:00
$bestDelimiter = $delimiter;
}
2024-01-14 05:05:00 +01:00
2023-02-16 02:36:09 +01:00
}
2023-07-26 06:44:39 +02:00
return $bestDelimiter;
}
2020-12-12 11:01:53 +01:00
}