Added asset model import to importer

Signed-off-by: snipe <snipe@snipe.net>
This commit is contained in:
snipe 2024-08-17 02:31:03 +01:00
parent 7e6ff3cbe6
commit 5066eb58f4
6 changed files with 164 additions and 11 deletions

View file

@ -0,0 +1,100 @@
<?php
namespace App\Importer;
use App\Models\AssetModel;
use Illuminate\Support\Facades\Log;
/**
* When we are importing users via an Asset/etc import, we use createOrFetchUser() in
* Importer\Importer.php. [ALG]
*
* Class LocationImporter
*/
class AssetModelImporter extends ItemImporter
{
protected $models;
public function __construct($filename)
{
parent::__construct($filename);
}
protected function handle($row)
{
parent::handle($row);
$this->createAssetModelIfNotExists($row);
}
/**
* Create a model if a duplicate does not exist.
* @todo Investigate how this should interact with Importer::createModelIfNotExists
*
* @author A. Gianotto
* @since 6.1.0
* @param array $row
*/
public function createAssetModelIfNotExists(array $row)
{
$editingAssetModel = false;
$assetmodel = AssetModel::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
if ($assetmodel) {
if (! $this->updating) {
$this->log('A matching Model '.$this->item['name'].' already exists');
return;
}
$this->log('Updating Model');
$editingAssetModel = true;
} else {
$this->log('No Matching Model, Create a new one');
$assetmodel = new AssetModel();
}
// Pull the records from the CSV to determine their values
$this->item['name'] = trim($this->findCsvMatch($row, 'name'));
$this->item['category'] = trim($this->findCsvMatch($row, 'category'));
$this->item['manufacturer'] = trim($this->findCsvMatch($row, 'manufacturer'));
$this->item['min_amt'] = trim($this->findCsvMatch($row, 'min_amt'));
$this->item['model_number'] = trim($this->findCsvMatch($row, 'model_number'));
$this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
$this->item['user_id'] = auth()->id();
if (!empty($this->item['category'])) {
if ($category = $this->createOrFetchCategory($row, 'category')) {
$this->item['category_id'] = $category->id;
}
}
if (!empty($this->item['manufacturer'])) {
if ($manufacturer = $this->createOrFetchManufacturer($row, 'manufacturer')) {
$this->item['manufacturer_id'] = $manufacturer->id;
}
}
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
if ($editingAssetModel) {
Log::debug('Updating existing model');
$assetmodel->update($this->sanitizeItemForUpdating($assetmodel));
} else {
Log::debug('Creating model');
$assetmodel->fill($this->sanitizeItemForStoring($assetmodel));
}
if ($assetmodel->save()) {
$this->log('AssetModel '.$assetmodel->name.' created or updated from CSV import');
return $assetmodel;
} else {
Log::debug($assetmodel->getErrors());
return $assetmodel->errors;
}
}
}

View file

