diff --git a/app/Abstracts/Import.php b/app/Abstracts/Import.php index 54003fc60..4ccae7fc6 100644 --- a/app/Abstracts/Import.php +++ b/app/Abstracts/Import.php @@ -29,7 +29,15 @@ abstract class Import implements HasLocalePreference, ShouldQueue, SkipsEmptyRow public $user; + public $model; + public $request_class = null; + + public $with_trashed = false; + + public $columns = []; + + public $has_row = []; public function __construct() { @@ -209,4 +217,41 @@ abstract class Import implements HasLocalePreference, ShouldQueue, SkipsEmptyRow return str_replace($dependent_rules, $batch_rules, $rules); } + + //This function is used in import classes. If the data in the row exists in the database, it is returned. + public function hasRow($row) + { + // must be models and columns + if (empty($this->model) || empty($this->columns)) { + return false; + } + + /* This function is called for each row. + This check is done in order not to query again for each row. + When the model to which the query is thrown changes, the new query should be discarded. + */ + if (! $this->has_row || ! $this->has_row instanceof $this->model) { + $this->has_row = $this->model::withoutEvents(function () { + if ($this->with_trashed) { + // This query should be used if there is no deleted_at field in the table or if the deleted data is to be retrieved. + return $this->model::withTrashed()->get($this->columns)->each(function ($data) { + $data->setAppends([]); + }); + } else { + return $this->model::get($this->columns)->each(function ($data) { + $data->setAppends([]); + }); + } + }); + } + + $search_value = []; + + //In the model, the fields to be searched for the row are determined. + foreach ($this->columns as $key) { + $search_value[$key] = isset($row[$key]) ? $row[$key] : null; + } + + return in_array($search_value, $this->has_row->toArray()); + } } diff --git a/app/Imports/Banking/Transactions.php b/app/Imports/Banking/Transactions.php index 3253d1be0..56505ea94 100644 --- a/app/Imports/Banking/Transactions.php +++ b/app/Imports/Banking/Transactions.php @@ -11,10 +11,20 @@ class Transactions extends Import { use TraitsTransactions; + public $model = Model::class; + public $request_class = Request::class; + public $columns = [ + 'number', + ]; + public function model(array $row) { + if (self::hasRow($row)) { + return; + } + return new Model($row); } @@ -29,8 +39,15 @@ class Transactions extends Import $row['category_id'] = $this->getCategoryId($row, $real_type); $row['contact_id'] = $this->getContactId($row, $real_type); $row['document_id'] = $this->getDocumentId($row); - $row['parent_id'] = $this->getParentId($row); + $row['parent_id'] = $this->getParentId($row) ?? 0; return $row; } + + public function prepareRules($rules): array + { + $rules['number'] = 'required|string'; + + return $rules; + } }