snipe-it/app/Importer/ItemImporter.php
snipe e27065fe16 Merge branch 'develop-v6-integration' into develop-v6-rc1
Signed-off-by: snipe <snipe@snipe.net>

# Conflicts:
#	.all-contributorsrc
#	README.md
#	app/Console/Commands/ResetDemoSettings.php
#	app/Helpers/Helper.php
#	app/Http/Controllers/Api/AccessoriesController.php
#	app/Http/Controllers/Api/AssetsController.php
#	app/Http/Controllers/Api/CategoriesController.php
#	app/Http/Controllers/Api/ComponentsController.php
#	app/Http/Controllers/Api/ConsumablesController.php
#	app/Http/Controllers/Api/LocationsController.php
#	app/Http/Controllers/Api/StatuslabelsController.php
#	app/Http/Controllers/Api/SuppliersController.php
#	app/Http/Controllers/AssetMaintenancesController.php
#	app/Http/Controllers/Auth/ForgotPasswordController.php
#	app/Http/Controllers/DepreciationsController.php
#	app/Http/Controllers/ReportsController.php
#	app/Http/Controllers/SettingsController.php
#	app/Http/Requests/ImageUploadRequest.php
#	app/Http/Transformers/ActionlogsTransformer.php
#	app/Http/Transformers/DepreciationsTransformer.php
#	app/Listeners/CheckoutableListener.php
#	app/Models/Accessory.php
#	app/Models/Asset.php
#	app/Models/Company.php
#	app/Models/Ldap.php
#	app/Models/User.php
#	app/Presenters/AssetPresenter.php
#	app/Presenters/CategoryPresenter.php
#	composer.json
#	composer.lock
#	config/version.php
#	database/factories/AssetModelFactory.php
#	database/migrations/2020_10_22_233743_move_accessory_checkout_note_to_join_table.php
#	database/seeds/AssetModelSeeder.php
#	package-lock.json
#	public/css/build/AdminLTE.css
#	public/css/build/app.css
#	public/css/build/overrides.css
#	public/css/dist/all.css
#	public/css/dist/bootstrap-table.css
#	public/css/dist/skins/skin-black-dark.css
#	public/css/dist/skins/skin-black-dark.min.css
#	public/css/dist/skins/skin-black.css
#	public/css/dist/skins/skin-black.min.css
#	public/css/dist/skins/skin-blue-dark.css
#	public/css/dist/skins/skin-blue-dark.min.css
#	public/css/dist/skins/skin-blue.css
#	public/css/dist/skins/skin-blue.min.css
#	public/css/dist/skins/skin-contrast.css
#	public/css/dist/skins/skin-contrast.min.css
#	public/css/dist/skins/skin-green-dark.css
#	public/css/dist/skins/skin-green-dark.min.css
#	public/css/dist/skins/skin-green.css
#	public/css/dist/skins/skin-green.min.css
#	public/css/dist/skins/skin-orange-dark.css
#	public/css/dist/skins/skin-orange-dark.min.css
#	public/css/dist/skins/skin-orange.css
#	public/css/dist/skins/skin-orange.min.css
#	public/css/dist/skins/skin-purple-dark.css
#	public/css/dist/skins/skin-purple-dark.min.css
#	public/css/dist/skins/skin-purple.css
#	public/css/dist/skins/skin-purple.min.css
#	public/css/dist/skins/skin-red-dark.css
#	public/css/dist/skins/skin-red-dark.min.css
#	public/css/dist/skins/skin-red.css
#	public/css/dist/skins/skin-red.min.css
#	public/css/dist/skins/skin-yellow-dark.css
#	public/css/dist/skins/skin-yellow-dark.min.css
#	public/css/dist/skins/skin-yellow.css
#	public/css/dist/skins/skin-yellow.min.css
#	public/js/build/app.js
#	public/js/build/vendor.js
#	public/js/dist/all.js
#	public/js/dist/bootstrap-table.js
#	public/mix-manifest.json
#	resources/assets/js/vue.js
#	resources/lang/af/validation.php
#	resources/lang/ar/admin/settings/general.php
#	resources/lang/ar/validation.php
#	resources/lang/bg/admin/settings/general.php
#	resources/lang/bg/validation.php
#	resources/lang/cs/admin/settings/general.php
#	resources/lang/cs/validation.php
#	resources/lang/cy/help.php
#	resources/lang/cy/validation.php
#	resources/lang/da/admin/settings/general.php
#	resources/lang/da/validation.php
#	resources/lang/de/admin/settings/general.php
#	resources/lang/de/validation.php
#	resources/lang/el/validation.php
#	resources/lang/en-GB/admin/settings/general.php
#	resources/lang/en-GB/validation.php
#	resources/lang/en-ID/admin/hardware/table.php
#	resources/lang/en-ID/admin/settings/general.php
#	resources/lang/en-ID/validation.php
#	resources/lang/es-CO/admin/settings/general.php
#	resources/lang/es-CO/auth/message.php
#	resources/lang/es-CO/button.php
#	resources/lang/es-CO/help.php
#	resources/lang/es-CO/validation.php
#	resources/lang/es-ES/admin/settings/general.php
#	resources/lang/es-ES/auth/message.php
#	resources/lang/es-ES/button.php
#	resources/lang/es-ES/help.php
#	resources/lang/es-ES/validation.php
#	resources/lang/es-MX/admin/settings/general.php
#	resources/lang/es-MX/validation.php
#	resources/lang/es-VE/admin/settings/general.php
#	resources/lang/es-VE/auth/message.php
#	resources/lang/es-VE/button.php
#	resources/lang/es-VE/help.php
#	resources/lang/es-VE/validation.php
#	resources/lang/et/validation.php
#	resources/lang/fa/validation.php
#	resources/lang/fi/admin/settings/general.php
#	resources/lang/fi/validation.php
#	resources/lang/fil/validation.php
#	resources/lang/fr/admin/settings/general.php
#	resources/lang/fr/validation.php
#	resources/lang/ga-IE/validation.php
#	resources/lang/he/admin/settings/general.php
#	resources/lang/he/general.php
#	resources/lang/he/validation.php
#	resources/lang/hr/validation.php
#	resources/lang/hu/validation.php
#	resources/lang/id/validation.php
#	resources/lang/is/admin/categories/general.php
#	resources/lang/is/admin/companies/message.php
#	resources/lang/is/admin/companies/table.php
#	resources/lang/is/admin/components/general.php
#	resources/lang/is/admin/components/table.php
#	resources/lang/is/admin/consumables/table.php
#	resources/lang/is/admin/depreciations/general.php
#	resources/lang/is/admin/depreciations/message.php
#	resources/lang/is/admin/hardware/form.php
#	resources/lang/is/admin/hardware/general.php
#	resources/lang/is/admin/hardware/message.php
#	resources/lang/is/admin/hardware/table.php
#	resources/lang/is/admin/kits/general.php
#	resources/lang/is/admin/licenses/form.php
#	resources/lang/is/admin/licenses/general.php
#	resources/lang/is/admin/locations/table.php
#	resources/lang/is/admin/manufacturers/table.php
#	resources/lang/is/admin/reports/message.php
#	resources/lang/is/admin/settings/general.php
#	resources/lang/is/admin/settings/message.php
#	resources/lang/is/admin/statuslabels/message.php
#	resources/lang/is/admin/suppliers/message.php
#	resources/lang/is/admin/suppliers/table.php
#	resources/lang/is/admin/users/table.php
#	resources/lang/is/mail.php
#	resources/lang/is/validation.php
#	resources/lang/it/admin/settings/general.php
#	resources/lang/it/validation.php
#	resources/lang/iu/validation.php
#	resources/lang/ja/mail.php
#	resources/lang/ja/validation.php
#	resources/lang/ko/validation.php
#	resources/lang/lt/validation.php
#	resources/lang/lv/validation.php
#	resources/lang/mi/validation.php
#	resources/lang/mk/validation.php
#	resources/lang/ml-IN/validation.php
#	resources/lang/mn/validation.php
#	resources/lang/ms/validation.php
#	resources/lang/nl/admin/settings/general.php
#	resources/lang/nl/validation.php
#	resources/lang/no/validation.php
#	resources/lang/pl/admin/settings/general.php
#	resources/lang/pl/validation.php
#	resources/lang/pt-BR/admin/settings/general.php
#	resources/lang/pt-BR/mail.php
#	resources/lang/pt-BR/validation.php
#	resources/lang/pt-PT/validation.php
#	resources/lang/ro/validation.php
#	resources/lang/ru/validation.php
#	resources/lang/sl/validation.php
#	resources/lang/sr-CS/admin/settings/general.php
#	resources/lang/sr-CS/validation.php
#	resources/lang/sv-SE/admin/settings/general.php
#	resources/lang/sv-SE/auth/message.php
#	resources/lang/sv-SE/button.php
#	resources/lang/sv-SE/mail.php
#	resources/lang/sv-SE/validation.php
#	resources/lang/ta/validation.php
#	resources/lang/th/validation.php
#	resources/lang/tl/validation.php
#	resources/lang/tr/mail.php
#	resources/lang/tr/validation.php
#	resources/lang/uk/admin/accessories/table.php
#	resources/lang/uk/admin/asset_maintenances/message.php
#	resources/lang/uk/admin/asset_maintenances/table.php
#	resources/lang/uk/validation.php
#	resources/lang/ur-PK/validation.php
#	resources/lang/vi/admin/settings/general.php
#	resources/lang/vi/validation.php
#	resources/lang/zh-CN/admin/settings/general.php
#	resources/lang/zh-CN/validation.php
#	resources/lang/zh-HK/validation.php
#	resources/lang/zh-TW/validation.php
#	resources/lang/zu/validation.php
#	resources/views/partials/bootstrap-table.blade.php
#	resources/views/partials/forms/edit/company-select.blade.php
#	routes/api.php
2021-09-21 23:46:50 -07:00