@ -113,7 +113,7 @@ class ItemImporter extends Importer
protected function determineCheckout($row) protected function determineCheckout($row)
{ {
// Locations don't get checked out to anyone/anything // Locations don't get checked out to anyone/anything
if (get_class($this) == LocationImporter::class) { if ((get_class($this) == LocationImporter::class) || (get_class($this) == AssetModelImporter::class)) {
return; return;
} }
@ -287,14 +287,22 @@ class ItemImporter extends Importer
$classname = class_basename(get_class($this)); $classname = class_basename(get_class($this));
$item_type = strtolower(substr($classname, 0, strpos($classname, 'Importer'))); $item_type = strtolower(substr($classname, 0, strpos($classname, 'Importer')));
if ($item_type == 'assetmodel') {
$item_type = 'asset';
}
\Log::error('Item Type: '.$item_type);
if (empty($asset_category)) { if (empty($asset_category)) {
$asset_category = 'Unnamed Category'; $asset_category = 'Unnamed Category';
} }
$category = Category::where(['name' => $asset_category, 'category_type' => $item_type])->first(); $category = Category::where(['name' => $asset_category, 'category_type' => $item_type])->first();
if ($category) { if ($category) {
$this->log('A matching category: '.$asset_category.' already exists'); $this->log('A matching category: '.$asset_category.' already exists');
return $category->id; return $category->id;
} }

View file

@ -79,6 +79,7 @@ class Importer extends Component
private function getColumns($type) private function getColumns($type)
{ {
\Log::error($type);
switch ($type) { switch ($type) {
case 'asset': case 'asset':
$results = $this->assets_fields; $results = $this->assets_fields;
@ -101,10 +102,14 @@ class Importer extends Component
case 'location': case 'location':
$results = $this->locations_fields; $results = $this->locations_fields;
break; break;
case 'assetmodel':
$results = $this->assetmodels_fields;
break;
default: default:
$results = []; $results = [];
} }
asort($results, SORT_FLAG_CASE | SORT_STRING); asort($results, SORT_FLAG_CASE | SORT_STRING);
if ($type == "asset") { if ($type == "asset") {
// add Custom Fields after a horizontal line // add Custom Fields after a horizontal line
$results['-'] = "———" . trans('admin/custom_fields/general.custom_fields') . "———’"; $results['-'] = "———" . trans('admin/custom_fields/general.custom_fields') . "———’";
@ -143,6 +148,7 @@ class Importer extends Component
} }
// if you got here, we didn't find a match. Try the $aliases_fields // if you got here, we didn't find a match. Try the $aliases_fields
foreach ($this->aliases_fields as $key => $alias_values) { foreach ($this->aliases_fields as $key => $alias_values) {
\Log::error('No matches');
foreach ($alias_values as $alias_value) { foreach ($alias_values as $alias_value) {
if (strcasecmp($alias_value, $header) === 0) { // aLsO CaSe-INSENSitiVE! if (strcasecmp($alias_value, $header) === 0) { // aLsO CaSe-INSENSitiVE!
// Make *absolutely* sure that this key actually _exists_ in this import type - // Make *absolutely* sure that this key actually _exists_ in this import type -
@ -179,6 +185,7 @@ class Importer extends Component
'license' => trans('general.licenses'), 'license' => trans('general.licenses'),
'user' => trans('general.users'), 'user' => trans('general.users'),
'location' => trans('general.locations'), 'location' => trans('general.locations'),
'assetmodel' => trans('general.asset_models'),
]; ];
/** /**
@ -352,6 +359,18 @@ class Importer extends Component
'parent_location' => trans('admin/locations/table.parent'), 'parent_location' => trans('admin/locations/table.parent'),
]; ];
$this->assetmodels_fields = [
'item_name' => trans('general.item_name_var', ['item' => trans('general.asset_model')]),
'category' => trans('general.category'),
'manufacturer' => trans('general.manufacturer'),
'model_number' => trans('general.model_no'),
'notes' => trans('general.item_notes', ['item' => trans('admin/hardware/form.model')]),
'min_amt' => trans('mail.min_QTY'),
'fieldset' => trans('admin/models/general.fieldset'),
'category_type' => 'category type',
];
// "real fieldnames" to a list of aliases for that field // "real fieldnames" to a list of aliases for that field
$this->aliases_fields = [ $this->aliases_fields = [
'item_name' => 'item_name' =>
@ -527,18 +546,19 @@ class Importer extends Component
if (!$this->activeFile) { if (!$this->activeFile) {
$this->message = trans('admin/hardware/message.import.file_missing'); $this->message = trans('admin/hardware/message.import.file_missing');
$this->message_type = 'danger'; $this->message_type = 'danger';
return; return;
} }
$this->field_map = null; $this->field_map = null;
foreach($this->activeFile->header_row as $element) { foreach($this->activeFile->header_row as $element) {
if(isset($this->activeFile->field_map[$element])) { if(isset($this->activeFile->field_map[$element])) {
$this->field_map[] = $this->activeFile->field_map[$element]; $this->field_map[] = $this->activeFile->field_map[$element];
} else { } else {
$this->field_map[] = null; // re-inject the 'nulls' if a file was imported with some 'Do Not Import' settings $this->field_map[] = null; // re-inject the 'nulls' if a file was imported with some 'Do Not Import' settings
} }
} }
$this->file_id = $id; $this->file_id = $id;
$this->import_errors = null; $this->import_errors = null;
$this->statusText = null; $this->statusText = null;

View file

@ -557,7 +557,7 @@ return [
'something_went_wrong' => 'Something went wrong with your request.', 'something_went_wrong' => 'Something went wrong with your request.',
'close' => 'Close', 'close' => 'Close',
'expires' => 'Expires', 'expires' => 'Expires',
'map_fields'=> 'Map :item_type Field', 'map_fields'=> 'Map :item_type Fields',
'remaining_var' => ':count Remaining', 'remaining_var' => ':count Remaining',
'assets_in_var' => 'Assets in :name :type', 'assets_in_var' => 'Assets in :name :type',
'label' => 'Label', 'label' => 'Label',

View file

@ -170,16 +170,19 @@
<input type="checkbox" name="update" data-livewire-component="{{ $this->getId() }}" wire:model.live="update"> <input type="checkbox" name="update" data-livewire-component="{{ $this->getId() }}" wire:model.live="update">
{{ trans('general.update_existing_values') }} {{ trans('general.update_existing_values') }}
</label> </label>
@if ($activeFile->import_type === 'asset' && $snipeSettings->auto_increment_assets == 1 && $update) @if ($activeFile->import_type === 'asset' && $snipeSettings->auto_increment_assets == 1 && $update)
<p class="help-block"> <p class="help-block">
{{ trans('general.auto_incrementing_asset_tags_enabled_so_now_assets_will_be_created') }} {{ trans('general.auto_incrementing_asset_tags_enabled_so_now_assets_will_be_created') }}
</p> </p>
@endif @endif
@if ($activeFile->import_type != 'location' && $activeFile->import_type == 'assetmodel' && $update)
<label class="form-control"> <label class="form-control">
<input type="checkbox" name="send_welcome" data-livewire-component="{{ $this->getId() }}" wire:model.live="send_welcome"> <input type="checkbox" name="send_welcome" data-livewire-component="{{ $this->getId() }}" wire:model.live="send_welcome">
{{ trans('general.send_welcome_email_to_users') }} {{ trans('general.send_welcome_email_to_users') }}
</label> </label>
@endif
<label class="form-control"> <label class="form-control">
<input type="checkbox" name="run_backup" data-livewire-component="{{ $this->getId() }}" wire:model.live="run_backup"> <input type="checkbox" name="run_backup" data-livewire-component="{{ $this->getId() }}" wire:model.live="run_backup">

View file

@ -0,0 +1,22 @@
Category,Category Type,Manufacturer,Name,Notes,Model Number,Fieldset
Laptops,asset,Berge Inc,Test Model 1,,1786VM80X07,Laptops and Desktops
Laptops,asset,"Botsford, Boyle and Herzog",Test Model 2,ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae mauris viverra diam vitae quam suspendisse potenti nullam,9351IS25A51,Laptops and Desktops
Laptops,asset,Pollich LLC,Test Model 3,,9929FR08W85,Laptops and Desktops
Laptops,asset,Walker-Towne,Test Model 4,neque vestibulum eget vulputate ut ultrices vel augue vestibulum ante ipsum primis in faucibus orci luctus,9139KQ78G81,Laptops and Desktops
Laptops,asset,Berge Inc,Test Model 5,turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis nunc proin at turpis a pede,0910VB28Q61,Laptops and Desktops
Laptops,asset,"Heaney, Altenwerth and Emmerich",Test Model 6,,7375EM02N97,Laptops and Desktops
Laptops,asset,"Romaguera, Goldner and Crooks",Test Model 7,blandit non interdum in ante vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae,,Laptops and Desktops
Laptops,asset,Watsica LLC,Test Model 8,sapien urna pretium nisl ut volutpat sapien arcu sed augue aliquam erat volutpat in,,Laptops and Desktops
Laptops,asset,"Fritsch, Sauer and Conn",Test Model 9,orci luctus et ultrices posuere cubilia curae duis faucibus accumsan odio curabitur,,Laptops and Desktops
Laptops,asset,"Upton, Feil and Jast",Test Model 10,velit vivamus vel nulla eget eros elementum pellentesque quisque porta volutpat,,Laptops and Desktops
Laptops,asset,Berge Inc,Test Model 11,sed nisl nunc rhoncus dui vel sem sed sagittis nam congue risus semper porta volutpat quam pede lobortis ligula sit,,Laptops and Desktops
Laptops,asset,"Kutch, Johnson and Olson",Test Model 12,curae mauris viverra diam vitae quam suspendisse potenti nullam porttitor lacus at turpis donec posuere metus vitae ipsum aliquam non,,Laptops and Desktops
Laptops,asset,Mosciski Inc,Test Model 13,molestie hendrerit at vulputate vitae nisl aenean lectus pellentesque eget nunc donec quis orci,,Laptops and Desktops
Laptops,asset,Mosciski Inc,Test Model 14,egestas metus aenean fermentum donec ut mauris eget massa tempor convallis nulla neque libero convallis eget eleifend,,Laptops and Desktops
Laptops,asset,"Upton, Feil and Jast",Test Model 15,,,Laptops and Desktops
Laptops,asset,"Romaguera, Goldner and Crooks",Test Model 16,dui luctus rutrum nulla tellus in sagittis dui vel nisl duis ac nibh fusce,2315CN41G71,Laptops and Desktops
Laptops,asset,Abernathy-Stamm,Test Model 17,maecenas pulvinar lobortis est phasellus sit amet erat nulla tempus,6080UE59E09,Laptops and Desktops
Laptops,asset,Mosciski Inc,Test Model 18,,5505YF23M46,Laptops and Desktops
Laptops,asset,Walker-Towne,Test Model 19,,8673QP30R80,Laptops and Desktops
Mobile Phones,asset,"Heaney, Altenwerth and Emmerich",Test Model 20,nisl ut volutpat sapien arcu sed augue aliquam erat volutpat in congue etiam justo etiam pretium,9088XV67Q94,Mobile Devices
Mobile Phones,asset,Okuneva Group,Test One,quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a nibh in quis,,Mobile Devices
1 Category Category Type Manufacturer Name Notes Model Number Fieldset
2 Laptops asset Berge Inc Test Model 1 1786VM80X07 Laptops and Desktops
3 Laptops asset Botsford, Boyle and Herzog Test Model 2 ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae mauris viverra diam vitae quam suspendisse potenti nullam 9351IS25A51 Laptops and Desktops
4 Laptops asset Pollich LLC Test Model 3 9929FR08W85 Laptops and Desktops
5 Laptops asset Walker-Towne Test Model 4 neque vestibulum eget vulputate ut ultrices vel augue vestibulum ante ipsum primis in faucibus orci luctus 9139KQ78G81 Laptops and Desktops
6 Laptops asset Berge Inc Test Model 5 turpis adipiscing lorem vitae mattis nibh ligula nec sem duis aliquam convallis nunc proin at turpis a pede 0910VB28Q61 Laptops and Desktops
7 Laptops asset Heaney, Altenwerth and Emmerich Test Model 6 7375EM02N97 Laptops and Desktops
8 Laptops asset Romaguera, Goldner and Crooks Test Model 7 blandit non interdum in ante vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae Laptops and Desktops
9 Laptops asset Watsica LLC Test Model 8 sapien urna pretium nisl ut volutpat sapien arcu sed augue aliquam erat volutpat in Laptops and Desktops
10 Laptops asset Fritsch, Sauer and Conn Test Model 9 orci luctus et ultrices posuere cubilia curae duis faucibus accumsan odio curabitur Laptops and Desktops
11 Laptops asset Upton, Feil and Jast Test Model 10 velit vivamus vel nulla eget eros elementum pellentesque quisque porta volutpat Laptops and Desktops
12 Laptops asset Berge Inc Test Model 11 sed nisl nunc rhoncus dui vel sem sed sagittis nam congue risus semper porta volutpat quam pede lobortis ligula sit Laptops and Desktops
13 Laptops asset Kutch, Johnson and Olson Test Model 12 curae mauris viverra diam vitae quam suspendisse potenti nullam porttitor lacus at turpis donec posuere metus vitae ipsum aliquam non Laptops and Desktops
14 Laptops asset Mosciski Inc Test Model 13 molestie hendrerit at vulputate vitae nisl aenean lectus pellentesque eget nunc donec quis orci Laptops and Desktops
15 Laptops asset Mosciski Inc Test Model 14 egestas metus aenean fermentum donec ut mauris eget massa tempor convallis nulla neque libero convallis eget eleifend Laptops and Desktops
16 Laptops asset Upton, Feil and Jast Test Model 15 Laptops and Desktops
17 Laptops asset Romaguera, Goldner and Crooks Test Model 16 dui luctus rutrum nulla tellus in sagittis dui vel nisl duis ac nibh fusce 2315CN41G71 Laptops and Desktops
18 Laptops asset Abernathy-Stamm Test Model 17 maecenas pulvinar lobortis est phasellus sit amet erat nulla tempus 6080UE59E09 Laptops and Desktops
19 Laptops asset Mosciski Inc Test Model 18 5505YF23M46 Laptops and Desktops
20 Laptops asset Walker-Towne Test Model 19 8673QP30R80 Laptops and Desktops
21 Mobile Phones asset Heaney, Altenwerth and Emmerich Test Model 20 nisl ut volutpat sapien arcu sed augue aliquam erat volutpat in congue etiam justo etiam pretium 9088XV67Q94 Mobile Devices
22 Mobile Phones asset Okuneva Group Test One quis libero nullam sit amet turpis elementum ligula vehicula consequat morbi a ipsum integer a nibh in quis Mobile Devices