476 lines
16 KiB
PHP

<?php
namespace App\Importer;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\Company;
use App\Models\Location;
use App\Models\Manufacturer;
use App\Models\Statuslabel;
use App\Models\Supplier;
use App\Models\User;
class ItemImporter extends Importer
{
protected $item;
public function __construct($filename)
{
parent::__construct($filename);
}
protected function handle($row)
{
// Need to reset this between iterations or we'll have stale data.
$this->item = [];
$item_category = $this->findCsvMatch($row, 'category');
if ($this->shouldUpdateField($item_category)) {
$this->item['category_id'] = $this->createOrFetchCategory($item_category);
}
$item_company_name = $this->findCsvMatch($row, 'company');
if ($this->shouldUpdateField($item_company_name)) {
$this->item['company_id'] = $this->createOrFetchCompany($item_company_name);
}
$item_location = $this->findCsvMatch($row, 'location');
if ($this->shouldUpdateField($item_location)) {
$this->item['location_id'] = $this->createOrFetchLocation($item_location);
}
$item_manufacturer = $this->findCsvMatch($row, 'manufacturer');
if ($this->shouldUpdateField($item_manufacturer)) {
$this->item['manufacturer_id'] = $this->createOrFetchManufacturer($item_manufacturer);
}
$item_status_name = $this->findCsvMatch($row, 'status');
if ($this->shouldUpdateField($item_status_name)) {
$this->item['status_id'] = $this->createOrFetchStatusLabel($item_status_name);
}
$item_supplier = $this->findCsvMatch($row, 'supplier');
if ($this->shouldUpdateField($item_supplier)) {
$this->item['supplier_id'] = $this->createOrFetchSupplier($item_supplier);
}
$item_department = $this->findCsvMatch($row, 'department');
if ($this->shouldUpdateField($item_department)) {
$this->item['department_id'] = $this->createOrFetchDepartment($item_department);
}
$item_manager_first_name = $this->findCsvMatch($row, 'manage_first_name');
$item_manager_last_name = $this->findCsvMatch($row, 'manage_last_name');
if ($this->shouldUpdateField($item_manager_first_name)) {
$this->item['manager_id'] = $this->fetchManager($item_manager_first_name, $item_manager_last_name);
}
$this->item['name'] = $this->findCsvMatch($row, 'item_name');
$this->item['notes'] = $this->findCsvMatch($row, 'notes');
$this->item['order_number'] = $this->findCsvMatch($row, 'order_number');
$this->item['purchase_cost'] = $this->findCsvMatch($row, 'purchase_cost');
$this->item['purchase_date'] = null;
if ($this->findCsvMatch($row, 'purchase_date') != '') {
$this->item['purchase_date'] = date('Y-m-d 00:00:01', strtotime($this->findCsvMatch($row, 'purchase_date')));
}
$this->item['qty'] = $this->findCsvMatch($row, 'quantity');
$this->item['requestable'] = $this->findCsvMatch($row, 'requestable');
$this->item['user_id'] = $this->user_id;
$this->item['serial'] = $this->findCsvMatch($row, 'serial');
// NO need to call this method if we're running the user import.
// TODO: Merge these methods.
$this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class');
if (get_class($this) !== UserImporter::class) {
// $this->item["user"] = $this->createOrFetchUser($row);
$this->item['checkout_target'] = $this->determineCheckout($row);
}
}
/**
* Parse row to determine what (if anything) we should checkout to.
* @param array $row CSV Row being parsed
* @return SnipeModel Model to be checked out to
*/
protected function determineCheckout($row)
{
// We only support checkout-to-location for asset, so short circuit otherwise.
if (get_class($this) != AssetImporter::class) {
return $this->createOrFetchUser($row);
}
if (strtolower($this->item['checkout_class']) === 'location') {
return Location::findOrFail($this->createOrFetchLocation($this->findCsvMatch($row, 'checkout_location')));
}
return $this->createOrFetchUser($row);
}
/**
* Cleanup the $item array before storing.
* We need to remove any values that are not part of the fillable fields.
* Also, if updating, we remove any fields from the array that are empty.
*
* @author Daniel Melzter
* @since 4.0
* @param $model SnipeModel Model that's being updated.
* @param $updating boolean Should we remove blank values?
* @return array
*/
protected function sanitizeItemForStoring($model, $updating = false)
{
// Create a collection for all manipulations to come.
$item = collect($this->item);
// First Filter the item down to the model's fillable fields
$item = $item->only($model->getFillable());
// Then iterate through the item and, if we are updating, remove any blank values.
if ($updating) {
$item = $item->reject(function ($value) {
return empty($value);
});
}
return $item->toArray();
}
/**
* Convenience function for updating that strips the empty values.
* @param $model SnipeModel Model that's being updated.
* @return array
*/
protected function sanitizeItemForUpdating($model)
{
return $this->sanitizeItemForStoring($model, true);
}
/**
* Determines if a field needs updating
* Follows the following rules:
* If we are not updating, we should update the field
* If We are updating, we only update the field if it's not empty.
*
* @author Daniel Melzter
* @since 4.0
* @param $field string
* @return bool
*/
protected function shouldUpdateField($field)
{
if (empty($field)) {
return false;
}
return ! ($this->updating && empty($field));
}
/**
* Select the asset model if it exists, otherwise create it.
*
* @author Daniel Melzter
* @since 3.0
* @param array
* @param $row Row
* @return int Id of asset model created/found
* @internal param $asset_modelno string
*/
public function createOrFetchAssetModel(array $row)
{
$asset_model_name = $this->findCsvMatch($row, 'asset_model');
$asset_modelNumber = $this->findCsvMatch($row, 'model_number');
// TODO: At the moment, this means we can't update the model number if the model name stays the same.
if (! $this->shouldUpdateField($asset_model_name)) {
return;
}
if ((empty($asset_model_name)) && (! empty($asset_modelNumber))) {
$asset_model_name = $asset_modelNumber;
} elseif ((empty($asset_model_name)) && (empty($asset_modelNumber))) {
$asset_model_name = 'Unknown';
}
$editingModel = $this->updating;
$asset_model = AssetModel::where(['name' => $asset_model_name, 'model_number' => $asset_modelNumber])->first();
if ($asset_model) {
if (! $this->updating) {
$this->log('A matching model already exists, returning it.');
return $asset_model->id;
}
$this->log('Matching Model found, updating it.');
$item = $this->sanitizeItemForStoring($asset_model, $editingModel);
$item['name'] = $asset_model_name;
$item['model_number'] = $asset_modelNumber;
$asset_model->update($item);
$asset_model->save();
$this->log('Asset Model Updated');
return $asset_model->id;
}
$this->log('No Matching Model, Creating a new one');
$asset_model = new AssetModel();
$item = $this->sanitizeItemForStoring($asset_model, $editingModel);
$item['name'] = $asset_model_name;
$item['model_number'] = $asset_modelNumber;
$asset_model->fill($item);
$item = null;
if ($asset_model->save()) {
$this->log('Asset Model '.$asset_model_name.' with model number '.$asset_modelNumber.' was created');
return $asset_model->id;
}
$this->logError($asset_model, 'Asset Model "'.$asset_model_name.'"');
return null;
}
/**
* Finds a category with the same name and item type in the database, otherwise creates it
*
* @author Daniel Melzter
* @since 3.0
* @param $asset_category string
* @return int Id of category created/found
* @internal param string $item_type
*/
public function createOrFetchCategory($asset_category)
{
// Magic to transform "AssetImporter" to "asset" or similar.
$classname = class_basename(get_class($this));
$item_type = strtolower(substr($classname, 0, strpos($classname, 'Importer')));
if (empty($asset_category)) {
$asset_category = 'Unnamed Category';
}
$category = Category::where(['name' => $asset_category, 'category_type' => $item_type])->first();
if ($category) {
$this->log('A matching category: '.$asset_category.' already exists');
return $category->id;
}
$category = new Category();
$category->name = $asset_category;
$category->category_type = $item_type;
$category->user_id = $this->user_id;
if ($category->save()) {
$this->log('Category '.$asset_category.' was created');
return $category->id;
}
$this->logError($category, 'Category "'.$asset_category.'"');
return null;
}
/**
* Fetch an existing company, or create new if it doesn't exist
*
* @author Daniel Melzter
* @since 3.0
* @param $asset_company_name string
* @return int id of company created/found
*/
public function createOrFetchCompany($asset_company_name)
{
$company = Company::where(['name' => $asset_company_name])->first();
if ($company) {
$this->log('A matching Company '.$asset_company_name.' already exists');
return $company->id;
}
$company = new Company();
$company->name = $asset_company_name;
if ($company->save()) {
$this->log('Company '.$asset_company_name.' was created');
return $company->id;
}
$this->logError($company, 'Company');
return null;
}
/**
* Fetch an existing manager
*
* @author A. Gianotto
* @since 4.6.5
* @param $user_manager string
* @return int id of company created/found
*/
public function fetchManager($user_manager_first_name, $user_manager_last_name)
{
$manager = User::where('first_name', '=', $user_manager_first_name)
->where('last_name', '=', $user_manager_last_name)->first();
if ($manager) {
$this->log('A matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' already exists');
return $manager->id;
}
$this->log('No matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' found. If their user account is being created through this import, you should re-process this file again. ');
return null;
}
/**
* Fetch the existing status label or create new if it doesn't exist.
*
* @author Daniel Melzter
* @since 3.0
* @param string $asset_statuslabel_name
* @return Statuslabel|null
*/
public function createOrFetchStatusLabel($asset_statuslabel_name)
{
if (empty($asset_statuslabel_name)) {
return null;
}
$status = Statuslabel::where(['name' => $asset_statuslabel_name])->first();
if ($status) {
$this->log('A matching Status '.$asset_statuslabel_name.' already exists');
return $status->id;
}
$this->log('Creating a new status');
$status = new Statuslabel();
$status->name = $asset_statuslabel_name;
$status->deployable = 1;
$status->pending = 0;
$status->archived = 0;
if ($status->save()) {
$this->log('Status '.$asset_statuslabel_name.' was created');
return $status->id;
}
$this->logError($status, 'Status "'.$asset_statuslabel_name.'"');
return null;
}
/**
* Finds a manufacturer with matching name, otherwise create it.
*
* @author Daniel Melzter
* @since 3.0
* @param $item_manufacturer string
* @return Manufacturer
*/
public function createOrFetchManufacturer($item_manufacturer)
{
if (empty($item_manufacturer)) {
$item_manufacturer = 'Unknown';
}
$manufacturer = Manufacturer::where(['name'=> $item_manufacturer])->first();
if ($manufacturer) {
$this->log('Manufacturer '.$item_manufacturer.' already exists');
return $manufacturer->id;
}
//Otherwise create a manufacturer.
$manufacturer = new Manufacturer();
$manufacturer->name = $item_manufacturer;
$manufacturer->user_id = $this->user_id;
if ($manufacturer->save()) {
$this->log('Manufacturer '.$manufacturer->name.' was created');
return $manufacturer->id;
}
$this->logError($manufacturer, 'Manufacturer "'.$manufacturer->name.'"');
return null;
}
/**
* Checks the DB to see if a location with the same name exists, otherwise create it
*
* @author Daniel Melzter
* @since 3.0
* @param $asset_location string
* @return Location|null
*/
public function createOrFetchLocation($asset_location)
{
if (empty($asset_location)) {
$this->log('No location given, so none created.');
return null;
}
$location = Location::where(['name' => $asset_location])->first();
if ($location) {
$this->log('Location '.$asset_location.' already exists');
return $location->id;
}
// No matching locations in the collection, create a new one.
$location = new Location();
$location->name = $asset_location;
$location->address = '';
$location->city = '';
$location->state = '';
$location->country = '';
$location->user_id = $this->user_id;
if ($location->save()) {
$this->log('Location '.$asset_location.' was created');
return $location->id;
}
$this->logError($location, 'Location');
return null;
}
/**
* Fetch an existing supplier or create new if it doesn't exist
*
* @author Daniel Melzter
* @since 3.0
* @param $row array
* @return Supplier
*/
public function createOrFetchSupplier($item_supplier)
{
if (empty($item_supplier)) {
$item_supplier = 'Unknown';
}
$supplier = Supplier::where(['name' => $item_supplier])->first();
if ($supplier) {
$this->log('Supplier '.$item_supplier.' already exists');
return $supplier->id;
}
$supplier = new Supplier();
$supplier->name = $item_supplier;
$supplier->user_id = $this->user_id;
if ($supplier->save()) {
$this->log('Supplier '.$item_supplier.' was created');
return $supplier->id;
}
$this->logError($supplier, 'Supplier');
return null;
}
}