Skip to content

A free open source IT asset/license management system

Importer improvements

snipebc3cde5e971e
diff --git a/app/Http/Controllers/Api/ImportController.php b/app/Http/Controllers/Api/ImportController.php
index a283c1cbc2..e57b736432 100644
--- a/app/Http/Controllers/Api/ImportController.php
+++ b/app/Http/Controllers/Api/ImportController.php
@@ -294,17 +294,22 @@ class ImportController extends Controller
break;
}
+ $tally = $request->getTally();
+ // Payload only carries the tally when at least one importer for this
+ // type has been wired up to record it. Un-instrumented importers
+ // leave every count at zero; suppress the block in that case so we
+ // don't surface a misleading all-zero summary in the wizard.
+ $tallyPayload = array_sum($tally) > 0 ? ['tally' => $tally] : null;
+
if ($errors) { // Failure
- return response()->json(Helper::formatStandardApiResponse('import-errors', null, $errors), 500);
+ return response()->json(Helper::formatStandardApiResponse('import-errors', $tallyPayload, $errors), 500);
}
// Flash message before the redirect
Session::flash('success', trans('admin/hardware/message.import.success'));
- if (auth()->user()->can('view', $model_perms)) {
- return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route($redirectTo)]));
- }
+ $redirect_url = auth()->user()->can('view', $model_perms) ? route($redirectTo) : route('imports.index');
- return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route('imports.index')]));
+ return response()->json(Helper::formatStandardApiResponse('success', $tallyPayload, ['redirect_url' => $redirect_url]));
}
/**
diff --git a/app/Http/Requests/ItemImportRequest.php b/app/Http/Requests/ItemImportRequest.php
index f18f9b8a78..364313b961 100644
--- a/app/Http/Requests/ItemImportRequest.php
+++ b/app/Http/Requests/ItemImportRequest.php
@@ -86,10 +86,16 @@ class ItemImportRequest extends FormRequest
$limit = $this->filled('limit') ? (int) $this->input('limit') : null;
$importer->import($offset, $limit);
+ $this->tally = $importer->getTally();
return $this->errors;
}
+ public function getTally(): array
+ {
+ return $this->tally ?? ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 0];
+ }
+
public function log($string)
{
Log::Info($string);
@@ -106,4 +112,6 @@ class ItemImportRequest extends FormRequest
}
private $errors;
+
+ private array $tally;
}
diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php
index a74fa5e355..28fffb1b08 100644
--- a/app/Importer/AccessoryImporter.php
+++ b/app/Importer/AccessoryImporter.php
@@ -15,10 +15,81 @@ class AccessoryImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row); // TODO: Change the autogenerated stub
+ // AccessoryImporter deliberately does NOT call parent::handle(). See
+ // LicenseImporter / AssetImporter for the same pattern: absent CSV
+ // columns are left out of $this->item so update mode preserves the
+ // DB value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ // Shared lookup fields. Present-and-empty clears the FK; absent
+ // preserves it; present-and-set resolves and stores the id.
+ // department + manager kept as side-effect calls even though they
+ // are not in Accessory's fillable, so createOrFetchUser can find
+ // an auto-created department when it mints a checkout-target user.
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['company_id', 'company', fn ($v) => $this->createOrFetchCompany($v)],
+ ['location_id', 'location', fn ($v) => $this->createOrFetchLocation($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['supplier_id', 'supplier', fn ($v) => $this->createOrFetchSupplier($v)],
+ ['department_id', 'department', fn ($v) => $this->createOrFetchDepartment($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ if ($this->csvRowHas($row, 'manager_first_name')) {
+ $first = $this->findCsvMatch($row, 'manager_first_name');
+ $last = $this->findCsvMatch($row, 'manager_last_name');
+ $this->item['manager_id'] = ($first !== '') ? $this->fetchManager($first, $last) : null;
+ }
+
+ $this->setItemFromCsvIfPresent($row, 'name', 'item_name');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'order_number');
+ $this->setItemFromCsvIfPresent($row, 'purchase_cost');
+ $this->setItemFromCsvIfPresent($row, 'model_number');
+ $this->setItemFromCsvIfPresent($row, 'min_amt');
+ $this->setItemFromCsvIfPresent($row, 'qty', 'quantity');
+ $this->setItemFromCsvIfPresent($row, 'requestable');
+
+ if ($this->csvRowHas($row, 'image')) {
+ $raw = $this->findCsvMatch($row, 'image');
+ $this->item['image'] = ($raw !== '') ? basename($raw) : null;
+ }
+
+ if ($this->csvRowHas($row, 'purchase_date')) {
+ $raw = $this->findCsvMatch($row, 'purchase_date');
+ if ($raw !== '') {
+ $this->item['purchase_date'] = $raw;
+ $this->item['purchase_date'] = $this->parseOrNullDate('purchase_date');
+ } else {
+ $this->item['purchase_date'] = null;
+ }
+ }
+
+ // Internal signals used by the checkout logic below; neither is
+ // fillable on Accessory so sanitize's fillable filter drops them.
+ $this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class');
+ $this->item['checkout_target'] = $this->determineCheckout($row);
+ $this->item['created_by'] = $this->created_by;
+
$this->createAccessoryIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create an accessory if a duplicate does not exist
*
@@ -28,10 +99,12 @@ class AccessoryImporter extends ItemImporter
*/
public function createAccessoryIfNotExists($row)
{
- $accessory = Accessory::where('name', $this->item['name'])->first();
+ $name = $this->item['name'] ?? '';
+ $accessory = Accessory::where('name', $name)->first();
if ($accessory) {
if (! $this->updating) {
- $this->log('A matching Accessory '.$this->item['name'].' already exists. ');
+ $this->log('A matching Accessory '.$name.' already exists. ');
+ $this->recordSkipped();
$this->maybeCheckoutAccessory($accessory);
@@ -39,10 +112,10 @@ class AccessoryImporter extends ItemImporter
}
$this->log('Updating Accessory');
- $this->item['model_number'] = trim($this->findCsvMatch($row, 'model_number'));
$accessory->update($this->sanitizeItemForUpdating($accessory));
// update() already saves the model, no need to call save() again while Model::unguard() is active
$accessory->setImported(true);
+ $this->recordUpdated();
$this->maybeCheckoutAccessory($accessory);
@@ -51,19 +124,19 @@ class AccessoryImporter extends ItemImporter
$this->log('No Matching Accessory, Creating a new one');
$accessory = new Accessory;
$accessory->created_by = $this->created_by;
- $this->item['model_number'] = $this->findCsvMatch($row, 'model_number');
- $this->item['min_amt'] = $this->findCsvMatch($row, 'min_amt');
$accessory->fill($this->sanitizeItemForStoring($accessory));
// This sets an attribute on the Loggable trait for the action log
$accessory->setImported(true);
if ($accessory->save()) {
- $this->log('Accessory '.$this->item['name'].' was created');
+ $this->log('Accessory '.$name.' was created');
+ $this->recordCreated();
$this->maybeCheckoutAccessory($accessory);
return;
}
+ $this->recordErrored();
$this->logError($accessory, 'Accessory');
}
diff --git a/app/Importer/AssetHistoryImporter.php b/app/Importer/AssetHistoryImporter.php
index 5b04112d11..1b7e47dcaa 100644
--- a/app/Importer/AssetHistoryImporter.php
+++ b/app/Importer/AssetHistoryImporter.php
@@ -90,6 +90,7 @@ class AssetHistoryImporter extends Importer
if (empty($asset_tag)) {
$this->log('Row is missing an asset tag - skipping');
+ $this->recordSkipped();
$this->addRowError(
trans('admin/hardware/message.import.history.missing_asset_tag_identity'),
trans('general.import-history'),
@@ -104,6 +105,7 @@ class AssetHistoryImporter extends Importer
if (! $asset) {
$this->log('Asset '.$asset_tag.' does not exist - skipping');
+ $this->recordSkipped();
$this->addRowError(
trans('general.asset').' '.$asset_tag,
trans('general.import-history'),
@@ -132,6 +134,7 @@ class AssetHistoryImporter extends Importer
if (! $user) {
$this->log('User "'.$name.'" does not exist so no checkin log was created for asset '.$asset_tag);
+ $this->recordSkipped();
$this->addRowError(
trans('general.asset').' '.$asset_tag,
trans('general.import-history'),
@@ -178,7 +181,9 @@ class AssetHistoryImporter extends Importer
if ($asset->save()) {
$this->log('Asset history imported for '.$asset_tag.' -> '.$user->username.' at '.$checkout_date);
+ $this->recordCreated();
} else {
+ $this->recordErrored();
$this->logError($asset, 'asset_tag');
}
}
diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php
index 2a1f005474..530abc9b5b 100644
--- a/app/Importer/AssetImporter.php
+++ b/app/Importer/AssetImporter.php
@@ -37,9 +37,124 @@ class AssetImporter extends ItemImporter
protected function handle($row)
{
- // ItemImporter handles the general fetching.
- parent::handle($row);
+ // AssetImporter deliberately does NOT call parent::handle(). The
+ // parent unconditionally assigns $this->item entries for every
+ // shared field, which conflates "column absent from CSV" with
+ // "column present but empty" and prevents empty CSV cells from
+ // clearing existing DB values on update. AssetImporter builds
+ // $this->item exclusively via setItemFromCsvIfPresent so absent
+ // columns never enter the update payload (preserving DB values)
+ // and present-but-empty columns land as null (clearing DB values).
+ // See sanitizeItemForStoring override below for the matching
+ // pass-through sanitize.
+ $this->item = [];
+
+ // Shared lookup fields. Present-and-empty clears the FK; absent
+ // preserves it; present-and-set resolves and stores the id. Some
+ // of these (category, manufacturer, department, manager) are not
+ // in Asset's fillable and get dropped by sanitize before the DB
+ // write, but the resolver calls still have important side effects
+ // like auto-creating the referenced record so downstream lookups
+ // (createOrFetchAssetModel needs the category, createOrFetchUser
+ // needs the department) can find them.
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['company_id', 'company', fn ($v) => $this->createOrFetchCompany($v)],
+ ['location_id', 'location', fn ($v) => $this->createOrFetchLocation($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['status_id', 'status', fn ($v) => $this->createOrFetchStatusLabel($v)],
+ ['supplier_id', 'supplier', fn ($v) => $this->createOrFetchSupplier($v)],
+ ['department_id', 'department', fn ($v) => $this->createOrFetchDepartment($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ // Manager needs both first + last name; treat "first name column
+ // present" as the presence signal for the whole lookup. Not in
+ // Asset's fillable, but createOrFetchUser reads $this->item['manager_id']
+ // when auto-creating a checkout-target user.
+ if ($this->csvRowHas($row, 'manager_first_name')) {
+ $first = $this->findCsvMatch($row, 'manager_first_name');
+ $last = $this->findCsvMatch($row, 'manager_last_name');
+ $this->item['manager_id'] = ($first !== '') ? $this->fetchManager($first, $last) : null;
+ }
+
+ // Straight CSV-to-item assignments for the Asset fillable set. Note
+ // asset_notes not notes: assets use a different CSV column name to
+ // avoid the ItemImporter's shared 'notes' handling.
+ $this->setItemFromCsvIfPresent($row, 'name', 'item_name');
+ $this->setItemFromCsvIfPresent($row, 'notes', 'asset_notes');
+ $this->setItemFromCsvIfPresent($row, 'order_number');
+ $this->setItemFromCsvIfPresent($row, 'purchase_cost');
+ $this->setItemFromCsvIfPresent($row, 'serial');
+
+ if ($this->csvRowHas($row, 'image')) {
+ $raw = $this->findCsvMatch($row, 'image');
+ $this->item['image'] = ($raw !== '') ? basename($raw) : null;
+ }
+
+ if ($this->csvRowHas($row, 'warranty_months')) {
+ $raw = $this->findCsvMatch($row, 'warranty_months');
+ $this->item['warranty_months'] = ($raw !== '') ? intval($raw) : null;
+ }
+
+ // Boolean flags: present-and-empty means clear (0). Absent means
+ // don't touch on update. On create the default fallback below
+ // fills in 0 for both columns if the CSV was absent.
+ foreach (['requestable', 'byod'] as $flag) {
+ if ($this->csvRowHas($row, $flag)) {
+ $raw = $this->findCsvMatch($row, $flag);
+ $this->item[$flag] = ($raw !== '') ? (($this->fetchHumanBoolean($raw) == 1) ? '1' : 0) : 0;
+ }
+ }
+ // Model lookup. asset_model absent from CSV means "don't touch";
+ // if present but resolves to nothing, leave model_id unset so the
+ // required-field validator catches it.
+ if ($this->csvRowHas($row, 'asset_model')) {
+ $modelId = $this->createOrFetchAssetModel($row);
+ if ($modelId !== null) {
+ $this->item['model_id'] = $modelId;
+ }
+ }
+
+ // Dates: raw value stored so parseOrNullDate can read it, then the
+ // parsed date replaces it. Empty CSV cell becomes null (clearing
+ // the DB field on update). Datetime format on the checkout/checkin
+ // fields preserves any time portion in the CSV.
+ foreach ([
+ 'purchase_date' => 'date',
+ 'last_checkin' => 'datetime',
+ 'last_checkout' => 'datetime',
+ 'expected_checkin' => 'datetime',
+ 'last_audit_date' => 'date',
+ 'next_audit_date' => 'date',
+ 'asset_eol_date' => 'date',
+ ] as $dateField => $format) {
+ if ($this->csvRowHas($row, $dateField)) {
+ $raw = $this->findCsvMatch($row, $dateField);
+ if ($raw !== '') {
+ $this->item[$dateField] = $raw;
+ $this->item[$dateField] = $this->parseOrNullDate($dateField, $format);
+ } else {
+ $this->item[$dateField] = null;
+ }
+ }
+ }
+
+ // Internal signals used by the checkout logic below. Neither is
+ // fillable on Asset so sanitize's fillable filter always drops
+ // them before the DB write.
+ $this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class');
+ $this->item['checkout_target'] = $this->determineCheckout($row);
+ $this->item['created_by'] = $this->created_by;
+
+ // Custom fields keep their existing logic. Only populated when the
+ // matching CSV column is present in the row; unchanged from the
+ // pre-refactor behavior.
if ($this->customFields) {
foreach ($this->customFields as $customField) {
$customFieldValue = $this->array_smart_custom_field_fetch($row, $customField);
@@ -62,6 +177,17 @@ class AssetImporter extends ItemImporter
$this->createAssetIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. AssetImporter
+ * populates $this->item exclusively from CSV columns that were present in
+ * the row, so an empty value here is an explicit intent to clear the DB
+ * field on update. See handle() above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create the asset if it does not exist.
*
@@ -103,52 +229,30 @@ class AssetImporter extends ItemImporter
$this->log('No Matching Asset, Creating a new one');
$asset = new Asset;
// created_by is not in Asset's $fillable, so the value that
- // ItemImporter::handle() puts on $this->item is stripped by
- // sanitizeItemForStoring() before it reaches the model. Set
- // it directly. Use $this->created_by (the property set by
- // setCreatedBy() from both ItemImportRequest and
- // ObjectImportCommand) rather than auth()->id() so CLI-run
+ // handle() puts on $this->item is stripped by sanitizeItemForStoring()
+ // before it reaches the model. Set it directly. Use $this->created_by
+ // (the property set by setCreatedBy() from both ItemImportRequest
+ // and ObjectImportCommand) rather than auth()->id() so CLI-run
// imports get the --user_id option value instead of null.
$asset->created_by = $this->created_by;
}
- // If no status ID is found
- if (! array_key_exists('status_id', $this->item) && ! $editingAsset) {
- $this->log('No status ID field found, defaulting to first deployable status label.');
- $this->item['status_id'] = $this->defaultStatusLabelId;
- }
-
- $this->item['notes'] = trim($this->findCsvMatch($row, 'asset_notes'));
- $this->item['image'] = basename(trim($this->findCsvMatch($row, 'image')));
-
- /**
- * Boolean fields need special handling. On create, a missing or blank value
- * defaults to 0. On update, only touch the flag when the CSV actually provides
- * a value — otherwise a file without the column would silently reset the flag
- * on every updated asset. The coerced value is also assigned directly to the
- * model because sanitizeItemForUpdating() strips falsy values, which would
- * make it impossible to explicitly clear a flag in update mode.
- */
- $requestable = trim((string) $this->findCsvMatch($row, 'requestable'));
- if ((! $this->updating) || ($requestable !== '')) {
- $this->item['requestable'] = ($this->fetchHumanBoolean($requestable) == 1) ? '1' : 0;
- $asset->requestable = $this->item['requestable'];
- }
-
- $byod = trim((string) $this->findCsvMatch($row, 'byod'));
- if ((! $this->updating) || ($byod !== '')) {
- $this->item['byod'] = ($this->fetchHumanBoolean($byod) == 1) ? '1' : 0;
- $asset->byod = $this->item['byod'];
+ // On create: default requestable/byod/status_id if the CSV did not
+ // include those columns. On update: leave them unset in $this->item
+ // so absent columns preserve existing values.
+ if (! $editingAsset) {
+ if (! array_key_exists('requestable', $this->item)) {
+ $this->item['requestable'] = 0;
+ }
+ if (! array_key_exists('byod', $this->item)) {
+ $this->item['byod'] = 0;
+ }
+ if (! array_key_exists('status_id', $this->item)) {
+ $this->log('No status ID field found, defaulting to first deployable status label.');
+ $this->item['status_id'] = $this->defaultStatusLabelId;
+ }
}
- $this->item['warranty_months'] = intval(trim($this->findCsvMatch($row, 'warranty_months')));
- $this->item['model_id'] = $this->createOrFetchAssetModel($row);
- $this->item['last_checkin'] = trim($this->findCsvMatch($row, 'last_checkin'));
- $this->item['last_checkout'] = trim($this->findCsvMatch($row, 'last_checkout'));
- $this->item['expected_checkin'] = trim($this->findCsvMatch($row, 'expected_checkin'));
- $this->item['last_audit_date'] = trim($this->findCsvMatch($row, 'last_audit_date'));
- $this->item['next_audit_date'] = trim($this->findCsvMatch($row, 'next_audit_date'));
- $this->item['asset_eol_date'] = trim($this->findCsvMatch($row, 'asset_eol_date'));
$this->item['asset_tag'] = $asset_tag;
// We need to save the user if it exists so that we can checkout to user later.
@@ -166,42 +270,16 @@ class AssetImporter extends ItemImporter
$item['rtd_location_id'] = $this->item['location_id'];
}
- /**
- * We use this to backdate the checkin action further down
- */
+ // Backdate helpers for the checkin/checkout events below.
$checkin_date = date('Y-m-d H:i:s');
- if ($this->item['last_checkin'] != '') {
- $item['last_checkin'] = $this->parseOrNullDate('last_checkin', 'datetime');
- $checkout_date = $this->item['last_checkin'];
+ if (! empty($this->item['last_checkin'])) {
+ $checkin_date = $this->item['last_checkin'];
}
-
- /**
- * We use this to backdate the checkout action further down
- */
$checkout_date = date('Y-m-d H:i:s');
- if ($this->item['last_checkout'] != '') {
- $item['last_checkout'] = $this->parseOrNullDate('last_checkout', 'datetime');
+ if (! empty($this->item['last_checkout'])) {
$checkout_date = $this->item['last_checkout'];
}
- if ($this->item['expected_checkin'] != '') {
- // datetime format preserves any time portion in the CSV. Date-only
- // values still parse fine and land as 00:00:00.
- $item['expected_checkin'] = $this->parseOrNullDate('expected_checkin', 'datetime');
- }
-
- if ($this->item['last_audit_date'] != '') {
- $item['last_audit_date'] = $this->parseOrNullDate('last_audit_date');
- }
-
- if ($this->item['next_audit_date'] != '') {
- $item['next_audit_date'] = $this->parseOrNullDate('next_audit_date');
- }
-
- if ($this->item['asset_eol_date'] != '') {
- $item['asset_eol_date'] = $this->parseOrNullDate('asset_eol_date');
- }
-
if ($editingAsset) {
$asset->update($item);
$asset->setImported(true);
@@ -235,11 +313,17 @@ class AssetImporter extends ItemImporter
if ($success) {
- $this->log('Asset '.$this->item['name'].' with serial number '.$this->item['serial'].' created or updated');
+ $name = $this->item['name'] ?? '';
+ $serial = $this->item['serial'] ?? '';
+ $this->log('Asset '.$name.' with serial number '.$serial.' created or updated');
+
+ if ($editingAsset) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
// If we have a target to checkout to, lets do so.
- // -- created_by is a property of the abstract class Importer, which this class inherits from and it's set by
- // -- the class that needs to use it (command importer or GUI importer inside the project).
if (isset($target) && ($target !== false)) {
$asset = $asset->fresh();
@@ -266,6 +350,8 @@ class AssetImporter extends ItemImporter
return;
}
- $this->logError($asset, 'Asset "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $name = $this->item['name'] ?? '';
+ $this->logError($asset, 'Asset "'.$name.'"');
}
}
diff --git a/app/Importer/AssetModelImporter.php b/app/Importer/AssetModelImporter.php
index 7344905b51..22c1c5469d 100644
--- a/app/Importer/AssetModelImporter.php
+++ b/app/Importer/AssetModelImporter.php
@@ -24,10 +24,56 @@ class AssetModelImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // AssetModelImporter deliberately does NOT call parent::handle(). See
+ // the other subclass migrations for the same pattern: absent CSV
+ // columns stay out of $this->item so update mode preserves the DB
+ // value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ $this->setItemFromCsvIfPresent($row, 'name');
+ $this->setItemFromCsvIfPresent($row, 'model_number');
+ $this->setItemFromCsvIfPresent($row, 'min_amt');
+ $this->setItemFromCsvIfPresent($row, 'eol');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+
+ // Lookup fields resolve a name to an id. Present-and-empty clears
+ // the FK; absent preserves it. category_id is required per model
+ // validation; clearing it will surface a clear validation error.
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['depreciation_id', 'depreciation', fn ($v) => $this->fetchDepreciation($v)],
+ ['fieldset_id', 'fieldset', fn ($v) => $this->createOrFetchCustomFieldset($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ // Boolean flags. Present-empty maps to 0; present-with-value uses
+ // fetchHumanBoolean; absent leaves the DB value alone on update.
+ foreach (['requestable', 'require_serial'] as $flag) {
+ if ($this->csvRowHas($row, $flag)) {
+ $raw = $this->findCsvMatch($row, $flag);
+ $this->item[$flag] = ($this->fetchHumanBoolean($raw) == 1) ? 1 : 0;
+ }
+ }
+
$this->createAssetModelIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a model if a duplicate does not exist.
*
@@ -41,6 +87,8 @@ class AssetModelImporter extends ItemImporter
{
$editingAssetModel = false;
+ $name = $this->item['name'] ?? '';
+ $modelNumber = $this->item['model_number'] ?? '';
/**
* This part gets a little confusing, since folks might be importing multiple models with the same name and different model numbers for the first time
@@ -49,8 +97,8 @@ class AssetModelImporter extends ItemImporter
// They are not trying to update existing models, so we'll check for duplicates with model name *and* number
if (! $this->updating) {
- $this->log('Finding model by name and model number: '.$this->findCsvMatch($row, 'name').' / '.$this->findCsvMatch($row, 'model_number'));
- $assetModel = AssetModel::where('name', '=', $this->findCsvMatch($row, 'name'))->where('model_number', '=', $this->findCsvMatch($row, 'model_number'))->first();
+ $this->log('Finding model by name and model number: '.$name.' / '.$modelNumber);
+ $assetModel = AssetModel::where('name', '=', $name)->where('model_number', '=', $modelNumber)->first();
} else {
if ($this->findCsvMatch($row, 'id') != '') {
@@ -58,14 +106,15 @@ class AssetModelImporter extends ItemImporter
$this->log('Finding model by ID: '.$this->findCsvMatch($row, 'id'));
$assetModel = AssetModel::find($this->findCsvMatch($row, 'id'));
} else {
- $this->log('Finding model by name: '.$this->findCsvMatch($row, 'name'));
- $assetModel = AssetModel::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
+ $this->log('Finding model by name: '.$name);
+ $assetModel = AssetModel::where('name', '=', $name)->first();
}
}
if ($assetModel) {
if (! $this->updating) {
- $this->log('A matching Model '.$this->item['name'].' already exists and we are not updating. Skipping.');
+ $this->log('A matching Model '.$name.' already exists and we are not updating. Skipping.');
+ $this->recordSkipped();
return;
}
@@ -77,42 +126,6 @@ class AssetModelImporter extends ItemImporter
$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['eol'] = trim($this->findCsvMatch($row, 'eol'));
- $this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
- $this->item['fieldset'] = trim($this->findCsvMatch($row, 'fieldset'));
- $this->item['depreciation'] = trim($this->findCsvMatch($row, 'depreciation'));
- $this->item['requestable'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'requestable'))) == 1) ? 1 : 0;
- $this->item['require_serial'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'require_serial'))) == 1) ? 1 : 0;
-
- if (! empty($this->item['category'])) {
- if ($category = $this->createOrFetchCategory($this->item['category'])) {
- $this->item['category_id'] = $category;
- }
- }
- if (! empty($this->item['manufacturer'])) {
- if ($manufacturer = $this->createOrFetchManufacturer($this->item['manufacturer'])) {
- $this->item['manufacturer_id'] = $manufacturer;
- }
- }
-
- if (! empty($this->item['depreciation'])) {
- if ($depreciation = $this->fetchDepreciation($this->item['depreciation'])) {
- $this->item['depreciation_id'] = $depreciation;
- }
- }
-
- if (! empty($this->item['fieldset'])) {
- if ($fieldset = $this->createOrFetchCustomFieldset($this->item['fieldset'])) {
- $this->item['fieldset_id'] = $fieldset;
- }
- }
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
@@ -127,10 +140,16 @@ class AssetModelImporter extends ItemImporter
if ($assetModel->save()) {
$this->log('AssetModel '.$assetModel->name.' created or updated from CSV import');
+ if ($editingAssetModel) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
return $assetModel;
} else {
+ $this->recordErrored();
$this->log($assetModel->getErrors()->first());
$this->addErrorToBag($assetModel, $assetModel->getErrors()->keys()[0], $assetModel->getErrors()->first());
diff --git a/app/Importer/CategoryImporter.php b/app/Importer/CategoryImporter.php
index f2695017e3..d3f3bc91eb 100644
--- a/app/Importer/CategoryImporter.php
+++ b/app/Importer/CategoryImporter.php
@@ -22,10 +22,48 @@ class CategoryImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // CategoryImporter deliberately does NOT call parent::handle(). See
+ // the other subclass migrations for the same pattern: absent CSV
+ // columns stay out of $this->item so update mode preserves the DB
+ // value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ $this->setItemFromCsvIfPresent($row, 'name');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'eula_text');
+ $this->setItemFromCsvIfPresent($row, 'tag_color');
+
+ // category_type is required-in-list-of-5 validation. Lowercase it so
+ // "Asset" from a human-authored CSV lands as "asset". Present-empty
+ // stays as null (which will fail validation with a clear message).
+ if ($this->csvRowHas($row, 'category_type')) {
+ $raw = $this->findCsvMatch($row, 'category_type');
+ $this->item['category_type'] = ($raw !== '') ? strtolower($raw) : null;
+ }
+
+ // Boolean flags. Present-empty maps to 0; present-with-value uses
+ // fetchHumanBoolean; absent leaves the DB value alone on update.
+ foreach (['use_default_eula', 'require_acceptance', 'checkin_email'] as $flag) {
+ if ($this->csvRowHas($row, $flag)) {
+ $raw = $this->findCsvMatch($row, $flag);
+ $this->item[$flag] = ($this->fetchHumanBoolean($raw) == 1) ? 1 : 0;
+ }
+ }
+
$this->createCategoryIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a category if a duplicate does not exist.
*
@@ -37,10 +75,10 @@ class CategoryImporter extends ItemImporter
*/
public function createCategoryIfNotExists(array $row)
{
-
$editingCategory = false;
+ $name = trim($this->item['name'] ?? '');
- $category = Category::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
+ $category = Category::where('name', '=', $name)->first();
if ($this->findCsvMatch($row, 'id') != '') {
// Override category if an ID was given
@@ -50,7 +88,8 @@ class CategoryImporter extends ItemImporter
if ($category) {
if (! $this->updating) {
- $this->log('A matching Category '.$this->item['name'].' already exists');
+ $this->log('A matching Category '.$name.' already exists');
+ $this->recordSkipped();
return;
}
@@ -63,16 +102,6 @@ class CategoryImporter extends ItemImporter
$category->created_by = $this->created_by;
}
- // Pull the records from the CSV to determine their values
- $this->item['name'] = trim($this->findCsvMatch($row, 'name'));
- $this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
- $this->item['eula_text'] = trim($this->findCsvMatch($row, 'eula_text'));
- $this->item['category_type'] = trim(strtolower($this->findCsvMatch($row, 'category_type')));
- $this->item['use_default_eula'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'use_default_eula'))) == 1) ? 1 : 0;
- $this->item['require_acceptance'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'require_acceptance'))) == 1) ? 1 : 0;
- $this->item['checkin_email'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'checkin_email'))) == 1) ? 1 : 0;
- $this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
@@ -86,12 +115,18 @@ class CategoryImporter extends ItemImporter
if ($category->save()) {
$this->log('Category '.$category->name.' created or updated from CSV import');
+ if ($editingCategory) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
return $category;
} else {
Log::debug($category->getErrors());
- $this->logError($category, 'Category "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $this->logError($category, 'Category "'.$name.'"');
return $category->errors;
}
diff --git a/app/Importer/ComponentImporter.php b/app/Importer/ComponentImporter.php
index 22573ecd21..64ef9260db 100644
--- a/app/Importer/ComponentImporter.php
+++ b/app/Importer/ComponentImporter.php
@@ -14,10 +14,77 @@ class ComponentImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // ComponentImporter deliberately does NOT call parent::handle(). See
+ // LicenseImporter / AssetImporter / AccessoryImporter / ConsumableImporter
+ // for the same pattern: absent CSV columns stay out of $this->item so
+ // update mode preserves the DB value, and present-but-empty cells land
+ // as null so update mode clears the DB value. The base sanitize's
+ // reject-empty pass is suppressed via the sanitizeItemForStoring
+ // override below.
+ $this->item = [];
+
+ // Shared lookup fields. Present-and-empty clears the FK; absent
+ // preserves it; present-and-set resolves and stores the id.
+ // department + manager kept as side-effect calls even though they
+ // are not in Component's fillable, in case a future subclass hook
+ // starts using them (parity with the other importers).
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['company_id', 'company', fn ($v) => $this->createOrFetchCompany($v)],
+ ['location_id', 'location', fn ($v) => $this->createOrFetchLocation($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['supplier_id', 'supplier', fn ($v) => $this->createOrFetchSupplier($v)],
+ ['department_id', 'department', fn ($v) => $this->createOrFetchDepartment($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ if ($this->csvRowHas($row, 'manager_first_name')) {
+ $first = $this->findCsvMatch($row, 'manager_first_name');
+ $last = $this->findCsvMatch($row, 'manager_last_name');
+ $this->item['manager_id'] = ($first !== '') ? $this->fetchManager($first, $last) : null;
+ }
+
+ $this->setItemFromCsvIfPresent($row, 'name', 'item_name');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'order_number');
+ $this->setItemFromCsvIfPresent($row, 'purchase_cost');
+ $this->setItemFromCsvIfPresent($row, 'model_number');
+ $this->setItemFromCsvIfPresent($row, 'min_amt');
+ $this->setItemFromCsvIfPresent($row, 'qty', 'quantity');
+ $this->setItemFromCsvIfPresent($row, 'serial');
+
+ // asset_tag is not in Component's fillable but is used by the
+ // checkout-to-asset path in createComponentIfNotExists.
+ $this->setItemFromCsvIfPresent($row, 'asset_tag');
+
+ if ($this->csvRowHas($row, 'purchase_date')) {
+ $raw = $this->findCsvMatch($row, 'purchase_date');
+ if ($raw !== '') {
+ $this->item['purchase_date'] = $raw;
+ $this->item['purchase_date'] = $this->parseOrNullDate('purchase_date');
+ } else {
+ $this->item['purchase_date'] = null;
+ }
+ }
+
+ $this->item['created_by'] = $this->created_by;
+
$this->createComponentIfNotExists();
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a component if a duplicate does not exist
*
@@ -27,16 +94,19 @@ class ComponentImporter extends ItemImporter
*/
public function createComponentIfNotExists()
{
- $component = null;
+ $name = trim($this->item['name'] ?? '');
+ $serial = trim($this->item['serial'] ?? '');
+
$this->log('Creating Component');
- $component = Component::where('name', trim($this->item['name']))
- ->where('serial', trim($this->item['serial']))
+ $component = Component::where('name', $name)
+ ->where('serial', $serial)
->first();
if ($component) {
- $this->log('A matching Component '.$this->item['name'].' with serial '.$this->item['serial'].' already exists. ');
+ $this->log('A matching Component '.$name.' with serial '.$serial.' already exists. ');
if (! $this->updating) {
$this->log('Skipping Component');
+ $this->recordSkipped();
return;
}
@@ -44,6 +114,7 @@ class ComponentImporter extends ItemImporter
$component->update($this->sanitizeItemForUpdating($component));
// update() already saves the model, no need to call save() again while Model::unguard() is active
$component->setImported(true);
+ $this->recordUpdated();
return;
}
@@ -55,10 +126,11 @@ class ComponentImporter extends ItemImporter
// This sets an attribute on the Loggable trait for the action log
$component->setImported(true);
if ($component->save()) {
- $this->log('Component '.$this->item['name'].' was created');
+ $this->log('Component '.$name.' was created');
+ $this->recordCreated();
// If we have an asset tag, checkout to that asset.
- if (isset($this->item['asset_tag']) && ($asset = Asset::where('asset_tag', $this->item['asset_tag'])->first())) {
+ if (! empty($this->item['asset_tag']) && ($asset = Asset::where('asset_tag', $this->item['asset_tag'])->first())) {
if (! $component->canCheckoutTo($asset)) {
$this->log(trans('general.error_checkout_company_mismatch', [
'item' => trans('general.component').' "'.$component->name.'"',
@@ -78,6 +150,7 @@ class ComponentImporter extends ItemImporter
return;
}
+ $this->recordErrored();
$this->logError($component, 'Component');
}
}
diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php
index 9b098cd0b9..7e62919f62 100644
--- a/app/Importer/ConsumableImporter.php
+++ b/app/Importer/ConsumableImporter.php
@@ -15,10 +15,77 @@ class ConsumableImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // ConsumableImporter deliberately does NOT call parent::handle(). See
+ // LicenseImporter / AssetImporter / AccessoryImporter for the same
+ // pattern: absent CSV columns stay out of $this->item so update mode
+ // preserves the DB value, and present-but-empty cells land as null
+ // so update mode clears the DB value. The base sanitize's reject-empty
+ // pass is suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ // Shared lookup fields. Present-and-empty clears the FK; absent
+ // preserves it; present-and-set resolves and stores the id.
+ // department + manager kept as side-effect calls even though they
+ // are not in Consumable's fillable, so createOrFetchUser can find
+ // an auto-created department when it mints a checkout-target user.
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['company_id', 'company', fn ($v) => $this->createOrFetchCompany($v)],
+ ['location_id', 'location', fn ($v) => $this->createOrFetchLocation($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['supplier_id', 'supplier', fn ($v) => $this->createOrFetchSupplier($v)],
+ ['department_id', 'department', fn ($v) => $this->createOrFetchDepartment($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ if ($this->csvRowHas($row, 'manager_first_name')) {
+ $first = $this->findCsvMatch($row, 'manager_first_name');
+ $last = $this->findCsvMatch($row, 'manager_last_name');
+ $this->item['manager_id'] = ($first !== '') ? $this->fetchManager($first, $last) : null;
+ }
+
+ $this->setItemFromCsvIfPresent($row, 'name', 'item_name');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'order_number');
+ $this->setItemFromCsvIfPresent($row, 'purchase_cost');
+ $this->setItemFromCsvIfPresent($row, 'model_number');
+ $this->setItemFromCsvIfPresent($row, 'min_amt');
+ $this->setItemFromCsvIfPresent($row, 'qty', 'quantity');
+ $this->setItemFromCsvIfPresent($row, 'requestable');
+ $this->setItemFromCsvIfPresent($row, 'item_no');
+
+ if ($this->csvRowHas($row, 'purchase_date')) {
+ $raw = $this->findCsvMatch($row, 'purchase_date');
+ if ($raw !== '') {
+ $this->item['purchase_date'] = $raw;
+ $this->item['purchase_date'] = $this->parseOrNullDate('purchase_date');
+ } else {
+ $this->item['purchase_date'] = null;
+ }
+ }
+
+ // Internal signals for the checkout logic; neither is fillable on
+ // Consumable so sanitize's fillable filter drops them.
+ $this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class');
+ $this->item['checkout_target'] = $this->determineCheckout($row);
+ $this->item['created_by'] = $this->created_by;
+
$this->createConsumableIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a consumable if a duplicate does not exist
*
@@ -30,11 +97,13 @@ class ConsumableImporter extends ItemImporter
*/
public function createConsumableIfNotExists($row)
{
- $consumable = Consumable::where('name', trim($this->item['name']))->first();
+ $name = trim($this->item['name'] ?? '');
+ $consumable = Consumable::where('name', $name)->first();
if ($consumable) {
if (! $this->updating) {
- $this->log('A matching Consumable '.$this->item['name'].' already exists. ');
+ $this->log('A matching Consumable '.$name.' already exists. ');
+ $this->recordSkipped();
$this->maybeCheckoutConsumable($consumable);
@@ -44,6 +113,7 @@ class ConsumableImporter extends ItemImporter
$consumable->update($this->sanitizeItemForUpdating($consumable));
// update() already saves the model, no need to call save() again while Model::unguard() is active
$consumable->setImported(true);
+ $this->recordUpdated();
$this->maybeCheckoutConsumable($consumable);
@@ -58,12 +128,14 @@ class ConsumableImporter extends ItemImporter
// This sets an attribute on the Loggable trait for the action log
$consumable->setImported(true);
if ($consumable->save()) {
- $this->log('Consumable '.$this->item['name'].' was created');
+ $this->log('Consumable '.$name.' was created');
+ $this->recordCreated();
$this->maybeCheckoutConsumable($consumable);
return;
}
+ $this->recordErrored();
$this->logError($consumable, 'Consumable');
}
diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php
index 07a82f8d43..45f07252ab 100644
--- a/app/Importer/Importer.php
+++ b/app/Importer/Importer.php
@@ -178,6 +178,14 @@ abstract class Importer
// CLI callers (ObjectImportCommand) and any external caller
// hitting the API without offset/limit still work unchanged.
foreach ($this->csv->getRecords($headerRow) as $row) {
+ // Fully blank rows (every cell empty, like ",,,,,,,,") carry
+ // no importable data. Skipping them before both the offset
+ // walk AND handle() means slice math, tallies, and per-row
+ // logging all reflect real work rather than padding rows.
+ if (self::rowIsBlank($row)) {
+ continue;
+ }
+
if ($offset !== null && $importedItemsCount < $offset) {
$importedItemsCount++;
@@ -264,6 +272,52 @@ abstract class Importer
return $val;
}
+ /**
+ * True when the CSV row contains a value for the given logical key
+ * (whether the value is populated or empty). Callers use this to
+ * distinguish "column absent from the CSV" (leave DB alone) from
+ * "column present with an empty value" (clear the DB field on update).
+ */
+ protected function csvRowHas(array $row, string $csvKey): bool
+ {
+ return array_key_exists($this->lookupCustomKey($csvKey), $row);
+ }
+
+ /**
+ * True when every cell in the CSV row is empty after trimming.
+ * Fully blank rows (like ",,,,,,,") get filtered out before handle()
+ * so they do not count toward the tally, appear in the preview,
+ * or trigger per-row logging.
+ */
+ protected static function rowIsBlank(array $row): bool
+ {
+ foreach ($row as $value) {
+ if (trim((string) $value) !== '') {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Assign a value from the CSV row into $this->item under the given item
+ * key, only when the CSV row actually contained that column. Empty CSV
+ * cells are assigned as null (not as empty strings) so the DB stores
+ * NULL when the user explicitly clears a nullable field on update.
+ * Columns absent from the CSV row are never touched, so update mode
+ * preserves existing DB values for any field the user did not include
+ * in their file.
+ */
+ protected function setItemFromCsvIfPresent(array $row, string $itemKey, ?string $csvKey = null): void
+ {
+ $csvKey = $csvKey ?? $itemKey;
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value === '') ? null : $value;
+ }
+ }
+
/**
* Looks up A custom key in the custom field map
*
@@ -322,6 +376,46 @@ abstract class Importer
}
}
+ /**
+ * Per-row tally accumulated across the current slice. The wizard UI adds
+ * these across slices so the user sees a real "N created, M updated,
+ * K skipped as duplicates" summary at the end of an import instead of
+ * a generic success flash. logError() and addErrorToBag() auto-record
+ * errored; subclasses call recordCreated/Updated/Skipped explicitly
+ * from the branches of their handle() method.
+ */
+ protected array $tally = [
+ 'created' => 0,
+ 'updated' => 0,
+ 'skipped' => 0,
+ 'errored' => 0,
+ ];
+
+ protected function recordCreated(): void
+ {
+ $this->tally['created']++;
+ }
+
+ protected function recordUpdated(): void
+ {
+ $this->tally['updated']++;
+ }
+
+ protected function recordSkipped(): void
+ {
+ $this->tally['skipped']++;
+ }
+
+ protected function recordErrored(): void
+ {
+ $this->tally['errored']++;
+ }
+
+ public function getTally(): array
+ {
+ return $this->tally;
+ }
+
/**
* Finds the user matching given data, or creates a new one if there is no match.
* This is NOT used by the User Import, only for Asset/Accessory/etc where
diff --git a/app/Importer/LicenseImporter.php b/app/Importer/LicenseImporter.php
index 9ea29d9f56..80305bfcab 100644
--- a/app/Importer/LicenseImporter.php
+++ b/app/Importer/LicenseImporter.php
@@ -14,11 +14,74 @@ class LicenseImporter extends ItemImporter
protected function handle($row)
{
- // ItemImporter handles the general fetching.
- parent::handle($row);
+ // LicenseImporter deliberately does NOT call parent::handle(). The
+ // parent unconditionally assigns $this->item entries for every
+ // shared field, which conflates "column absent from CSV" with
+ // "column present but empty" and prevents empty CSV cells from
+ // clearing existing DB values on update. LicenseImporter builds
+ // $this->item exclusively via setItemFromCsvIfPresent so absent
+ // columns never enter the update payload (preserving DB values)
+ // and present-but-empty columns land as empty strings (clearing
+ // DB values). See sanitizeItemForStoring override below for the
+ // matching pass-through sanitize.
+ $this->item = [];
+
+ // Shared lookup fields. Present-and-empty clears the FK; absent
+ // preserves it; present-and-set resolves and stores the id.
+ foreach ([
+ ['category_id', 'category', fn ($v) => $this->createOrFetchCategory($v)],
+ ['company_id', 'company', fn ($v) => $this->createOrFetchCompany($v)],
+ ['manufacturer_id', 'manufacturer', fn ($v) => $this->createOrFetchManufacturer($v)],
+ ['supplier_id', 'supplier', fn ($v) => $this->createOrFetchSupplier($v)],
+ ] as [$itemKey, $csvKey, $resolver]) {
+ if ($this->csvRowHas($row, $csvKey)) {
+ $value = $this->findCsvMatch($row, $csvKey);
+ $this->item[$itemKey] = ($value !== '') ? $resolver($value) : null;
+ }
+ }
+
+ // Shared straight assignments from ItemImporter's field list that
+ // apply to licenses.
+ $this->setItemFromCsvIfPresent($row, 'name', 'item_name');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'purchase_cost');
+
+ if ($this->csvRowHas($row, 'purchase_date')) {
+ $raw = $this->findCsvMatch($row, 'purchase_date');
+ if ($raw !== '') {
+ $this->item['purchase_date'] = $raw;
+ $this->item['purchase_date'] = $this->parseOrNullDate('purchase_date');
+ } else {
+ $this->item['purchase_date'] = null;
+ }
+ }
+
+ // Serial and asset_tag both need special handling. serial IS a
+ // License field so it goes through the helper. asset_tag is captured
+ // separately for the seat-checkout logic in createLicenseIfNotExists.
+ $this->setItemFromCsvIfPresent($row, 'serial');
+
+ // checkout_class + checkout_target are internal signals for the
+ // seat-checkout logic below; neither is fillable on License, so
+ // sanitize's fillable filter drops them before the DB write.
+ $this->item['checkout_class'] = $this->findCsvMatch($row, 'checkout_class');
+ $this->item['checkout_target'] = $this->determineCheckout($row);
+ $this->item['created_by'] = $this->created_by;
+
$this->createLicenseIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. LicenseImporter
+ * populates $this->item exclusively from CSV columns that were present in
+ * the row, so an empty value here is an explicit intent to clear the DB
+ * field on update. See handle() above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create the license if it does not exist.
*
@@ -33,18 +96,28 @@ class LicenseImporter extends ItemImporter
*/
public function createLicenseIfNotExists(array $row)
{
+ // serial and name are the identity fields for the create-or-update
+ // match. Both are populated in handle() via setItemFromCsvIfPresent,
+ // so a CSV without those columns will produce empty keys here.
+ // Fallback to empty string so the where clauses do not blow up on
+ // undefined indexes; the resulting query will match nothing, and the
+ // validation error path takes over on the save attempt.
+ $serial = $this->item['serial'] ?? '';
+ $name = $this->item['name'] ?? '';
+
$editingLicense = false;
- $license = License::where('serial', $this->item['serial'])->where('name', $this->item['name'])
- ->first();
+ $license = License::where('serial', $serial)->where('name', $name)->first();
if ($license) {
if (! $this->updating) {
- if ($this->item['serial'] != '') {
- $this->log('A matching License '.$this->item['name'].' with serial '.$this->item['serial'].' already exists');
+ if ($serial !== '') {
+ $this->log('A matching License '.$name.' with serial '.$serial.' already exists');
} else {
- $this->log('A matching License '.$this->item['name'].' with no serial number already exists');
+ $this->log('A matching License '.$name.' with no serial number already exists');
}
+ $this->recordSkipped();
+
return;
}
@@ -54,31 +127,32 @@ class LicenseImporter extends ItemImporter
$this->log('No Matching License, Creating a new one');
$license = new License;
}
- $asset_tag = $this->item['asset_tag'] = trim($this->findCsvMatch($row, 'asset_tag')); // used for checkout out to an asset.
-
- $this->item['expiration_date'] = null;
- if ($this->findCsvMatch($row, 'expiration_date') != '') {
- $this->item['expiration_date'] = $this->findCsvMatch($row, 'expiration_date');
- $this->item['expiration_date'] = $this->parseOrNullDate('expiration_date');
- }
- $this->item['license_email'] = trim($this->findCsvMatch($row, 'license_email'));
- $this->item['license_name'] = trim($this->findCsvMatch($row, 'license_name'));
- $this->item['maintained'] = trim($this->findCsvMatch($row, 'maintained'));
- $this->item['purchase_order'] = trim($this->findCsvMatch($row, 'purchase_order'));
- $this->item['order_number'] = trim($this->findCsvMatch($row, 'order_number'));
- $this->item['reassignable'] = trim($this->findCsvMatch($row, 'reassignable'));
- $this->item['manufacturer'] = $this->createOrFetchManufacturer(trim($this->findCsvMatch($row, 'manufacturer')));
- $this->item['min_amt'] = trim($this->findCsvMatch($row, 'min_amt'));
-
- if ($this->item['reassignable'] == '') {
- $this->item['reassignable'] = 1;
- }
- $this->item['seats'] = $this->findCsvMatch($row, 'seats');
-
- $this->item['termination_date'] = null;
- if ($this->findCsvMatch($row, 'termination_date') != '') {
- $this->item['termination_date'] = $this->findCsvMatch($row, 'termination_date');
- $this->item['termination_date'] = $this->parseOrNullDate('termination_date');
+ // Asset tag is captured separately for the seat-checkout logic below;
+ // it is not itself a License column, so it does not go through the
+ // item array (asset_tag isn't in License's fillable).
+ $asset_tag = $this->csvRowHas($row, 'asset_tag') ? $this->findCsvMatch($row, 'asset_tag') : '';
+
+ $this->setItemFromCsvIfPresent($row, 'license_email');
+ $this->setItemFromCsvIfPresent($row, 'license_name');
+ $this->setItemFromCsvIfPresent($row, 'maintained');
+ $this->setItemFromCsvIfPresent($row, 'purchase_order');
+ $this->setItemFromCsvIfPresent($row, 'order_number');
+ $this->setItemFromCsvIfPresent($row, 'reassignable');
+ $this->setItemFromCsvIfPresent($row, 'min_amt');
+ $this->setItemFromCsvIfPresent($row, 'seats');
+
+ // Dates need parseOrNullDate after the raw value is in $this->item.
+ // Empty value stays null (which clears the DB field on update).
+ foreach (['expiration_date', 'termination_date'] as $dateField) {
+ if ($this->csvRowHas($row, $dateField)) {
+ $raw = $this->findCsvMatch($row, $dateField);
+ if ($raw !== '') {
+ $this->item[$dateField] = $raw;
+ $this->item[$dateField] = $this->parseOrNullDate($dateField);
+ } else {
+ $this->item[$dateField] = null;
+ }
+ }
}
if ($editingLicense) {
@@ -95,7 +169,13 @@ class LicenseImporter extends ItemImporter
$licenseWasSaved = $editingLicense || $license->save();
if ($licenseWasSaved) {
- $this->log('License '.$this->item['name'].' with serial number '.$this->item['serial'].' was created or updated');
+ $this->log('License '.$name.' with serial number '.$serial.' was created or updated');
+
+ if ($editingLicense) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
// Lets try to checkout seats if the fields exist and we have seats.
if ($license->seats > 0) {
@@ -139,6 +219,7 @@ class LicenseImporter extends ItemImporter
return;
}
- $this->logError($license, 'License "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $this->logError($license, 'License "'.$name.'"');
}
}
diff --git a/app/Importer/LocationImporter.php b/app/Importer/LocationImporter.php
index 4464c09f2c..2028e28489 100644
--- a/app/Importer/LocationImporter.php
+++ b/app/Importer/LocationImporter.php
@@ -22,10 +22,76 @@ class LocationImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // LocationImporter deliberately does NOT call parent::handle(). See
+ // the other subclass migrations for the same pattern: absent CSV
+ // columns stay out of $this->item so update mode preserves the DB
+ // value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ // Straight CSV-to-item assignments for Location fillable fields.
+ $this->setItemFromCsvIfPresent($row, 'name');
+ $this->setItemFromCsvIfPresent($row, 'address');
+ $this->setItemFromCsvIfPresent($row, 'address2');
+ $this->setItemFromCsvIfPresent($row, 'city');
+ $this->setItemFromCsvIfPresent($row, 'state');
+ $this->setItemFromCsvIfPresent($row, 'country');
+ $this->setItemFromCsvIfPresent($row, 'zip');
+ $this->setItemFromCsvIfPresent($row, 'currency');
+ $this->setItemFromCsvIfPresent($row, 'ldap_ou');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'tag_color');
+
+ // parent_location column resolves to parent_id on the model. Empty
+ // value clears the parent (root-level location); absent preserves.
+ if ($this->csvRowHas($row, 'parent_location')) {
+ $raw = $this->findCsvMatch($row, 'parent_location');
+ $this->item['parent_id'] = ($raw !== '') ? $this->createOrFetchLocation($raw) : null;
+ }
+
+ // company column resolves to company_id. Applies to both create and
+ // update paths (the old importer only did this on create - which
+ // silently prevented reassigning a location to a different company
+ // via re-import). Present-and-empty clears company_id.
+ if ($this->csvRowHas($row, 'company')) {
+ $raw = $this->findCsvMatch($row, 'company');
+ $this->item['company_id'] = ($raw !== '') ? $this->createOrFetchCompany($raw) : null;
+ }
+
+ // Manager lookup: the 'manager' CSV column is the full name string
+ // (space-separated first + last), matched via createOrFetchUser
+ // which reads $this->item['manager'] (and optionally 'manager_username'
+ // as an alternate lookup key). Both are internal signals, not
+ // fillable on Location, so sanitize's fillable filter drops them
+ // before the DB write.
+ if ($this->csvRowHas($row, 'manager')) {
+ $this->item['manager'] = $this->findCsvMatch($row, 'manager');
+ }
+ if ($this->csvRowHas($row, 'manager_username')) {
+ $this->item['manager_username'] = $this->findCsvMatch($row, 'manager_username');
+ }
+ if (! empty($this->item['manager'])) {
+ if ($manager = $this->createOrFetchUser($row, 'manager')) {
+ $this->item['manager_id'] = $manager->id;
+ }
+ } elseif (array_key_exists('manager', $this->item)) {
+ // CSV had the manager column but left it empty - clear the FK.
+ $this->item['manager_id'] = null;
+ }
+
$this->createLocationIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a location if a duplicate does not exist.
*
@@ -37,10 +103,10 @@ class LocationImporter extends ItemImporter
*/
public function createLocationIfNotExists(array $row)
{
-
$editingLocation = false;
+ $name = trim($this->item['name'] ?? '');
- $location = Location::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
+ $location = Location::where('name', '=', $name)->first();
if ($this->findCsvMatch($row, 'id') != '') {
// Override location if an ID was given
@@ -50,7 +116,8 @@ class LocationImporter extends ItemImporter
if ($location) {
if (! $this->updating) {
- $this->log('A matching Location '.$this->item['name'].' already exists');
+ $this->log('A matching Location '.$name.' already exists');
+ $this->recordSkipped();
return;
}
@@ -63,31 +130,6 @@ class LocationImporter extends ItemImporter
$location->created_by = $this->created_by;
}
- // Pull the records from the CSV to determine their values
- $this->item['name'] = trim($this->findCsvMatch($row, 'name'));
- $this->item['address'] = trim($this->findCsvMatch($row, 'address'));
- $this->item['address2'] = trim($this->findCsvMatch($row, 'address2'));
- $this->item['city'] = trim($this->findCsvMatch($row, 'city'));
- $this->item['state'] = trim($this->findCsvMatch($row, 'state'));
- $this->item['country'] = trim($this->findCsvMatch($row, 'country'));
- $this->item['zip'] = trim($this->findCsvMatch($row, 'zip'));
- $this->item['currency'] = trim($this->findCsvMatch($row, 'currency'));
- $this->item['ldap_ou'] = trim($this->findCsvMatch($row, 'ldap_ou'));
- $this->item['manager'] = trim($this->findCsvMatch($row, 'manager'));
- $this->item['manager_username'] = trim($this->findCsvMatch($row, 'manager_username'));
- $this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
- $this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
- if ($this->findCsvMatch($row, 'parent_location')) {
- $this->item['parent_id'] = $this->createOrFetchLocation(trim($this->findCsvMatch($row, 'parent_location')));
- }
-
- if (! empty($this->item['manager'])) {
- if ($manager = $this->createOrFetchUser($row, 'manager')) {
- $this->item['manager_id'] = $manager->id;
- }
- }
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
@@ -96,20 +138,23 @@ class LocationImporter extends ItemImporter
$location->update($this->sanitizeItemForUpdating($location));
} else {
Log::debug('Creating location');
- if ($this->findCsvMatch($row, 'company')) {
- $this->item['company_id'] = $this->createOrFetchCompany(trim($this->findCsvMatch($row, 'company')));
- }
$location->fill($this->sanitizeItemForStoring($location));
}
if ($location->save()) {
$this->log('Location '.$location->name.' created or updated from CSV import');
+ if ($editingLocation) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
return $location;
} else {
Log::debug($location->getErrors());
- $this->logError($location, 'Location "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $this->logError($location, 'Location "'.$name.'"');
return $location->errors;
}
diff --git a/app/Importer/ManufacturerImporter.php b/app/Importer/ManufacturerImporter.php
index 15497ba90a..7038c06a9b 100644
--- a/app/Importer/ManufacturerImporter.php
+++ b/app/Importer/ManufacturerImporter.php
@@ -22,10 +22,39 @@ class ManufacturerImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // ManufacturerImporter deliberately does NOT call parent::handle(). See
+ // the other subclass migrations for the same pattern: absent CSV
+ // columns stay out of $this->item so update mode preserves the DB
+ // value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ foreach ([
+ 'name',
+ 'support_phone',
+ 'support_email',
+ 'url',
+ 'support_url',
+ 'warranty_lookup_url',
+ 'notes',
+ 'tag_color',
+ ] as $field) {
+ $this->setItemFromCsvIfPresent($row, $field);
+ }
+
$this->createManufacturerIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a manufacturer if a duplicate does not exist.
*
@@ -37,10 +66,10 @@ class ManufacturerImporter extends ItemImporter
*/
public function createManufacturerIfNotExists(array $row)
{
-
$editingManufacturer = false;
+ $name = trim($this->item['name'] ?? '');
- $manufacturer = Manufacturer::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
+ $manufacturer = Manufacturer::where('name', '=', $name)->first();
if ($this->findCsvMatch($row, 'id') != '') {
// Override manufacturer if an ID was given
@@ -50,7 +79,8 @@ class ManufacturerImporter extends ItemImporter
if ($manufacturer) {
if (! $this->updating) {
- $this->log('A matching Manufacturer '.$this->item['name'].' already exists');
+ $this->log('A matching Manufacturer ' . $name . ' already exists');
+ $this->recordSkipped();
return;
}
@@ -63,18 +93,6 @@ class ManufacturerImporter extends ItemImporter
$manufacturer->created_by = $this->created_by;
}
- // Pull the records from the CSV to determine their values
- $this->item['name'] = trim($this->findCsvMatch($row, 'name'));
- $this->item['support_phone'] = trim($this->findCsvMatch($row, 'support_phone'));
- $this->item['fax'] = trim($this->findCsvMatch($row, 'fax'));
- $this->item['support_email'] = trim($this->findCsvMatch($row, 'support_email'));
- $this->item['contact'] = trim($this->findCsvMatch($row, 'contact'));
- $this->item['url'] = trim($this->findCsvMatch($row, 'url'));
- $this->item['support_url'] = trim($this->findCsvMatch($row, 'support_url'));
- $this->item['warranty_lookup_url'] = trim($this->findCsvMatch($row, 'warranty_lookup_url'));
- $this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
- $this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
@@ -88,12 +106,18 @@ class ManufacturerImporter extends ItemImporter
if ($manufacturer->save()) {
$this->log('Manufacturer '.$manufacturer->name.' created or updated from CSV import');
+ if ($editingManufacturer) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
return $manufacturer;
} else {
Log::debug($manufacturer->getErrors());
- $this->logError($manufacturer, 'Manufacturer "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $this->logError($manufacturer, 'Manufacturer "' . $name . '"');
return $manufacturer->errors;
}
diff --git a/app/Importer/SupplierImporter.php b/app/Importer/SupplierImporter.php
index f99d0c7a6b..e38fc6e309 100644
--- a/app/Importer/SupplierImporter.php
+++ b/app/Importer/SupplierImporter.php
@@ -22,10 +22,45 @@ class SupplierImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
+ // SupplierImporter deliberately does NOT call parent::handle(). See
+ // the other subclass migrations for the same pattern: absent CSV
+ // columns stay out of $this->item so update mode preserves the DB
+ // value, and present-but-empty cells land as null so update mode
+ // clears the DB value. The base sanitize's reject-empty pass is
+ // suppressed via the sanitizeItemForStoring override below.
+ $this->item = [];
+
+ foreach ([
+ 'name',
+ 'address',
+ 'address2',
+ 'city',
+ 'state',
+ 'country',
+ 'zip',
+ 'phone',
+ 'fax',
+ 'email',
+ 'contact',
+ 'url',
+ 'notes',
+ 'tag_color',
+ ] as $field) {
+ $this->setItemFromCsvIfPresent($row, $field);
+ }
+
$this->createSupplierIfNotExists($row);
}
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
+ }
+
/**
* Create a supplier if a duplicate does not exist.
*
@@ -37,10 +72,10 @@ class SupplierImporter extends ItemImporter
*/
public function createSupplierIfNotExists(array $row)
{
-
$editingSupplier = false;
+ $name = trim($this->item['name'] ?? '');
- $supplier = Supplier::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
+ $supplier = Supplier::where('name', '=', $name)->first();
if ($this->findCsvMatch($row, 'id') != '') {
// Override supplier if an ID was given
@@ -50,7 +85,8 @@ class SupplierImporter extends ItemImporter
if ($supplier) {
if (! $this->updating) {
- $this->log('A matching Supplier '.$this->item['name'].' already exists');
+ $this->log('A matching Supplier '.$name.' already exists');
+ $this->recordSkipped();
return;
}
@@ -63,22 +99,6 @@ class SupplierImporter extends ItemImporter
$supplier->created_by = $this->created_by;
}
- // Pull the records from the CSV to determine their values
- $this->item['name'] = trim($this->findCsvMatch($row, 'name'));
- $this->item['address'] = trim($this->findCsvMatch($row, 'address'));
- $this->item['address2'] = trim($this->findCsvMatch($row, 'address2'));
- $this->item['city'] = trim($this->findCsvMatch($row, 'city'));
- $this->item['state'] = trim($this->findCsvMatch($row, 'state'));
- $this->item['country'] = trim($this->findCsvMatch($row, 'country'));
- $this->item['zip'] = trim($this->findCsvMatch($row, 'zip'));
- $this->item['phone'] = trim($this->findCsvMatch($row, 'phone'));
- $this->item['fax'] = trim($this->findCsvMatch($row, 'fax'));
- $this->item['email'] = trim($this->findCsvMatch($row, 'email'));
- $this->item['contact'] = trim($this->findCsvMatch($row, 'contact'));
- $this->item['url'] = trim($this->findCsvMatch($row, 'url'));
- $this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
- $this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
@@ -92,12 +112,18 @@ class SupplierImporter extends ItemImporter
if ($supplier->save()) {
$this->log('Supplier '.$supplier->name.' created or updated from CSV import');
+ if ($editingSupplier) {
+ $this->recordUpdated();
+ } else {
+ $this->recordCreated();
+ }
return $supplier;
} else {
Log::debug($supplier->getErrors());
- $this->logError($supplier, 'Supplier "'.$this->item['name'].'"');
+ $this->recordErrored();
+ $this->logError($supplier, 'Supplier "'.$name.'"');
return $supplier->errors;
}
diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.php
index 4c29189085..50dc304af5 100644
--- a/app/Importer/UserImporter.php
+++ b/app/Importer/UserImporter.php
@@ -32,8 +32,122 @@ class UserImporter extends ItemImporter
protected function handle($row)
{
- parent::handle($row);
- $this->createUserIfNotExists($row);
+ // UserImporter deliberately does NOT call parent::handle(). See the
+ // other subclass migrations (LicenseImporter / AssetImporter / etc.)
+ // for the same pattern: absent CSV columns stay out of $this->item so
+ // update mode preserves the DB value, and present-but-empty cells land
+ // as null so update mode clears the DB value. The base sanitize's
+ // reject-empty pass is suppressed via the sanitizeItemForStoring
+ // override below.
+ //
+ // Company is handled separately (pipe-separated CSV column, synced via
+ // pivot rather than a company_id column) and is intentionally not
+ // routed through the shared FK lookup loop.
+ $this->item = [];
+
+ if ($this->csvRowHas($row, 'location')) {
+ $raw = $this->findCsvMatch($row, 'location');
+ $this->item['location_id'] = ($raw !== '') ? $this->createOrFetchLocation($raw) : null;
+ }
+
+ if ($this->csvRowHas($row, 'department')) {
+ $raw = $this->findCsvMatch($row, 'department');
+ $this->item['department_id'] = ($raw !== '') ? $this->createOrFetchDepartment($raw) : null;
+ }
+
+ // Manager lookup uses whichever identifier the CSV provides, in
+ // priority order: username, employee_num, then first + last name pair.
+ // Treat any of those columns being present as the presence signal
+ // for the whole lookup so an update can clear the manager_id by
+ // leaving all four columns present but empty.
+ $managerCsvKeys = ['manager_username', 'manager_employee_num', 'manager_first_name', 'manager_last_name'];
+ $managerCsvPresent = false;
+ foreach ($managerCsvKeys as $key) {
+ if ($this->csvRowHas($row, $key)) {
+ $managerCsvPresent = true;
+ break;
+ }
+ }
+ if ($managerCsvPresent) {
+ $managerUsername = $this->findCsvMatch($row, 'manager_username') ?? '';
+ $managerEmployeeNum = $this->findCsvMatch($row, 'manager_employee_num') ?? '';
+ $managerFirstName = $this->findCsvMatch($row, 'manager_first_name') ?? '';
+ $managerLastName = $this->findCsvMatch($row, 'manager_last_name') ?? '';
+ $anyPopulated = ($managerUsername !== '' || $managerEmployeeNum !== '' || $managerFirstName !== '' || $managerLastName !== '');
+ $this->item['manager_id'] = $anyPopulated
+ ? $this->fetchManager($managerUsername, $managerEmployeeNum, $managerFirstName, $managerLastName)
+ : null;
+ }
+
+ // Straight string fields. Each column absent from the CSV stays out
+ // of $this->item; present-but-empty lands as null so sanitize can
+ // pass it through and Eloquent clears the DB value on update.
+ $this->setItemFromCsvIfPresent($row, 'username');
+ $this->setItemFromCsvIfPresent($row, 'display_name');
+ $this->setItemFromCsvIfPresent($row, 'first_name');
+ $this->setItemFromCsvIfPresent($row, 'last_name');
+ $this->setItemFromCsvIfPresent($row, 'email');
+ $this->setItemFromCsvIfPresent($row, 'gravatar');
+ $this->setItemFromCsvIfPresent($row, 'phone', 'phone_number');
+ $this->setItemFromCsvIfPresent($row, 'mobile', 'mobile_number');
+ $this->setItemFromCsvIfPresent($row, 'website');
+ $this->setItemFromCsvIfPresent($row, 'jobtitle');
+ $this->setItemFromCsvIfPresent($row, 'address');
+ $this->setItemFromCsvIfPresent($row, 'city');
+ $this->setItemFromCsvIfPresent($row, 'state');
+ $this->setItemFromCsvIfPresent($row, 'country');
+ $this->setItemFromCsvIfPresent($row, 'zip');
+ $this->setItemFromCsvIfPresent($row, 'employee_num');
+ $this->setItemFromCsvIfPresent($row, 'notes');
+ $this->setItemFromCsvIfPresent($row, 'avatar');
+ $this->setItemFromCsvIfPresent($row, 'scim_externalid');
+ $this->setItemFromCsvIfPresent($row, 'locale');
+ $this->setItemFromCsvIfPresent($row, 'ldap_import');
+
+ // Boolean flags. Present-and-empty means 0 (fetchHumanBoolean returns
+ // 0 for empty); present-with-value means the parsed 1/0. Absent
+ // means don't touch the DB value on update.
+ foreach (['activated', 'remote', 'vip', 'autoassign_licenses'] as $flag) {
+ if ($this->csvRowHas($row, $flag)) {
+ $raw = $this->findCsvMatch($row, $flag);
+ $this->item[$flag] = ($this->fetchHumanBoolean($raw) == 1) ? '1' : 0;
+ }
+ }
+
+ foreach (['start_date', 'end_date'] as $dateField) {
+ if ($this->csvRowHas($row, $dateField)) {
+ $raw = $this->findCsvMatch($row, $dateField);
+ if ($raw !== '') {
+ $this->item[$dateField] = $raw;
+ $this->item[$dateField] = $this->parseOrNullDate($dateField);
+ } else {
+ $this->item[$dateField] = null;
+ }
+ }
+ }
+
+ // id is used only for identity matching (see createUserIfNotExists),
+ // never written to the DB. Not fillable on User either, so sanitize's
+ // fillable filter would drop it - stash separately.
+ $csvId = $this->csvRowHas($row, 'id') ? trim((string) $this->findCsvMatch($row, 'id')) : '';
+
+ // display_name coerces empty to null explicitly - the DB column is
+ // nullable and users expect empty CSV to mean "no display name"
+ // (falls back to first_name + last_name at read time).
+ if (array_key_exists('display_name', $this->item) && $this->item['display_name'] === '') {
+ $this->item['display_name'] = null;
+ }
+
+ $this->createUserIfNotExists($row, $csvId);
+ }
+
+ /**
+ * Override the base sanitize to skip the reject-empty pass. See handle()
+ * above for the matching item-population.
+ */
+ protected function sanitizeItemForStoring($model, $updating = false)
+ {
+ return collect($this->item)->only($model->getFillable())->toArray();
}
/**
@@ -70,67 +184,44 @@ class UserImporter extends ItemImporter
*
* @since 4.0
*/
- public function createUserIfNotExists(array $row)
+ public function createUserIfNotExists(array $row, string $csvId = '')
{
- // Pull the records from the CSV to determine their values
- $this->item['id'] = trim($this->findCsvMatch($row, 'id'));
- $this->item['username'] = trim($this->findCsvMatch($row, 'username'));
- $this->item['display_name'] = trim($this->findCsvMatch($row, 'display_name')) ?: null;
- $this->item['first_name'] = trim($this->findCsvMatch($row, 'first_name'));
- $this->item['last_name'] = trim($this->findCsvMatch($row, 'last_name'));
- $this->item['email'] = trim($this->findCsvMatch($row, 'email'));
- $this->item['gravatar'] = trim($this->findCsvMatch($row, 'gravatar'));
- $this->item['phone'] = trim($this->findCsvMatch($row, 'phone_number'));
- $this->item['mobile'] = trim($this->findCsvMatch($row, 'mobile_number'));
- $this->item['website'] = trim($this->findCsvMatch($row, 'website'));
- $this->item['jobtitle'] = trim($this->findCsvMatch($row, 'jobtitle'));
- $this->item['address'] = trim($this->findCsvMatch($row, 'address'));
- $this->item['city'] = trim($this->findCsvMatch($row, 'city'));
- $this->item['state'] = trim($this->findCsvMatch($row, 'state'));
- $this->item['country'] = trim($this->findCsvMatch($row, 'country'));
- $this->item['start_date'] = trim($this->findCsvMatch($row, 'start_date'));
- $this->item['start_date'] = $this->parseOrNullDate('start_date');
- $this->item['end_date'] = trim($this->findCsvMatch($row, 'end_date'));
- $this->item['end_date'] = $this->parseOrNullDate('end_date');
- $this->item['zip'] = trim($this->findCsvMatch($row, 'zip'));
- $this->item['activated'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'activated'))) == 1) ? '1' : 0;
- $this->item['employee_num'] = trim($this->findCsvMatch($row, 'employee_num'));
- $this->item['department_id'] = trim($this->createOrFetchDepartment(trim($this->findCsvMatch($row, 'department'))));
- $this->item['manager_id'] = $this->fetchManager(trim($this->findCsvMatch($row, 'manager_username')), trim($this->findCsvMatch($row, 'manager_employee_num')), trim($this->findCsvMatch($row, 'manager_first_name')), trim($this->findCsvMatch($row, 'manager_last_name')));
- $this->item['remote'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'remote'))) == 1) ? '1' : 0;
- $this->item['vip'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'vip'))) == 1) ? '1' : 0;
- $this->item['autoassign_licenses'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'autoassign_licenses'))) == 1) ? '1' : 0;
-
- $user_department = trim($this->findCsvMatch($row, 'department'));
- if ($this->shouldUpdateField($user_department)) {
- $this->item['department_id'] = $this->createOrFetchDepartment($user_department);
- }
-
// Resolve pipe-separated company names (e.g. "Acme Corp|Widget Inc") into IDs.
- // company_id is a legacy column — company membership is managed via the pivot.
- // Unset whatever the parent set so it is not written to the DB.
- $companyRaw = trim($this->findCsvMatch($row, 'company'));
+ // Company membership is managed via the pivot; the legacy company_id column
+ // mirror is synced separately via syncLegacyCompanyIdMirror() below.
+ $companyRaw = $this->csvRowHas($row, 'company')
+ ? trim((string) $this->findCsvMatch($row, 'company'))
+ : '';
$companyIds = $this->resolveCompanyIds($companyRaw);
- unset($this->item['company_id']);
- if (is_null($this->item['username']) || $this->item['username'] == '') {
- $user_full_name = $this->item['first_name'].' '.$this->item['last_name'];
+ // Auto-generate a username from first + last name if the CSV did
+ // not provide one (either the column was absent or the value was
+ // empty). Requires first_name + last_name to have been populated
+ // by the CSV; otherwise the generated username will just be the
+ // configured format with empty inputs.
+ $usernameProvided = array_key_exists('username', $this->item) && $this->item['username'] !== '' && $this->item['username'] !== null;
+ if (! $usernameProvided) {
+ $firstName = $this->item['first_name'] ?? '';
+ $lastName = $this->item['last_name'] ?? '';
+ $user_full_name = trim($firstName.' '.$lastName);
$user_formatted_array = User::generateFormattedNameFromFullName($user_full_name, Setting::getSettings()->username_format);
$this->item['username'] = $user_formatted_array['username'];
}
- // Check if a numeric ID was passed. If it does, use that above all else.
- if ((array_key_exists('id', $this->item) && ($this->item['id'] != '') && (is_numeric($this->item['id'])))) {
- $user = User::find($this->item['id']);
+ // Identity match. Prefer a numeric ID from the CSV over the username
+ // lookup, so a re-import against a renamed user still lands on the
+ // right record. Username is required for the fallback and is
+ // guaranteed populated above (either from the CSV or auto-generated).
+ if ($csvId !== '' && is_numeric($csvId)) {
+ $user = User::find((int) $csvId);
} else {
$user = User::where('username', $this->item['username'])->first();
}
if ($user) {
-
- // If the user does not want to update existing values, only add new ones, bail out
if (! $this->updating) {
- Log::debug('A matching User '.$this->item['name'].' already exists. ');
+ Log::debug('A matching User '.$this->item['username'].' already exists. ');
+ $this->recordSkipped();
return;
}
@@ -138,7 +229,7 @@ class UserImporter extends ItemImporter
$this->log('Updating User');
// CLI imports run unauthenticated and are fully trusted; only restrict web-initiated imports.
- // Note: unset must target $this->item, not the model — sanitizeItemForUpdating() reads from $this->item.
+ // Note: unset must target $this->item, not the model - sanitizeItemForUpdating() reads from $this->item.
if (Auth::check() && (! Auth::user()->hasAccess('users.edit') || ! Gate::allows('canEditAuthFields', $user))) {
// GATED_AUTH_FIELDS is the shared list across the API,
// web-UI, and importer paths. The importer naturally
@@ -169,6 +260,7 @@ class UserImporter extends ItemImporter
]);
$this->log($msg);
$this->addErrorToBag($user, 'location_id', $msg);
+ $this->recordErrored();
return;
}
@@ -189,16 +281,18 @@ class UserImporter extends ItemImporter
->where('assigned_to', $user->id)
->update(['location_id' => $user->location_id]);
- // Log::debug('UserImporter.php Updated User ' . print_r($user, true));
+ $this->recordUpdated();
+
return;
}
// With FMCS enabled, the scoped lookup above only sees users in the current user's companies.
// If the username exists in another company it would appear as "not found" and fall through
- // to create — but usernames are unique system-wide, so we must skip instead.
+ // to create - but usernames are unique system-wide, so we must skip instead.
if (Auth::check() && Company::isFullMultipleCompanySupportEnabled()) {
if (User::withoutGlobalScopes()->where('username', $this->item['username'])->exists()) {
$this->log('Skipping '.$this->item['username'].': username belongs to a user outside your company scope.');
+ $this->recordSkipped();
return;
}
@@ -215,6 +309,7 @@ class UserImporter extends ItemImporter
$msg = trans('admin/users/general.cannot_make_floater');
$this->log('Skipping '.$this->item['username'].': '.$msg);
$this->addErrorToBag(new User, 'company_id', $msg);
+ $this->recordErrored();
return;
}
@@ -226,10 +321,22 @@ class UserImporter extends ItemImporter
]);
$this->log($msg);
$this->addErrorToBag(new User, 'location_id', $msg);
+ $this->recordErrored();
return;
}
+ // On create, default absent boolean flags to 0 to preserve backwards-
+ // compatible behavior. Under the old unconditional-set pattern these
+ // always got fetchHumanBoolean('') = 0 even when the CSV column was
+ // absent. Update mode still respects "absent means preserve," so we
+ // only apply the default on the create path.
+ foreach (['activated', 'remote', 'vip', 'autoassign_licenses'] as $flag) {
+ if (! array_key_exists($flag, $this->item)) {
+ $this->item[$flag] = 0;
+ }
+ }
+
$user = new User;
$user->created_by = $this->created_by;
@@ -238,7 +345,8 @@ class UserImporter extends ItemImporter
// TODO - check for gate here I guess
if ($user->save()) {
- $this->log('User '.$this->item['name'].' was created');
+ $this->log('User '.$user->username.' was created');
+ $this->recordCreated();
// Sync all resolved companies to the pivot. For single-company rows the
// User::created event already added company_id; sync() here is idempotent
@@ -262,11 +370,12 @@ class UserImporter extends ItemImporter
}
$user = null;
- $this->item = null;
+ $this->item = [];
return;
}
+ $this->recordErrored();
$this->logError($user, 'User');
}
@@ -275,11 +384,6 @@ class UserImporter extends ItemImporter
$this->send_welcome = $send;
}
- /**
- * Since the findCsvMatch() method will set '' for columns that are present but empty,
- * we need to set those empty strings to null to avoid passing bad data to the database
- * (ie ending up with 0000-00-00 instead of the intended null).
- */
/**
* Returns true when the given location is compatible with the given company IDs under
* FMCS location scoping rules. Mirrors the fmcs_location custom validator.
diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.php
index 5c4532de3d..f6537b50b7 100644
--- a/app/Livewire/Importer.php
+++ b/app/Livewire/Importer.php
@@ -819,6 +819,22 @@ class Importer extends Component
return;
}
+ $path = config('app.private_uploads').'/imports/'.$this->activeFile->file_path;
+ if (! is_file($path)) {
+ $this->message = trans('admin/hardware/message.import.file_missing_on_disk');
+ $this->message_type = 'danger';
+
+ return;
+ }
+
+ $this->activeFileRowCount = $this->countActiveFileRows();
+ if ($this->activeFileRowCount === 0) {
+ $this->message = trans('admin/hardware/message.import.file_empty');
+ $this->message_type = 'danger';
+
+ return;
+ }
+
$this->headerRow = $this->activeFile->header_row;
$this->typeOfImport = $this->activeFile->import_type;
@@ -834,7 +850,6 @@ class Importer extends Component
$this->file_id = $id;
$this->import_errors = null;
$this->statusText = null;
- $this->activeFileRowCount = $this->countActiveFileRows();
$this->wizardStep = 1;
$this->previewRows = [];
$this->processing = false;
@@ -1051,6 +1066,9 @@ class Importer extends Component
$rows = [];
foreach ($reader->getRecords() as $row) {
+ if (self::rowIsBlank($row)) {
+ continue;
+ }
$rows[] = $row;
if (count($rows) >= self::PREVIEW_ROW_LIMIT) {
break;
@@ -1064,10 +1082,11 @@ class Importer extends Component
}
/**
- * Count the number of data rows (excluding the header row) in the
- * currently active file's CSV. Returns 0 if the file is missing or the
- * CSV can't be read - the modal will render "0 rows" and the caller
- * can still choose to cancel out.
+ * Count the number of NON-BLANK data rows in the currently active file's
+ * CSV. Rows where every cell is empty (like ",,,,,,") are excluded so
+ * a file that is technically 50 rows tall but has nothing importable
+ * counts as 0 and the wizard's file_empty guard refuses to open. Returns
+ * 0 also when the file is missing or the CSV can't be read.
*/
private function countActiveFileRows(): int
{
@@ -1084,12 +1103,36 @@ class Importer extends Component
$reader = Reader::createFromPath($path);
$reader->setHeaderOffset(0);
- return iterator_count($reader->getRecords());
+ $count = 0;
+ foreach ($reader->getRecords() as $row) {
+ if (! self::rowIsBlank($row)) {
+ $count++;
+ }
+ }
+
+ return $count;
} catch (\Throwable $e) {
return 0;
}
}
+ /**
+ * True when every value in the CSV row is an empty string (after trim).
+ * Used to skip cells like ",,,,,,,," that carry no information but pad
+ * the file length and would otherwise inflate row counts, appear in the
+ * preview, and dispatch pointless slices to the server on Process.
+ */
+ private static function rowIsBlank(array $row): bool
+ {
+ foreach ($row as $value) {
+ if (trim((string) $value) !== '') {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
public function destroy($id)
{
$this->authorize('import');
@@ -1234,6 +1277,11 @@ class Importer extends Component
* superuser). Kept as a method so the view can guard both the row
* checkbox and the singular delete button consistently.
*/
+ public function fileMissingOnDisk(Import $import): bool
+ {
+ return ! is_file(config('app.private_uploads').'/imports/'.$import->file_path);
+ }
+
public function canDeleteFile(Import $import): bool
{
return auth()->user()->id === $import->created_by || auth()->user()->isSuperUser();
diff --git a/resources/lang/en-US/admin/hardware/message.php b/resources/lang/en-US/admin/hardware/message.php
index ad940b78a2..723e3ae82f 100644
--- a/resources/lang/en-US/admin/hardware/message.php
+++ b/resources/lang/en-US/admin/hardware/message.php
@@ -90,9 +90,17 @@ return [
'select_row' => 'Select :file for bulk delete',
],
'row_count' => '{0} No data rows in this file|{1} :count data row to import|[2,*] :count data rows to import',
+ 'summary' => [
+ 'created' => 'Created',
+ 'updated' => 'Updated',
+ 'skipped' => 'Skipped as duplicates',
+ 'errored' => 'Errored',
+ 'no_changes' => 'The import finished but nothing was created or updated. Every row was skipped, usually because the underlying records already existed. Check the counts below and adjust the CSV or import type if that is not what you expected.',
+ ],
+ 'update_mode_help' => 'When enabled, existing records matched by identity (serial, asset tag, username, etc.) are updated instead of skipped. Any column in your CSV with an empty value will clear the corresponding field on the existing record. Columns you leave out of your CSV entirely are not touched, so existing values are preserved. Required fields (like name and seats on a license) cannot be cleared. Leaving them empty will produce a validation error for that row.',
'type_required' => 'Please select an import type before continuing.',
'processing' => 'Processing your import. Please wait until this finishes before closing the page.',
- 'backup_running' => 'Running backup before importing. This can take a while on larger installs. Please wait.',
+ 'backup_running' => 'Running backup before importing. This can take a while on larger files. Please wait.',
'backup_label' => 'Pre-import backup',
'backup_complete' => 'Backup complete',
'import_label' => 'Import',
diff --git a/resources/views/livewire/importer.blade.php b/resources/views/livewire/importer.blade.php
index 6422ff935a..f4c7593866 100644
--- a/resources/views/livewire/importer.blade.php
+++ b/resources/views/livewire/importer.blade.php
@@ -149,7 +149,11 @@
</td>
<td>
- @if ((auth()->user()->id == $currentFile->adminuser?->id) || (auth()->user()->isSuperUser()))
+ @if ($this->fileMissingOnDisk($currentFile))
+ <span class="text-danger" style="text-decoration: line-through;" data-tooltip="true" title="{{ trans('general.file_does_not_exist') }}">
+ <x-icon type="x" /> {{ $currentFile->file_path }}
+ </span>
+ @elseif ((auth()->user()->id == $currentFile->adminuser?->id) || (auth()->user()->isSuperUser()))
<a href="{{ route('imports.download', $currentFile) }}">{{ $currentFile->file_path }}</a>
@else
{{ $currentFile->file_path }}
@@ -180,10 +184,17 @@
</td>
<td>{{ Helper::formatFilesizeUnits($currentFile->filesize) }}</td>
<td class="col-md-1 text-right" style="white-space: nowrap;">
- <button class="btn btn-sm btn-info" wire:click="selectFile({{ $currentFile->id }})" data-tooltip="true" data-title="{{ trans('general.import_this_file') }}">
- <i class="fa-solid fa-list-check" aria-hidden="true"></i>
- <span class="sr-only">{{ trans('general.import') }}</span>
- </button>
+ @if ($this->fileMissingOnDisk($currentFile))
+ <button class="btn btn-sm btn-info disabled" disabled data-tooltip="true" data-title="{{ trans('general.file_does_not_exist') }}">
+ <i class="fa-solid fa-list-check" aria-hidden="true"></i>
+ <span class="sr-only">{{ trans('general.import') }}</span>
+ </button>
+ @else
+ <button class="btn btn-sm btn-info" wire:click="selectFile({{ $currentFile->id }})" data-tooltip="true" data-title="{{ trans('general.import_this_file') }}">
+ <i class="fa-solid fa-list-check" aria-hidden="true"></i>
+ <span class="sr-only">{{ trans('general.import') }}</span>
+ </button>
+ @endif
@if (((auth()->user()->id == $currentFile->adminuser?->id) || (auth()->user()->isSuperUser())) && ! config('app.lock_passwords'))
<a href="#" wire:click.prevent="$set('activeFileId',null)" data-tooltip="true" data-title="{{ trans('general.delete') }}">
@@ -397,6 +408,7 @@
<x-form.checkbox-row
name="update"
:label="trans('general.update_existing_values')"
+ :help_text="trans('admin/hardware/message.import.update_mode_help')"
:checked="(bool) $update"
wire:model.live="update"
/>
@@ -1021,6 +1033,22 @@
var aggregatedErrors = {};
var lastRedirectUrl = null;
var anySliceFailed = false;
+ var aggregatedTally = {created: 0, updated: 0, skipped: 0, errored: 0};
+
+ function addTally(tally) {
+ if (!tally) return;
+ aggregatedTally.created += tally.created || 0;
+ aggregatedTally.updated += tally.updated || 0;
+ aggregatedTally.skipped += tally.skipped || 0;
+ aggregatedTally.errored += tally.errored || 0;
+ }
+
+ function tallySummaryHtml() {
+ return '{{ trans('admin/hardware/message.import.summary.created') }}: <strong>' + aggregatedTally.created + '</strong>' +
+ ' | {{ trans('admin/hardware/message.import.summary.updated') }}: <strong>' + aggregatedTally.updated + '</strong>' +
+ ' | {{ trans('admin/hardware/message.import.summary.skipped') }}: <strong>' + aggregatedTally.skipped + '</strong>' +
+ ' | {{ trans('admin/hardware/message.import.summary.errored') }}: <strong>' + aggregatedTally.errored + '</strong>';
+ }
function processSlice(sliceIndex) {
var offset = sliceIndex * SLICE_SIZE;
@@ -1076,6 +1104,9 @@
if (body && body.messages && body.messages.redirect_url) {
lastRedirectUrl = body.messages.redirect_url;
}
+ if (body && body.payload && body.payload.tally) {
+ addTally(body.payload.tally);
+ }
// Slice 0's response is our earliest signal
// that the sync backup has finished on the
// server (it runs at the top of process()
@@ -1098,6 +1129,9 @@
$wire.markBackupComplete();
}
var body = jqXHR.responseJSON;
+ if (body && body.payload && body.payload.tally) {
+ addTally(body.payload.tally);
+ }
if (body && body.status === 'import-errors' && body.messages) {
// Merge each slice's per-row messages flat
// into the aggregate map. The server
@@ -1141,12 +1175,14 @@
chain.always(function () {
$wire.$set('progress', 100);
+ var somethingLanded = aggregatedTally.created > 0 || aggregatedTally.updated > 0;
+
if (anySliceFailed) {
$wire.$set('progress_bar_class', 'progress-bar-danger');
$wire.$dispatch('importError', aggregatedErrors);
$wire.$set('import_errors', aggregatedErrors);
$wire.$set('statusType', 'error');
- $wire.$set('statusText', "Some slices failed. Successful slices were still committed.");
+ $wire.$set('statusText', "Some slices failed. Successful slices were still committed.<br>" + tallySummaryHtml());
// Reset processing so the modal footer's Back
// button reappears and the user can retry or
// navigate away rather than being trapped in
@@ -1154,28 +1190,37 @@
$wire.stopProcessing();
$wire.$set('activeFileId', null);
$('#importMappingModal').modal('hide');
+ return;
}
- else {
- $wire.$set('progress_bar_class', 'progress-bar-success');
- // Deliberately not setting statusText here.
- // The two bars going green (backup + import)
- // already communicate "done"; the extra
- // alert-success box was reading as a third
- // green progress rectangle stacked above
- // them. The 800ms setTimeout below still
- // gives the user time to see the completed
- // bars before the browser navigates.
- if (lastRedirectUrl) {
- // Tiny CSVs complete so fast that the
- // success flash never renders before the
- // browser navigates. Hold the redirect
- // for ~800ms so the user actually sees
- // the green bar + "success, redirecting"
- // message.
- setTimeout(function () {
- window.location.href = lastRedirectUrl;
- }, 800);
- }
+
+ $wire.$set('progress_bar_class', 'progress-bar-success');
+
+ // If nothing was created or updated (every row was skipped
+ // as a duplicate, typically), stop and surface the summary
+ // instead of redirecting - a silent 0-row-import looks
+ // broken but is usually the user re-importing a file whose
+ // rows already landed the first time.
+ if (!somethingLanded) {
+ $wire.$set('statusType', 'error');
+ $wire.$set('statusText',
+ '{{ trans('admin/hardware/message.import.summary.no_changes') }}<br>' + tallySummaryHtml()
+ );
+ $wire.stopProcessing();
+ $wire.$set('activeFileId', null);
+ $('#importMappingModal').modal('hide');
+ return;
+ }
+
+ // Rows landed - show the summary briefly, then redirect.
+ // 2500ms is enough to read the counts without being
+ // obnoxious. Longer than the previous 800ms because the
+ // summary is now user-relevant, not decorative.
+ $wire.$set('statusType', 'success');
+ $wire.$set('statusText', tallySummaryHtml());
+ if (lastRedirectUrl) {
+ setTimeout(function () {
+ window.location.href = lastRedirectUrl;
+ }, 2500);
}
});
});
diff --git a/sample_csvs/blank-licenses-sample.csv b/sample_csvs/blank-licenses-sample.csv
new file mode 100644
index 0000000000..1cc001d4db
--- /dev/null
+++ b/sample_csvs/blank-licenses-sample.csv
@@ -0,0 +1 @@
+Full Name,Email,Username,Item name,serial number,Category,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,notes
\ No newline at end of file
diff --git a/sample_csvs/licenses-sample.csv b/sample_csvs/licenses-sample.csv
index 57b9ddca12..f215dd8f11 100644
--- a/sample_csvs/licenses-sample.csv
+++ b/sample_csvs/licenses-sample.csv
@@ -1,148 +1,88 @@
Full Name,Email,Username,Item name,serial number,Category,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,notes
-Bevon Ibarra,[email protected],jgoodsell0,"Acetaminophen, Chlorpheniramine maleate, Phenylephrine HCl",4c2713a1-5b73-4ecb-b2e9-62bf0ff57165,Reverse-engineered incremental migration,Mayer-Bergnaum,11/24/2008,$12.58,34197,749317252-8,Jelene Goodsell,[email protected],02/26/2016,false,yes,56,Gislason-Hagenes,Treutel Inc,"Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
-
-Proin interdum mauris non ligula pellentesque ultrices. Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl."
-Brant Turley,[email protected],estrowan1,Mirtazapine,9dda5116-ec27-4a64-a566-1cb06513460f,Grass-roots system-worthy focus group,,12/27/1981,$41.70,,420038879-0,Ericka Strowan,[email protected],04/12/2016,false,no,55,,,
-Gilligan O'Kinneally,[email protected],kgillet2,"Aconitum napellus, Arsenicum album, Coffea cruda, Euphorbium officinarum, Gnaphalium polycephalum, Hypericum perforatum, Magnesia phosphorica, Passiflora incarnata, Ranunculus bulbosus,",e93c361f-1cf3-4fc3-bfeb-f3dee49452fc,Right-sized 4th generation instruction set,Schmeler Group,04/13/1989,$66.07,64491,398520367-9,Kevon Gillet,[email protected],04/03/2016,true,yes,23,Hodkiewicz LLC,Lakin-Sauer,"Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum. Integer a nibh.
-
-In quis justo. Maecenas rhoncus aliquam lacus. Morbi quis tortor id nulla ultrices aliquet.
-
-Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui."
-Cathy Vanini,[email protected],mferreo3,Gabapentin,e04d59af-7a42-468d-b11c-83b4c1fa2ee3,Pre-emptive solution-oriented adapter,Mertz and Sons,11/18/1981,$15.74,20450,272222159-4,Mario Ferreo,[email protected],09/17/2016,true,no,48,Herman and Sons,"Schuppe, Johnson and Heller","Nulla ut erat id mauris vulputate elementum. Nullam varius. Nulla facilisi.
-
-Cras non velit nec nisi vulputate nonummy. Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque."
-Lorene Lambrecht,[email protected],aimm4,Doxazosin Mesylate,89da2922-3639-4654-8c3e-58a8b95db32c,Monitored intermediate service-desk,Mayert-Homenick,02/23/1998,$78.19,69356,027802149-2,Alaster Imm,[email protected],04/11/2016,true,no,70,Hagenes Inc,"Wehner, Jaskolski and Champlin","Quisque porta volutpat erat. Quisque erat eros, viverra eget, congue eget, semper rutrum, nulla. Nunc purus.
-
-Phasellus in felis. Donec semper sapien a libero. Nam dui."
-Willey Mattityahou,[email protected],rjanaszkiewicz5,Loperamide Hydrochloride,5180a72a-9978-41e9-89cb-f5b6913a7d89,Focused secondary product,Ortiz Inc,12/15/2008,$15.75,69285,953084568-5,Reggie Janaszkiewicz,[email protected],06/12/2016,false,FALSE,16,Lockman and Sons,Braun LLC,"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin risus. Praesent lectus.
-
-Vestibulum quam sapien, varius ut, blandit non, interdum in, ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis."
-Mignonne Kirkup,[email protected],jlepiscopio6,Fluorescein Sodium,9001ff29-fbda-4095-944b-7a371179e5a6,Triple-buffered client-server conglomeration,,12/10/2007,$85.82,,514100350-7,Jereme L'Episcopio,[email protected],12/17/2016,false,TRUE,7,,,
-Cate McGavin,[email protected],aprobbings7,OCTINOXATE and TITANIUM DIOXIDE,1b7fd855-55d9-4034-9899-42a9095d3cde,Robust background circuit,Runte-Hartmann,01/29/1998,$64.32,41152,997334813-3,Alaric Probbings,[email protected],05/14/2016,false,true,78,Leffler Group,"Grady, Crona and Luettgen",Aenean lectus. Pellentesque eget nunc. Donec quis orci eget orci vehicula condimentum.
-Bradan Sipson,[email protected],lalliban8,"Apis Mellifica, Arsenicum Album, Borax, Capsicum Annuum, Graphites, Mentha piperita, Mezereum, Natrum muriaticum, Nux vomica, Petroleum, Ranunculus bulbosus",d420f5cf-36bb-43e7-9c1d-0e7703e492fd,Public-key dedicated service-desk,Botsford-Boyle,05/30/2000,$25.15,93671,462155625-8,Lukas Alliban,[email protected],11/03/2016,true,false,30,Brakus-Gaylord,Auer Group,"Vestibulum ac est lacinia nisi venenatis tristique. Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat.
-
-In congue. Etiam justo. Etiam pretium iaculis justo."
-Gare Paddison,[email protected],cogan9,DOCUSATE SODIUM,3025458b-920e-4c05-ad8b-f42e047f2dde,Assimilated optimal circuit,Tremblay LLC,02/18/1982,$82.42,28468,295163448-X,Cassi Ogan,[email protected],11/08/2016,true,yes,92,"McDermott, DuBuque and Rau",Glover-Emard,"Vestibulum ac est lacinia nisi venenatis tristique. Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat.
-
-In congue. Etiam justo. Etiam pretium iaculis justo.
-
-In hac habitasse platea dictumst. Etiam faucibus cursus urna. Ut tellus."
-Brennan Danielski,[email protected],stomasicchioa,Rosuvastatin calcium,b4ee3922-378c-4131-874f-8ebc5d280bc5,Object-based content-based secured line,"Ledner, Torphy and Schmitt",02/26/1986,$17.12,90269,401008001-9,Steffi Tomasicchio,[email protected],12/13/2016,false,sometimes,49,"Mueller, Ernser and Smitham","Lemke, O'Kon and Hills","Nulla ut erat id mauris vulputate elementum. Nullam varius. Nulla facilisi.
-
-Cras non velit nec nisi vulputate nonummy. Maecenas tincidunt lacus at velit. Vivamus vel nulla eget eros elementum pellentesque."
-Melody Harbidge,[email protected],bgoomsb,"fluocinolone acetonide, hydroquinone, and tretinoin",01ec85ac-5473-4ee0-a988-0864dfd6722d,Vision-oriented bifurcated system engine,"Farrell, Treutel and Haag",01/14/1985,$56.03,83323,433717940-2,Becki Gooms,[email protected],09/17/2016,false,true,32,Sawayn-Larson,"Nolan, O'Keefe and Wiza","Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
-
-Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris."
-Winifred Clough,[email protected],tchiversc,"Avobenzone, Octocrylene, Phenylbenzimidazole Sulfonic Acid",8bbc431f-b571-4912-9cc6-64c08512f1f2,Cloned 3rd generation function,Harvey-Hickle,11/05/2016,$45.82,76764,733010158-3,Tan Chivers,[email protected],01/22/2016,true,NO,73,O'Connell-Klocko,Nikolaus-McGlynn,"Curabitur at ipsum ac tellus semper interdum. Mauris ullamcorper purus sit amet nulla. Quisque arcu libero, rutrum ac, lobortis vel, dapibus at, diam."
-Hermine Vischi,[email protected],tdreusd,BENZALKONIUM CHLORIDE,97e50f8b-270f-4d67-b191-1e015096d472,Compatible encompassing matrix,Bernier and Sons,04/14/2014,$97.46,78245,392918422-2,Teddi Dreus,[email protected],02/16/2016,false,no,92,"Renner, McCullough and Walsh","Collier, Schuster and Block","Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius.
-
-Integer ac leo. Pellentesque ultrices mattis odio. Donec vitae nisi."
-Georgina O'Cullinane,[email protected],gsupplee,PHENYLEPHRINE HYDROCHLORIDE,e1d8e28c-d543-42db-a7b6-cb1128a8effd,Synergistic optimal orchestration,Crist Inc,05/13/1987,$15.81,59115,712672732-1,Grace Supple,[email protected],05/04/2016,true,TRUE,39,Weber LLC,Schuppe-Runolfsdottir,"Phasellus in felis. Donec semper sapien a libero. Nam dui.
-
-Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius."
-Malory Charlotte,[email protected],stemplarf,"Acetaminophen, Dextromethorphan HBr, Doxylamine succinate",23f475d3-74a5-43eb-8cd9-345f6ddfb423,Customer-focused optimizing product,Ruecker-Zemlak,09/14/1981,$44.86,21142,438762010-2,Sigfried Templar,[email protected],04/02/2016,false,NO,53,Graham-King,Collier LLC,"Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
-
-Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.
-
-Morbi non lectus. Aliquam sit amet diam in magna bibendum imperdiet. Nullam orci pede, venenatis non, sodales sed, tincidunt eu, felis."
-Nat Overthrow,[email protected],jkiendlg,Isopropyl Alcohol,4f40fa12-f799-4029-8a30-71aca4fab9be,Extended 3rd generation firmware,,12/14/2014,$52.86,,339064626-4,Jonathon Kiendl,[email protected],07/07/2016,false,true,29,,,
-Tana Middleditch,[email protected],osheardh,OCTINOXATE OCTISALATE TITANIUM DIOXIDE,23b40848-16fb-4023-a94b-5be44c080a88,Ameliorated needs-based data-warehouse,Reichert-Ebert,12/27/2010,$89.06,67203,061661177-3,Obed Sheard,[email protected],08/25/2016,false,,2,O'Connell Group,"Wolff, Wehner and Oberbrunner","Maecenas ut massa quis augue luctus tincidunt. Nulla mollis molestie lorem. Quisque ut erat.
-
-Curabitur gravida nisi at nibh. In hac habitasse platea dictumst. Aliquam augue quam, sollicitudin vitae, consectetuer eget, rutrum at, lorem."
-Giffer Tarling,[email protected],vbasterfieldi,Hydralazine Hydrochloride,1fb3906f-8730-4dda-b8b7-896fdf092c4a,Streamlined dynamic hardware,,10/15/2005,$20.71,,433426291-0,Victor Basterfield,[email protected],09/08/2016,false,YES,79,,,
-Doug Penquet,[email protected],karblasterj,Homeopathic Liquid,dcc764ec-011b-4fc1-abd3-e360089581b4,Ameliorated client-driven secured line,Hills and Sons,01/17/1995,$48.64,38562,003915810-1,Korey Arblaster,[email protected],07/17/2016,true,true,69,"Smith, Corwin and Schroeder",Goyette-Goodwin,In hac habitasse platea dictumst. Etiam faucibus cursus urna. Ut tellus.
-Tiphanie Witton,[email protected],selsayk,oxybutynin chloride,aad1618a-3d49-46d7-90da-c19503f927f8,Inverse mission-critical model,O'Keefe Group,03/06/1984,$78.97,80346,255771806-8,Stefanie Elsay,[email protected],01/22/2016,false,,6,Spencer-Torp,Ullrich Inc,"Vestibulum ac est lacinia nisi venenatis tristique. Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat.
-
-In congue. Etiam justo. Etiam pretium iaculis justo."
-Gibby Biford,[email protected],bemblinl,Acyclovir,e40d7183-eebe-47c6-9ec6-e54c36a80096,Profit-focused incremental orchestration,Buckridge Group,,$46.88,56260,426095673-6,Bron Emblin,[email protected],08/28/2016,true,no,94,Zemlak-Kreiger,Mante-Hessel,"Phasellus sit amet erat. Nulla tempus. Vivamus in felis eu sapien cursus vestibulum.
-
-Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem.
-
-Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit."
-Hymie Cameron,[email protected],vdallonm,losartan potassium,bf6a7eef-d6a5-4d06-ab63-631841deb014,Enhanced mission-critical functionalities,,03/25/2003,$85.19,,966275591-8,Venus Dallon,[email protected],11/04/2016,false,yes,6,,,
-Jeanette Clowes,[email protected],bhartlandn,Benzalkonium Chloride,e5dbc5e2-bd36-48c4-93a6-2002fa82e38f,Assimilated tangible functionalities,"Grady, Bernhard and Yost",12/02/1994,$53.96,45800,089164796-1,Brandtr Hartland,[email protected],05/30/2016,true,NO,33,Schmeler-McKenzie,"Moen, Purdy and Schultz","In congue. Etiam justo. Etiam pretium iaculis justo.
-
-In hac habitasse platea dictumst. Etiam faucibus cursus urna. Ut tellus."
-Diane Larmet,[email protected],tallabartono,ASARUM EUROPAEUM,db26726d-02d7-46de-9fef-72537b8f5e73,Centralized 24 hour data-warehouse,"Altenwerth, Wuckert and Feest",11/02/1999,$32.31,39634,983426091-1,Tremayne Allabarton,[email protected],08/15/2016,true,no,26,"Beahan, Koch and Heidenreich",Kirlin-Bruen,"Morbi porttitor lorem id ligula. Suspendisse ornare consequat lectus. In est risus, auctor sed, tristique in, tempus sit amet, sem."
-Alley Shyre,[email protected],bdurbridgep,loperamide HCl,9f659b3d-3ca7-442b-b9f9-85df21738d20,Customizable stable core,Weimann Inc,,$47.90,73216,483676849-7,Bridget Durbridge,[email protected],07/20/2016,false,TRUE,13,"Mosciski, Wolf and Bruen",Will Group,"Fusce posuere felis sed lacus. Morbi sem mauris, laoreet ut, rhoncus aliquet, pulvinar sed, nisl. Nunc rhoncus dui vel sem.
-
-Sed sagittis. Nam congue, risus semper porta volutpat, quam pede lobortis ligula, sit amet eleifend pede libero quis orci. Nullam molestie nibh in lectus."
-Karine Philipard,[email protected],amcilwraithq,Nifedipine,f8e28161-ee5c-4e90-9276-8928d8a1fe45,Re-engineered clear-thinking instruction set,"Kiehn, Auer and Cruickshank",10/13/1994,$29.88,95585,584880185-1,Annabal McIlwraith,[email protected],06/16/2016,true,sometimes,57,Bauch and Sons,Hartmann Inc,"Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
-
-Proin interdum mauris non ligula pellentesque ultrices. Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl.
-
-Aenean lectus. Pellentesque eget nunc. Donec quis orci eget orci vehicula condimentum."
-Tate Beckson,[email protected],hcordenr,NITROGLYCERIN,23b9128a-080d-40f1-bc9d-ed9f35d15c63,Virtual solution-oriented benchmark,"Ruecker, Hilll and Dicki",06/23/1999,$83.48,11095,779580200-1,Hercule Corden,[email protected],02/07/2016,true,yes,72,Bahringer and Sons,Aufderhar-Hudson,"Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius.
-
-Integer ac leo. Pellentesque ultrices mattis odio. Donec vitae nisi.
-
-Nam ultrices, libero non mattis pulvinar, nulla pede ullamcorper augue, a suscipit nulla elit ac nulla. Sed vel enim sit amet nunc viverra dapibus. Nulla suscipit ligula in lacus."
-Davide Garrioch,[email protected],abeacocks,PYRETHRUM CINERARIIFOLIUM,348dc629-504f-4266-9d12-93ec1a51b5de,Vision-oriented coherent standardization,,12/04/2000,$32.19,,836520830-X,Adrianne Beacock,[email protected],03/10/2016,true,,13,,,
-Johny Toll,[email protected],wleveringtont,Oxycodone Hydrochloride and Acetaminophen,a8e9517c-eb63-4743-8eaf-11fe9f76dc60,Multi-lateral next generation archive,Wiza-Haley,04/22/2004,$0.41,21378,607407045-8,Wallache Leverington,[email protected],05/13/2016,false,TRUE,23,"Steuber, Hoppe and Bruen",Rempel Inc,"Duis consequat dui nec nisi volutpat eleifend. Donec ut dolor. Morbi vel lectus in quam fringilla rhoncus.
-
-Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis. Integer aliquet, massa id lobortis convallis, tortor risus dapibus augue, vel accumsan tellus nisi eu orci. Mauris lacinia sapien quis libero.
-
-Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum. Integer a nibh."
-Anne-corinne Curless,[email protected],cstrydeu,Atorvastatin Calcium,45d86ea6-0012-4970-bba3-6432f03553d6,Sharable 3rd generation forecast,"Rowe, Cartwright and Wiza",06/07/2003,$55.55,88475,970951097-5,Coral Stryde,[email protected],07/01/2016,false,sometimes,43,Balistreri LLC,Wolf-Torphy,"Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.
-
-Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque."
-Norine Brakewell,[email protected],ccathesyedv,"Gum, Sweet Liquidambar styraciflua",15741b10-c48b-455e-b225-5020da01a93b,Customer-focused optimal system engine,Hayes Inc,01/02/2011,$92.63,48656,236374986-3,Carolina Cathesyed,[email protected],05/15/2016,true,yes,60,Botsford-Rodriguez,"Stiedemann, Kemmer and Brown","Vestibulum quam sapien, varius ut, blandit non, interdum in, ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis.
-
-Duis consequat dui nec nisi volutpat eleifend. Donec ut dolor. Morbi vel lectus in quam fringilla rhoncus.
-
-Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis. Integer aliquet, massa id lobortis convallis, tortor risus dapibus augue, vel accumsan tellus nisi eu orci. Mauris lacinia sapien quis libero."
-Bessy Ingerfield,[email protected],rifflandw,GLYCERIN,316812d7-41ff-42aa-8d1a-ffc6befda3b0,Seamless secondary emulation,Wilderman-Zemlak,05/02/1983,$78.78,95469,169865158-9,Raine Iffland,[email protected],04/18/2016,false,TRUE,59,Reynolds Group,Rodriguez-McClure,"Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
+Bevon Ibarra,[email protected],jgoodsell0,Phenylephrine HCl,4c2713a1-5b73-4ecb-b2e9-62bf0ff57165,Reverse-engineered incremental migration,Mayer-Bergnaum,11/24/08,$12.58 ,34197,749317252-8,Jelene Goodsell,[email protected],,FALSE,yes,56,Gislason-Hagenes,Treutel Inc,Sample import note
+Brant Turley,[email protected],estrowan1,Mirtazapine,9dda5116-ec27-4a64-a566-1cb06513460f,Grass-roots system-worthy focus group,,12/27/81,$41.70 ,,420038879-0,Ericka Strowan,[email protected],,FALSE,no,55,,,Sample import note
+Gilligan O'Kinneally,[email protected],kgillet2,Arsenicum album,e93c361f-1cf3-4fc3-bfeb-f3dee49452fc,Right-sized 4th generation instruction set,Schmeler Group,4/13/89,$66.07 ,64491,398520367-9,Kevon Gillet,[email protected],,TRUE,yes,23,Hodkiewicz LLC,Lakin-Sauer,Sample import note
+Cathy Vanini,[email protected],mferreo3,Gabapentin,e04d59af-7a42-468d-b11c-83b4c1fa2ee3,Pre-emptive solution-oriented adapter,Mertz and Sons,11/18/81,$15.74 ,20450,272222159-4,Mario Ferreo,[email protected],,TRUE,no,48,Herman and Sons,"Schuppe, Johnson and Heller",Sample import note
+Lorene Lambrecht,[email protected],aimm4,Doxazosin Mesylate,89da2922-3639-4654-8c3e-58a8b95db32c,Monitored intermediate service-desk,Mayert-Homenick,2/23/98,$78.19 ,69356,027802149-2,Alaster Imm,[email protected],,TRUE,no,70,Hagenes Inc,"Wehner, Jaskolski and Champlin",Sample import note
+Willey Mattityahou,[email protected],rjanaszkiewicz5,Loperamide Hydrochloride,5180a72a-9978-41e9-89cb-f5b6913a7d89,Focused secondary product,Ortiz Inc,12/15/08,$15.75 ,69285,953084568-5,Reggie Janaszkiewicz,[email protected],,FALSE,FALSE,16,Lockman and Sons,Braun LLC,Sample import note
+Mignonne Kirkup,[email protected],jlepiscopio6,Fluorescein Sodium,9001ff29-fbda-4095-944b-7a371179e5a6,Triple-buffered client-server conglomeration,,12/10/07,$85.82 ,,514100350-7,Jereme L'Episcopio,[email protected],,FALSE,TRUE,7,,,Sample import note
+Cate McGavin,[email protected],aprobbings7,OCTINOXATE and TITANIUM DIOXIDE,1b7fd855-55d9-4034-9899-42a9095d3cde,Robust background circuit,Runte-Hartmann,1/29/98,$64.32 ,41152,997334813-3,Alaric Probbings,[email protected],,FALSE,TRUE,78,Leffler Group,"Grady, Crona and Luettgen",Sample import note
+Bradan Sipson,[email protected],lalliban8,Borax,d420f5cf-36bb-43e7-9c1d-0e7703e492fd,Public-key dedicated service-desk,Botsford-Boyle,5/30/00,$25.15 ,93671,462155625-8,Lukas Alliban,[email protected],,TRUE,FALSE,30,Brakus-Gaylord,Auer Group,Sample import note
+Gare Paddison,[email protected],cogan9,DOCUSATE SODIUM,3025458b-920e-4c05-ad8b-f42e047f2dde,Assimilated optimal circuit,Tremblay LLC,2/18/82,$82.42 ,28468,295163448-X,Cassi Ogan,[email protected],,TRUE,yes,92,"McDermott, DuBuque and Rau",Glover-Emard,Sample import note
+Brennan Danielski,[email protected],stomasicchioa,Rosuvastatin calcium,b4ee3922-378c-4131-874f-8ebc5d280bc5,Object-based content-based secured line,"Ledner, Torphy and Schmitt",2/26/86,$17.12 ,90269,401008001-9,Steffi Tomasicchio,[email protected],,FALSE,sometimes,49,"Mueller, Ernser and Smitham","Lemke, O'Kon and Hills",Sample import note
+Melody Harbidge,[email protected],bgoomsb,"fluocinolone acetonide, hydroquinone, and tretinoin",01ec85ac-5473-4ee0-a988-0864dfd6722d,Vision-oriented bifurcated system engine,"Farrell, Treutel and Haag",1/14/85,$56.03 ,83323,433717940-2,Becki Gooms,[email protected],,FALSE,TRUE,32,Sawayn-Larson,"Nolan, O'Keefe and Wiza",Sample import note
+Winifred Clough,[email protected],tchiversc,"Avobenzone, Octocrylene, Phenylbenzimidazole Sulfonic Acid",8bbc431f-b571-4912-9cc6-64c08512f1f2,Cloned 3rd generation function,Harvey-Hickle,11/5/16,$45.82 ,76764,733010158-3,Tan Chivers,[email protected],,TRUE,NO,73,O'Connell-Klocko,Nikolaus-McGlynn,Sample import note
+Hermine Vischi,[email protected],tdreusd,BENZALKONIUM CHLORIDE,97e50f8b-270f-4d67-b191-1e015096d472,Compatible encompassing matrix,Bernier and Sons,4/14/14,$97.46 ,78245,392918422-2,Teddi Dreus,[email protected],,FALSE,no,92,"Renner, McCullough and Walsh","Collier, Schuster and Block",Sample import note
+Georgina O'Cullinane,[email protected],gsupplee,PHENYLEPHRINE HYDROCHLORIDE,e1d8e28c-d543-42db-a7b6-cb1128a8effd,Synergistic optimal orchestration,Crist Inc,5/13/87,$15.81 ,59115,712672732-1,Grace Supple,[email protected],,TRUE,TRUE,39,Weber LLC,Schuppe-Runolfsdottir,Sample import note
+Malory Charlotte,[email protected],stemplarf,"Acetaminophen, Dextromethorphan HBr, Doxylamine succinate",23f475d3-74a5-43eb-8cd9-345f6ddfb423,Customer-focused optimizing product,Ruecker-Zemlak,9/14/81,$44.86 ,21142,438762010-2,Sigfried Templar,[email protected],,FALSE,NO,53,Graham-King,Collier LLC,Sample import note
+Nat Overthrow,[email protected],jkiendlg,Isopropyl Alcohol,4f40fa12-f799-4029-8a30-71aca4fab9be,Extended 3rd generation firmware,,12/14/14,$52.86 ,,339064626-4,Jonathon Kiendl,[email protected],,FALSE,TRUE,29,,,Sample import note
+Tana Middleditch,[email protected],osheardh,OCTINOXATE OCTISALATE TITANIUM DIOXIDE,23b40848-16fb-4023-a94b-5be44c080a88,Ameliorated needs-based data-warehouse,Reichert-Ebert,12/27/10,$89.06 ,67203,061661177-3,Obed Sheard,[email protected],,FALSE,,2,O'Connell Group,"Wolff, Wehner and Oberbrunner",Sample import note
+Giffer Tarling,[email protected],vbasterfieldi,Hydralazine Hydrochloride,1fb3906f-8730-4dda-b8b7-896fdf092c4a,Streamlined dynamic hardware,,10/15/05,$20.71 ,,433426291-0,Victor Basterfield,[email protected],,FALSE,YES,79,,,Sample import note
+Doug Penquet,[email protected],karblasterj,Homeopathic Liquid,dcc764ec-011b-4fc1-abd3-e360089581b4,Ameliorated client-driven secured line,Hills and Sons,1/17/95,$48.64 ,38562,003915810-1,Korey Arblaster,[email protected],,TRUE,TRUE,69,"Smith, Corwin and Schroeder",Goyette-Goodwin,Sample import note
+Tiphanie Witton,[email protected],selsayk,oxybutynin chloride,aad1618a-3d49-46d7-90da-c19503f927f8,Inverse mission-critical model,O'Keefe Group,3/6/84,$78.97 ,80346,255771806-8,Stefanie Elsay,[email protected],,FALSE,,6,Spencer-Torp,Ullrich Inc,Sample import note
+Gibby Biford,[email protected],bemblinl,Acyclovir,e40d7183-eebe-47c6-9ec6-e54c36a80096,Profit-focused incremental orchestration,Buckridge Group,,$46.88 ,56260,426095673-6,Bron Emblin,[email protected],,TRUE,no,94,Zemlak-Kreiger,Mante-Hessel,Sample import note
+Hymie Cameron,[email protected],vdallonm,losartan potassium,bf6a7eef-d6a5-4d06-ab63-631841deb014,Enhanced mission-critical functionalities,,3/25/03,$85.19 ,,966275591-8,Venus Dallon,[email protected],,FALSE,yes,6,,,Sample import note
+Jeanette Clowes,[email protected],bhartlandn,Benzalkonium Chloride,e5dbc5e2-bd36-48c4-93a6-2002fa82e38f,Assimilated tangible functionalities,"Grady, Bernhard and Yost",12/2/94,$53.96 ,45800,089164796-1,Brandtr Hartland,[email protected],,TRUE,NO,33,Schmeler-McKenzie,"Moen, Purdy and Schultz",Sample import note
+Diane Larmet,[email protected],tallabartono,ASARUM EUROPAEUM,db26726d-02d7-46de-9fef-72537b8f5e73,Centralized 24 hour data-warehouse,"Altenwerth, Wuckert and Feest",11/2/99,$32.31 ,39634,983426091-1,Tremayne Allabarton,[email protected],,TRUE,no,26,"Beahan, Koch and Heidenreich",Kirlin-Bruen,Sample import note
+Alley Shyre,[email protected],bdurbridgep,loperamide HCl,9f659b3d-3ca7-442b-b9f9-85df21738d20,Customizable stable core,Weimann Inc,,$47.90 ,73216,483676849-7,Bridget Durbridge,[email protected],,FALSE,TRUE,13,"Mosciski, Wolf and Bruen",Will Group,Sample import note
+Karine Philipard,[email protected],amcilwraithq,Nifedipine,f8e28161-ee5c-4e90-9276-8928d8a1fe45,Re-engineered clear-thinking instruction set,"Kiehn, Auer and Cruickshank",10/13/94,$29.88 ,95585,584880185-1,Annabal McIlwraith,[email protected],,TRUE,sometimes,57,Bauch and Sons,Hartmann Inc,Sample import note
+Tate Beckson,[email protected],hcordenr,NITROGLYCERIN,23b9128a-080d-40f1-bc9d-ed9f35d15c63,Virtual solution-oriented benchmark,"Ruecker, Hilll and Dicki",6/23/99,$83.48 ,11095,779580200-1,Hercule Corden,[email protected],,TRUE,yes,72,Bahringer and Sons,Aufderhar-Hudson,Sample import note
+Davide Garrioch,[email protected],abeacocks,PYRETHRUM CINERARIIFOLIUM,348dc629-504f-4266-9d12-93ec1a51b5de,Vision-oriented coherent standardization,,12/4/00,$32.19 ,,836520830-X,Adrianne Beacock,[email protected],,TRUE,,13,,,Sample import note
+Johny Toll,[email protected],wleveringtont,Oxycodone Hydrochloride and Acetaminophen,a8e9517c-eb63-4743-8eaf-11fe9f76dc60,Multi-lateral next generation archive,Wiza-Haley,4/22/04,$0.41 ,21378,607407045-8,Wallache Leverington,[email protected],,FALSE,TRUE,23,"Steuber, Hoppe and Bruen",Rempel Inc,Sample import note
+Anne-corinne Curless,[email protected],cstrydeu,Atorvastatin Calcium,45d86ea6-0012-4970-bba3-6432f03553d6,Sharable 3rd generation forecast,"Rowe, Cartwright and Wiza",6/7/03,$55.55 ,88475,970951097-5,Coral Stryde,[email protected],,FALSE,sometimes,43,Balistreri LLC,Wolf-Torphy,Sample import note
+Norine Brakewell,[email protected],ccathesyedv,"Gum, Sweet Liquidambar styraciflua",15741b10-c48b-455e-b225-5020da01a93b,Customer-focused optimal system engine,Hayes Inc,1/2/11,$92.63 ,48656,236374986-3,Carolina Cathesyed,[email protected],,TRUE,yes,60,Botsford-Rodriguez,"Stiedemann, Kemmer and Brown",Sample import note
+Bessy Ingerfield,[email protected],rifflandw,GLYCERIN,316812d7-41ff-42aa-8d1a-ffc6befda3b0,Seamless secondary emulation,Wilderman-Zemlak,5/2/83,$78.78 ,95469,169865158-9,Raine Iffland,[email protected],,FALSE,TRUE,59,Reynolds Group,Rodriguez-McClure,"Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris."
-Kerstin McGrill,[email protected],fsteinx,Aspirin,0a14ff52-1d8c-450e-86a9-cc2069a4213d,Triple-buffered regional analyzer,"Hauck, O'Hara and Dibbert",07/13/2008,$88.52,69629,236206999-0,Farah Stein,[email protected],02/18/2016,true,true,86,Haag-Bailey,Rau LLC,"Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui.
+Kerstin McGrill,[email protected],fsteinx,Aspirin,0a14ff52-1d8c-450e-86a9-cc2069a4213d,Triple-buffered regional analyzer,"Hauck, O'Hara and Dibbert",7/13/08,$88.52 ,69629,236206999-0,Farah Stein,[email protected],,TRUE,TRUE,86,Haag-Bailey,Rau LLC,"Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui.
Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris."
-Harmonia Scoates,[email protected],sniavesy,ceftazidime,a82f197c-f1ac-4d02-82be-3968427b1bb4,Customer-focused analyzing productivity,Ankunding Group,09/05/2008,$42.54,12643,218498131-1,Sloane Niaves,[email protected],06/30/2016,true,false,4,"Donnelly, Pfeffer and Roberts","Kuvalis, Lubowitz and Zboncak","Praesent id massa id nisl venenatis lacinia. Aenean sit amet justo. Morbi ut odio.
+Harmonia Scoates,[email protected],sniavesy,ceftazidime,a82f197c-f1ac-4d02-82be-3968427b1bb4,Customer-focused analyzing productivity,Ankunding Group,9/5/08,$42.54 ,12643,218498131-1,Sloane Niaves,[email protected],,TRUE,FALSE,4,"Donnelly, Pfeffer and Roberts","Kuvalis, Lubowitz and Zboncak","Praesent id massa id nisl venenatis lacinia. Aenean sit amet justo. Morbi ut odio.
Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Proin interdum mauris non ligula pellentesque ultrices. Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl."
-Ringo Jeffs,[email protected],gdoylyz,"Piperonyl butoxide, Pyrethrum extract",a8f42a80-444a-4bcb-a7e9-38ded2c702c2,Streamlined leading edge groupware,Maggio and Sons,05/13/2000,$74.67,67907,190797448-2,Gene D'Oyly,[email protected],08/04/2016,false,false,2,Kozey-Romaguera,Kovacek-Lebsack,"Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.
+Ringo Jeffs,[email protected],gdoylyz,"Piperonyl butoxide, Pyrethrum extract",a8f42a80-444a-4bcb-a7e9-38ded2c702c2,Streamlined leading edge groupware,Maggio and Sons,5/13/00,$74.67 ,67907,190797448-2,Gene D'Oyly,[email protected],,FALSE,FALSE,2,Kozey-Romaguera,Kovacek-Lebsack,"Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.
Morbi non lectus. Aliquam sit amet diam in magna bibendum imperdiet. Nullam orci pede, venenatis non, sodales sed, tincidunt eu, felis.
Fusce posuere felis sed lacus. Morbi sem mauris, laoreet ut, rhoncus aliquet, pulvinar sed, nisl. Nunc rhoncus dui vel sem."
-Lew Kimmerling,[email protected],ctarbatt10,Allspice,6e358247-071f-478a-8452-28159a9f6da0,Right-sized logistical focus group,"Lakin, Kohler and Rogahn",08/10/1984,$28.33,46894,094697521-3,Charity Tarbatt,[email protected],04/21/2016,true,YES,57,Gislason-Murray,Gerhold LLC,"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin risus. Praesent lectus."
-Zorana Clewett,[email protected],emcgettigan11,"Acetaminophen, Guaifenesin, Phenylephrine HCl",ac38aa40-9e5a-4842-8a56-aabae234d828,User-centric zero defect budgetary management,Graham Inc,05/02/1998,$76.28,43880,258048655-0,Ethelin McGettigan,[email protected],02/06/2016,true,YES,29,Powlowski Group,"Kunze, Jakubowski and Tremblay",Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum. Integer a nibh.
-Wilburt Worrell,[email protected],mdealy12,Nadolol,20e2897c-a8f4-4e33-985a-5de751fa675f,Cross-platform 3rd generation solution,Mayert-Jacobs,06/20/2003,$90.84,69931,295626053-7,Mamie Dealy,[email protected],09/10/2016,false,false,56,Baumbach-Rolfson,"Heidenreich, Harris and Halvorson","Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius.
+Lew Kimmerling,[email protected],ctarbatt10,Allspice,6e358247-071f-478a-8452-28159a9f6da0,Right-sized logistical focus group,"Lakin, Kohler and Rogahn",8/10/84,$28.33 ,46894,094697521-3,Charity Tarbatt,[email protected],,TRUE,YES,57,Gislason-Murray,Gerhold LLC,Sample import note
+Zorana Clewett,[email protected],emcgettigan11,"Acetaminophen, Guaifenesin, Phenylephrine HCl",ac38aa40-9e5a-4842-8a56-aabae234d828,User-centric zero defect budgetary management,Graham Inc,5/2/98,$76.28 ,43880,258048655-0,Ethelin McGettigan,[email protected],,TRUE,YES,29,Powlowski Group,"Kunze, Jakubowski and Tremblay",Sample import note
+Wilburt Worrell,[email protected],mdealy12,Nadolol,20e2897c-a8f4-4e33-985a-5de751fa675f,Cross-platform 3rd generation solution,Mayert-Jacobs,6/20/03,$90.84 ,69931,295626053-7,Mamie Dealy,[email protected],,FALSE,FALSE,56,Baumbach-Rolfson,"Heidenreich, Harris and Halvorson","Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius.
Integer ac leo. Pellentesque ultrices mattis odio. Donec vitae nisi."
-Avie Barnbrook,[email protected],imordan13,GlyBURIDE,78d9f721-6a6f-4b61-9f16-f920330bb413,Progressive transitional parallelism,,09/05/1987,$42.02,,829075761-1,Isa Mordan,[email protected],09/02/2016,false,NO,53,,,
-Godfree Micheli,[email protected],mbonhomme14,Furosemide,8b1cf256-2e75-47d0-9ef1-bd05a7a8aa40,Phased even-keeled moderator,Rath Inc,10/21/2007,$80.18,57057,482496005-3,Marty Bonhomme,[email protected],11/27/2016,false,false,46,Mertz-Jast,Hermann and Sons,"Etiam vel augue. Vestibulum rutrum rutrum neque. Aenean auctor gravida sem.
+Avie Barnbrook,[email protected],imordan13,GlyBURIDE,78d9f721-6a6f-4b61-9f16-f920330bb413,Progressive transitional parallelism,,9/5/87,$42.02 ,,829075761-1,Isa Mordan,[email protected],,FALSE,NO,53,,,
+Godfree Micheli,[email protected],mbonhomme14,Furosemide,8b1cf256-2e75-47d0-9ef1-bd05a7a8aa40,Phased even-keeled moderator,Rath Inc,10/21/07,$80.18 ,57057,482496005-3,Marty Bonhomme,[email protected],,FALSE,FALSE,46,Mertz-Jast,Hermann and Sons,"Etiam vel augue. Vestibulum rutrum rutrum neque. Aenean auctor gravida sem.
Praesent id massa id nisl venenatis lacinia. Aenean sit amet justo. Morbi ut odio.
Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
-Candida Meedendorpe,[email protected],ostallworthy15,Octinoxate and Titanium Dioxide,fdffc27d-b625-4b4c-a037-7225377bb942,Object-based asymmetric migration,"Medhurst, Homenick and Marquardt",01/06/2007,$35.20,18641,456756372-7,Orsola Stallworthy,[email protected],06/10/2016,false,TRUE,56,"Sanford, Oberbrunner and Stracke",Schulist-Senger,Duis bibendum. Morbi non quam nec dui luctus rutrum. Nulla tellus.
-Dotti Fearey,[email protected],pstanners16,Temazepam,87592e58-5628-4d38-a3ae-fb06df901777,Adaptive well-modulated local area network,Murray Group,01/12/1994,$66.92,70036,393533011-1,Paolo Stanners,[email protected],06/12/2016,false,no,69,Crist and Sons,Moore and Sons,"Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui.
+Candida Meedendorpe,[email protected],ostallworthy15,Octinoxate and Titanium Dioxide,fdffc27d-b625-4b4c-a037-7225377bb942,Object-based asymmetric migration,"Medhurst, Homenick and Marquardt",1/6/07,$35.20 ,18641,456756372-7,Orsola Stallworthy,[email protected],,FALSE,TRUE,56,"Sanford, Oberbrunner and Stracke",Schulist-Senger,Sample import note
+Dotti Fearey,[email protected],pstanners16,Temazepam,87592e58-5628-4d38-a3ae-fb06df901777,Adaptive well-modulated local area network,Murray Group,1/12/94,$66.92 ,70036,393533011-1,Paolo Stanners,[email protected],,FALSE,no,69,Crist and Sons,Moore and Sons,"Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui.
Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti.
Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris."
-Arabela Coneybeare,[email protected],ccrolla17,Lorazepam,1b423a53-d014-4648-9f64-db4807525c2f,Synergistic logistical Graphic Interface,Moore and Sons,06/05/1995,$52.73,14746,087846643-6,Cele Crolla,[email protected],12/14/2016,false,true,56,Aufderhar-Mann,Sauer-Carter,"Etiam vel augue. Vestibulum rutrum rutrum neque. Aenean auctor gravida sem.
+Arabela Coneybeare,[email protected],ccrolla17,Lorazepam,1b423a53-d014-4648-9f64-db4807525c2f,Synergistic logistical Graphic Interface,Moore and Sons,6/5/95,$52.73 ,14746,087846643-6,Cele Crolla,[email protected],,FALSE,TRUE,56,Aufderhar-Mann,Sauer-Carter,"Etiam vel augue. Vestibulum rutrum rutrum neque. Aenean auctor gravida sem.
Praesent id massa id nisl venenatis lacinia. Aenean sit amet justo. Morbi ut odio.
Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo. In blandit ultrices enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
-Lewie Fancutt,[email protected],gnewdick18,"Aconitum napellus, Asafoetida, Chamomilla, Crocus sativus, Hyoscyamus niger, Ignatia amara, Sumbul, Valeriana officinalis,",49ee5fa4-d441-4d36-8708-29a394044fd3,Fundamental zero administration moderator,O'Kon-Pfannerstill,01/16/2008,$7.55,42229,546659697-3,Gerry Newdick,[email protected],08/30/2016,true,true,91,Howell-Schowalter,"Huel, Walker and Blanda",Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum. Integer a nibh.
-Farleigh Craisford,[email protected],kfilippi19,"Aconitum napellus, Apis mellifica, Arnica montana, Bellis perennis, Bryonia, Calendula officinalis, Chamomilla, Cistus canadensis, Clematis vitalba, flos",e5a134ef-5a83-42da-a695-2ece98455030,Re-engineered executive pricing structure,,10/05/2013,$80.46,,830372513-0,Kikelia Filippi,[email protected],01/11/2016,false,,37,,,
-Cilka Risdall,[email protected],agrogan1a,PILOCARPINE HYDROCHLORIDE,b13bcb71-4950-4e7b-98ff-120c07ff0a16,Extended reciprocal standardization,Sporer and Sons,08/01/1993,$99.99,11073,839726250-4,Antoni Grogan,[email protected],12/29/2016,true,FALSE,31,Fahey and Sons,Herman-Prohaska,"Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui."
-Leon Feckey,[email protected],lculshaw1b,ZONISAMIDE,d006b259-bc10-4c6c-aca2-3cdc5957bf90,Reactive cohesive website,Johnson Group,,$75.72,19200,008549857-2,Lynelle Culshaw,[email protected],08/13/2016,false,TRUE,55,McLaughlin Group,Fadel-Botsford,"Curabitur gravida nisi at nibh. In hac habitasse platea dictumst. Aliquam augue quam, sollicitudin vitae, consectetuer eget, rutrum at, lorem.
+Lewie Fancutt,[email protected],gnewdick18,Aconitum napellus,49ee5fa4-d441-4d36-8708-29a394044fd3,Fundamental zero administration moderator,O'Kon-Pfannerstill,1/16/08,$7.55 ,42229,546659697-3,Gerry Newdick,[email protected],,TRUE,TRUE,91,Howell-Schowalter,"Huel, Walker and Blanda",Sample import note
+Farleigh Craisford,[email protected],kfilippi19,Bryonia,e5a134ef-5a83-42da-a695-2ece98455030,Re-engineered executive pricing structure,,10/5/13,$80.46 ,,830372513-0,Kikelia Filippi,[email protected],,FALSE,,37,,,
+Cilka Risdall,[email protected],agrogan1a,PILOCARPINE HYDROCHLORIDE,b13bcb71-4950-4e7b-98ff-120c07ff0a16,Extended reciprocal standardization,Sporer and Sons,8/1/93,$99.99 ,11073,839726250-4,Antoni Grogan,[email protected],,TRUE,FALSE,31,Fahey and Sons,Herman-Prohaska,Sample import note
+Leon Feckey,[email protected],lculshaw1b,ZONISAMIDE,d006b259-bc10-4c6c-aca2-3cdc5957bf90,Reactive cohesive website,Johnson Group,,$75.72 ,19200,008549857-2,Lynelle Culshaw,[email protected],,FALSE,TRUE,55,McLaughlin Group,Fadel-Botsford,"Curabitur gravida nisi at nibh. In hac habitasse platea dictumst. Aliquam augue quam, sollicitudin vitae, consectetuer eget, rutrum at, lorem.
Integer tincidunt ante vel ipsum. Praesent blandit lacinia erat. Vestibulum sed magna at nunc commodo placerat.
Praesent blandit. Nam nulla. Integer pede justo, lacinia eget, tincidunt eget, tempus vel, pede."
-Lee Barlace,[email protected],psanja1c,Not applicable,44b4441c-c659-4b37-9aed-b6081030e770,Realigned 6th generation structure,Weimann Inc,08/22/1983,$65.31,45540,207737343-1,Pooh Sanja,[email protected],03/01/2016,true,,45,"Beer, Wehner and Bode",Fritsch-Pollich,"Aliquam quis turpis eget elit sodales scelerisque. Mauris sit amet eros. Suspendisse accumsan tortor quis turpis.
+Lee Barlace,[email protected],psanja1c,Not applicable,44b4441c-c659-4b37-9aed-b6081030e770,Realigned 6th generation structure,Weimann Inc,8/22/83,$65.31 ,45540,207737343-1,Pooh Sanja,[email protected],,TRUE,,45,"Beer, Wehner and Bode",Fritsch-Pollich,"Aliquam quis turpis eget elit sodales scelerisque. Mauris sit amet eros. Suspendisse accumsan tortor quis turpis.
Sed ante. Vivamus tortor. Duis mattis egestas metus."
-Esma Dabernott,[email protected],gholme1d,Metoprolol Tartrate and Hydrochlorothiazide,23f2f46f-0cbc-493c-9efa-05eed769235d,Open-architected 4th generation matrix,"Metz, Jacobson and Kreiger",03/24/1991,$41.52,15974,173704123-5,Gennifer Holme,[email protected],02/18/2016,false,TRUE,12,Will-Schamberger,"Fisher, Feest and Hane","Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin risus. Praesent lectus.
+Esma Dabernott,[email protected],gholme1d,Metoprolol Tartrate and Hydrochlorothiazide,23f2f46f-0cbc-493c-9efa-05eed769235d,Open-architected 4th generation matrix,"Metz, Jacobson and Kreiger",3/24/91,$41.52 ,15974,173704123-5,Gennifer Holme,[email protected],,FALSE,TRUE,12,Will-Schamberger,"Fisher, Feest and Hane","Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin risus. Praesent lectus.
Vestibulum quam sapien, varius ut, blandit non, interdum in, ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis.
diff --git a/tests/Feature/Importing/Api/ImportAccessoriesTest.php b/tests/Feature/Importing/Api/ImportAccessoriesTest.php
index c2c95bd163..63edc0f467 100644
--- a/tests/Feature/Importing/Api/ImportAccessoriesTest.php
+++ b/tests/Feature/Importing/Api/ImportAccessoriesTest.php
@@ -58,7 +58,7 @@ class ImportAccessoriesTest extends ImportDataTestCase implements TestsPermissio
$this->importFileResponse(['import' => $import->id])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => [
'redirect_url' => route('accessories.index'),
@@ -255,7 +255,7 @@ class ImportAccessoriesTest extends ImportDataTestCase implements TestsPermissio
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'Accessory' => [
@@ -348,6 +348,74 @@ class ImportAccessoriesTest extends ImportDataTestCase implements TestsPermissio
$this->assertNotNull($updateLog, 'Expected an update action log entry after accessory importer update mode.');
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $accessory = Accessory::factory()->create([
+ 'notes' => 'Some pre-existing notes',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $this->assertNotNull($accessory->purchase_date);
+ $this->assertNotEmpty($accessory->notes);
+
+ $row = ImportFileBuilder::new()->definition();
+ $row['itemName'] = $accessory->name;
+ $row['notes'] = '';
+ $row['purchaseDate'] = '';
+
+ $importFileBuilder = new ImportFileBuilder([$row]);
+ $import = Import::factory()->accessory()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $accessory->refresh();
+ $this->assertNull($accessory->notes);
+ $this->assertNull($accessory->purchase_date);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $accessory = Accessory::factory()->create([
+ 'notes' => 'Do not lose this',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $originalNotes = $accessory->notes;
+ $originalPurchaseDate = $accessory->purchase_date?->toDateString();
+
+ // Import a CSV that only has the identity field (name) plus one
+ // updated column. All other Accessory fields are absent from the
+ // CSV, so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'itemName' => $accessory->name,
+ 'orderNumber' => 'UPDATED-ORDER',
+ ]]);
+ $partialImport = Import::factory()->accessory()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $accessory->refresh();
+ $this->assertEquals('UPDATED-ORDER', $accessory->order_number);
+ $this->assertEquals($originalNotes, $accessory->notes);
+ $this->assertEquals($originalPurchaseDate, $accessory->purchase_date?->toDateString());
+ }
+
#[Test]
public function when_import_file_contains_empty_values(): void
{
@@ -377,7 +445,7 @@ class ImportAccessoriesTest extends ImportDataTestCase implements TestsPermissio
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
$importFileBuilder->firstRow()['itemName'] => [
'Accessory' => [
diff --git a/tests/Feature/Importing/Api/ImportAssetModelsTest.php b/tests/Feature/Importing/Api/ImportAssetModelsTest.php
index a93de447a2..4b6a6d3e8c 100644
--- a/tests/Feature/Importing/Api/ImportAssetModelsTest.php
+++ b/tests/Feature/Importing/Api/ImportAssetModelsTest.php
@@ -48,7 +48,7 @@ class ImportAssetModelsTest extends ImportDataTestCase implements TestsPermissio
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 0])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('models.index')],
]);
@@ -90,11 +90,11 @@ class ImportAssetModelsTest extends ImportDataTestCase implements TestsPermissio
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'name' => [
- 'name' => ['The name field is required.'],
+ 'name' => ['The name must be a string.'],
],
],
],
@@ -121,7 +121,7 @@ class ImportAssetModelsTest extends ImportDataTestCase implements TestsPermissio
$this->importFileResponse(['import' => $import->id, 'import-update' => true])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 1, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('models.index')],
]);
@@ -133,6 +133,84 @@ class ImportAssetModelsTest extends ImportDataTestCase implements TestsPermissio
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $assetmodel = AssetModel::factory()->create([
+ 'notes' => 'Some pre-existing notes',
+ 'eol' => 24,
+ ])->refresh();
+
+ $this->assertNotEmpty($assetmodel->notes);
+ $this->assertNotNull($assetmodel->eol);
+
+ $importFileBuilder = new ImportFileBuilder([[
+ 'name' => $assetmodel->name,
+ 'model_number' => $assetmodel->model_number,
+ 'notes' => '',
+ 'eol' => '',
+ ]]);
+ $import = Import::factory()->assetmodel()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $assetmodel->refresh();
+ $this->assertNull($assetmodel->notes);
+ $this->assertNull($assetmodel->eol);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $assetmodel = AssetModel::factory()->create([
+ 'notes' => 'Do Not Lose This',
+ 'eol' => 48,
+ ])->refresh();
+
+ $originalNotes = $assetmodel->notes;
+ $originalEol = $assetmodel->eol;
+ $originalModelNumber = $assetmodel->model_number;
+
+ // Import a CSV that only has the identity field (name) plus one
+ // updated column. All other AssetModel fields are absent from the
+ // CSV, so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'name' => $assetmodel->name,
+ 'min_amt' => 5,
+ ]]);
+ $partialImport = Import::factory()->assetmodel()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ // Explicit column-mappings so "Min Amount" resolves to 'min_amt'.
+ // Matches what the wizard's auto-map does in production; the
+ // default_field_map fallback used by tests that omit column-mappings
+ // does not know how to reduce "Min Amount" to 'min_amt'.
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ 'column-mappings' => [
+ 'Name' => 'name',
+ 'Min Amount' => 'min_amt',
+ ],
+ ])->assertOk();
+
+ $assetmodel->refresh();
+ $this->assertEquals(5, $assetmodel->min_amt);
+ $this->assertEquals($originalNotes, $assetmodel->notes);
+ $this->assertEquals($originalEol, $assetmodel->eol);
+ $this->assertEquals($originalModelNumber, $assetmodel->model_number);
+ }
+
#[Test]
public function update_mode_logs_asset_model_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportAssetsTest.php b/tests/Feature/Importing/Api/ImportAssetsTest.php
index 8dd2910bb9..e8af835d08 100644
--- a/tests/Feature/Importing/Api/ImportAssetsTest.php
+++ b/tests/Feature/Importing/Api/ImportAssetsTest.php
@@ -62,7 +62,7 @@ class ImportAssetsTest extends ImportDataTestCase implements TestsPermissionsReq
$this->importFileResponse(['import' => $import->id])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('hardware.index')],
]);
@@ -342,7 +342,7 @@ class ImportAssetsTest extends ImportDataTestCase implements TestsPermissionsReq
->assertInternalServerError()
->assertJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 2]],
'messages' => [
$rows[0]['itemName'] => [
"Asset \"{$rows[0]['itemName']}\"" => [
@@ -467,6 +467,90 @@ class ImportAssetsTest extends ImportDataTestCase implements TestsPermissionsReq
$this->assertEquals(0, $asset->byod, 'Update import with byod=FALSE should clear the byod flag.');
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ // Seed an asset directly with fields we intend to clear. Using the
+ // factory (rather than a prior import) gives us reliable non-null
+ // starting values regardless of importer-side mapping quirks.
+ $asset = Asset::factory()->create([
+ 'notes' => 'Some pre-existing notes',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ // Sanity: the pre-existing values are there for the clear to act on.
+ $this->assertNotNull($asset->purchase_date);
+ $this->assertNotEmpty($asset->notes);
+
+ $row = ImportFileBuilder::new()->definition();
+ $row['tag'] = $asset->asset_tag;
+ $row['notes'] = '';
+ $row['purchaseDate'] = '';
+
+ $importFileBuilder = new ImportFileBuilder([$row]);
+ $import = Import::factory()->asset()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ // Explicit column-mappings so the "Notes" CSV column resolves to the
+ // 'asset_notes' importer field. Matches what the wizard's auto-map
+ // does in production; the default_field_map fallback used by tests
+ // that omit column-mappings does not know about 'asset_notes'.
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ 'column-mappings' => [
+ 'Asset Tag' => 'asset_tag',
+ 'item Name' => 'item_name',
+ 'Notes' => 'asset_notes',
+ 'Purchase Date' => 'purchase_date',
+ 'Serial number' => 'serial',
+ ],
+ ])->assertOk();
+
+ $asset->refresh();
+ $this->assertNull($asset->notes);
+ $this->assertNull($asset->purchase_date);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $asset = Asset::factory()->create([
+ 'notes' => 'Do not lose this',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $originalNotes = $asset->notes;
+ $originalPurchaseDate = $asset->purchase_date?->toDateString();
+ $originalSerial = $asset->serial;
+
+ // Import a CSV that only has the identity field and one other column.
+ // All other Asset fields are absent from the CSV, so their DB values
+ // must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'tag' => $asset->asset_tag,
+ 'itemName' => 'Renamed via partial import',
+ ]]);
+ $partialImport = Import::factory()->asset()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $asset->refresh();
+ $this->assertEquals('Renamed via partial import', $asset->name);
+ $this->assertEquals($originalNotes, $asset->notes);
+ $this->assertEquals($originalPurchaseDate, $asset->purchase_date?->toDateString());
+ $this->assertEquals($originalSerial, $asset->serial);
+ }
+
#[Test]
public function update_mode_logs_asset_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportCategoriesTest.php b/tests/Feature/Importing/Api/ImportCategoriesTest.php
index b11f4809a2..56f3dd51cc 100644
--- a/tests/Feature/Importing/Api/ImportCategoriesTest.php
+++ b/tests/Feature/Importing/Api/ImportCategoriesTest.php
@@ -46,7 +46,7 @@ class ImportCategoriesTest extends ImportDataTestCase implements TestsPermission
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 0])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('categories.index')],
]);
@@ -86,7 +86,7 @@ class ImportCategoriesTest extends ImportDataTestCase implements TestsPermission
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'Category ""' => [
@@ -117,15 +117,100 @@ class ImportCategoriesTest extends ImportDataTestCase implements TestsPermission
$this->importFileResponse(['import' => $import->id, 'import-update' => true])->assertOk();
$updatedCategory = Category::query()->find($category->id);
+
+ // Boolean flags (use_default_eula, require_acceptance, checkin_email)
+ // are explicitly set to 0 in the CSV above. Under the new CSV-present
+ // semantics, those values now propagate to the DB - the old importer's
+ // sanitize reject-empty pass silently stripped 0 values on update.
+ // Excluding them from the "unchanged" comparison because they are
+ // intentionally overwritten by the CSV.
$updatedAttributes = [
'name',
+ 'use_default_eula',
+ 'require_acceptance',
+ 'checkin_email',
];
$this->assertEquals($row['name'], $updatedCategory->name);
+ $this->assertEquals(0, $updatedCategory->use_default_eula);
+ $this->assertEquals(0, $updatedCategory->require_acceptance);
+ $this->assertEquals(0, $updatedCategory->checkin_email);
$this->assertEquals(
Arr::except($category->attributesToArray(), array_merge($updatedAttributes, $category->getDates())),
Arr::except($updatedCategory->attributesToArray(), array_merge($updatedAttributes, $category->getDates())),
);
}
+
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $category = Category::factory()->assetLaptopCategory()->create([
+ 'notes' => 'Some pre-existing notes',
+ 'eula_text' => 'Some EULA text',
+ ])->refresh();
+
+ $this->assertNotEmpty($category->notes);
+ $this->assertNotEmpty($category->eula_text);
+
+ $importFileBuilder = new ImportFileBuilder([[
+ 'name' => $category->name,
+ 'category_type' => $category->category_type,
+ 'notes' => '',
+ 'eula_text' => '',
+ ]]);
+ $import = Import::factory()->categories()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $category->refresh();
+ $this->assertNull($category->notes);
+ $this->assertNull($category->eula_text);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $category = Category::factory()->assetLaptopCategory()->create([
+ 'notes' => 'Do Not Lose This',
+ 'eula_text' => 'Preserved EULA',
+ 'tag_color' => '#123456',
+ ])->refresh();
+
+ $originalNotes = $category->notes;
+ $originalEula = $category->eula_text;
+ $originalTagColor = $category->tag_color;
+
+ // Import a CSV that only has the identity fields (name + category_type)
+ // and one updated column. All other Category fields are absent from
+ // the CSV, so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'name' => $category->name,
+ 'category_type' => $category->category_type,
+ 'require_acceptance' => 1,
+ ]]);
+ $partialImport = Import::factory()->categories()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $category->refresh();
+ $this->assertEquals(1, $category->require_acceptance);
+ $this->assertEquals($originalNotes, $category->notes);
+ $this->assertEquals($originalEula, $category->eula_text);
+ $this->assertEquals($originalTagColor, $category->tag_color);
+ }
}
diff --git a/tests/Feature/Importing/Api/ImportComponentsTest.php b/tests/Feature/Importing/Api/ImportComponentsTest.php
index 8c481f55a9..a529ff8e6b 100644
--- a/tests/Feature/Importing/Api/ImportComponentsTest.php
+++ b/tests/Feature/Importing/Api/ImportComponentsTest.php
@@ -62,7 +62,7 @@ class ImportComponentsTest extends ImportDataTestCase implements TestsPermission
$this->importFileResponse(['import' => $import->id])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('components.index')],
]);
@@ -199,11 +199,11 @@ class ImportComponentsTest extends ImportDataTestCase implements TestsPermission
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
$row['itemName'] => [
'Component' => [
- 'qty' => ['The qty field must be at least 1.'],
+ 'qty' => ['The qty field is required.'],
'category_id' => ['The category id field is required.'],
],
],
@@ -251,6 +251,76 @@ class ImportComponentsTest extends ImportDataTestCase implements TestsPermission
$this->assertEquals($component->notes, $updatedComponent->notes);
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $component = Component::factory()->create([
+ 'order_number' => 'PRE-EXISTING-ORDER',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $this->assertNotNull($component->purchase_date);
+ $this->assertNotEmpty($component->order_number);
+
+ $row = ImportFileBuilder::new()->definition();
+ $row['itemName'] = $component->name;
+ $row['serialNumber'] = $component->serial;
+ $row['orderNumber'] = '';
+ $row['purchaseDate'] = '';
+
+ $importFileBuilder = new ImportFileBuilder([$row]);
+ $import = Import::factory()->component()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $component->refresh();
+ $this->assertNull($component->order_number);
+ $this->assertNull($component->purchase_date);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $component = Component::factory()->create([
+ 'order_number' => 'DO-NOT-LOSE-THIS',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $originalOrderNumber = $component->order_number;
+ $originalPurchaseDate = $component->purchase_date?->toDateString();
+
+ // Import a CSV that only has the identity fields (name+serial) plus
+ // quantity (required by Component validation). All other Component
+ // fields are absent from the CSV, so their DB values must be preserved.
+ $partialFile = new ImportFileBuilder([[
+ 'itemName' => $component->name,
+ 'serialNumber' => $component->serial,
+ 'quantity' => 42,
+ ]]);
+ $partialImport = Import::factory()->component()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $component->refresh();
+ $this->assertEquals(42, $component->qty);
+ $this->assertEquals($originalOrderNumber, $component->order_number);
+ $this->assertEquals($originalPurchaseDate, $component->purchase_date?->toDateString());
+ }
+
#[Test]
public function update_mode_logs_component_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportConsumablesTest.php b/tests/Feature/Importing/Api/ImportConsumablesTest.php
index 5bf8e3a375..c649947b27 100644
--- a/tests/Feature/Importing/Api/ImportConsumablesTest.php
+++ b/tests/Feature/Importing/Api/ImportConsumablesTest.php
@@ -60,7 +60,7 @@ class ImportConsumablesTest extends ImportDataTestCase implements TestsPermissio
$this->importFileResponse(['import' => $import->id])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('consumables.index')],
]);
@@ -191,11 +191,12 @@ class ImportConsumablesTest extends ImportDataTestCase implements TestsPermissio
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
$row['itemName'] => [
'Consumable' => [
'category_id' => ['The category id field is required.'],
+ 'qty' => ['The qty field is required.'],
],
],
],
@@ -243,6 +244,74 @@ class ImportConsumablesTest extends ImportDataTestCase implements TestsPermissio
$this->assertEquals($consumable->item_number, $updatedConsumable->item_number);
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $consumable = Consumable::factory()->create([
+ 'order_number' => 'PRE-EXISTING-ORDER',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $this->assertNotNull($consumable->purchase_date);
+ $this->assertNotEmpty($consumable->order_number);
+
+ $row = ImportFileBuilder::new()->definition();
+ $row['itemName'] = $consumable->name;
+ $row['orderNumber'] = '';
+ $row['purchaseDate'] = '';
+
+ $importFileBuilder = new ImportFileBuilder([$row]);
+ $import = Import::factory()->consumable()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $consumable->refresh();
+ $this->assertNull($consumable->order_number);
+ $this->assertNull($consumable->purchase_date);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $consumable = Consumable::factory()->create([
+ 'order_number' => 'DO-NOT-LOSE-THIS',
+ 'purchase_date' => '2022-01-01',
+ ])->refresh();
+
+ $originalOrderNumber = $consumable->order_number;
+ $originalPurchaseDate = $consumable->purchase_date?->toDateString();
+
+ // Import a CSV that only has the identity field (name) plus quantity
+ // (required by Consumable validation). All other Consumable fields
+ // are absent from the CSV, so their DB values must be preserved.
+ $partialFile = new ImportFileBuilder([[
+ 'itemName' => $consumable->name,
+ 'quantity' => 42,
+ ]]);
+ $partialImport = Import::factory()->consumable()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $consumable->refresh();
+ $this->assertEquals(42, $consumable->qty);
+ $this->assertEquals($originalOrderNumber, $consumable->order_number);
+ $this->assertEquals($originalPurchaseDate, $consumable->purchase_date?->toDateString());
+ }
+
#[Test]
public function update_mode_logs_consumable_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportLicenseTest.php b/tests/Feature/Importing/Api/ImportLicenseTest.php
index cf3dd1eb4c..c57446449c 100644
--- a/tests/Feature/Importing/Api/ImportLicenseTest.php
+++ b/tests/Feature/Importing/Api/ImportLicenseTest.php
@@ -59,7 +59,7 @@ class ImportLicenseTest extends ImportDataTestCase implements TestsPermissionsRe
$this->importFileResponse(['import' => $import->id])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('licenses.index')],
]);
@@ -220,7 +220,7 @@ class ImportLicenseTest extends ImportDataTestCase implements TestsPermissionsRe
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
$row['licenseName'] => [
"License \"{$row['licenseName']}\"" => [
@@ -279,6 +279,97 @@ class ImportLicenseTest extends ImportDataTestCase implements TestsPermissionsRe
$this->assertEquals($license->min_amt, $updatedLicense->min_amt);
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $initialFile = ImportFileBuilder::new();
+ $initialRow = $initialFile->firstRow();
+ $initialImport = Import::factory()->license()->create([
+ 'file_path' => $initialFile->saveToImportsDirectory(),
+ ]);
+ $this->importFileResponse(['import' => $initialImport->id])->assertOk();
+
+ $license = License::query()
+ ->where('name', $initialRow['licenseName'])
+ ->where('serial', $initialRow['serialNumber'])
+ ->sole();
+
+ // Sanity: initial import should have populated the fields we are
+ // about to clear. Guards against a false negative if the fixture
+ // shape changes and the fields default to null.
+ $this->assertNotNull($license->expiration_date);
+ $this->assertNotEmpty($license->license_email);
+ $this->assertNotEmpty($license->notes);
+
+ // Re-import with these columns present but empty. Empty CSV cells
+ // should clear the corresponding DB fields, not preserve them.
+ $clearedRow = array_merge($initialRow, [
+ 'expirationDate' => '',
+ 'licensedToEmail' => '',
+ 'notes' => '',
+ ]);
+ $clearFile = new ImportFileBuilder([$clearedRow]);
+ $clearImport = Import::factory()->license()->create([
+ 'file_path' => $clearFile->saveToImportsDirectory(),
+ ]);
+ $this->importFileResponse([
+ 'import' => $clearImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $license->refresh();
+ $this->assertNull($license->expiration_date);
+ $this->assertNull($license->license_email);
+ $this->assertNull($license->notes);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $initialFile = ImportFileBuilder::new();
+ $initialRow = $initialFile->firstRow();
+ $initialImport = Import::factory()->license()->create([
+ 'file_path' => $initialFile->saveToImportsDirectory(),
+ ]);
+ $this->importFileResponse(['import' => $initialImport->id])->assertOk();
+
+ $license = License::query()
+ ->where('name', $initialRow['licenseName'])
+ ->where('serial', $initialRow['serialNumber'])
+ ->sole();
+
+ $originalEmail = $license->license_email;
+ $originalNotes = $license->notes;
+ $originalExpirationDate = $license->expiration_date?->toDateString();
+
+ // Re-import with a CSV that only has the identity fields plus one
+ // updated field. All other columns are absent from the CSV, so
+ // their DB values must be preserved.
+ $partialRow = [
+ 'licenseName' => $initialRow['licenseName'],
+ 'serialNumber' => $initialRow['serialNumber'],
+ 'orderNumber' => 'UPDATED-'.$initialRow['orderNumber'],
+ ];
+ $partialFile = new ImportFileBuilder([$partialRow]);
+ $partialImport = Import::factory()->license()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $license->refresh();
+ $this->assertEquals('UPDATED-'.$initialRow['orderNumber'], $license->order_number);
+ $this->assertEquals($originalEmail, $license->license_email);
+ $this->assertEquals($originalNotes, $license->notes);
+ $this->assertEquals($originalExpirationDate, $license->expiration_date?->toDateString());
+ }
+
#[Test]
public function update_mode_logs_license_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportLocationsTest.php b/tests/Feature/Importing/Api/ImportLocationsTest.php
index 09dd28e42f..a673baed96 100644
--- a/tests/Feature/Importing/Api/ImportLocationsTest.php
+++ b/tests/Feature/Importing/Api/ImportLocationsTest.php
@@ -47,7 +47,7 @@ class ImportLocationsTest extends ImportDataTestCase implements TestsPermissions
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 0])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('locations.index')],
]);
@@ -87,7 +87,7 @@ class ImportLocationsTest extends ImportDataTestCase implements TestsPermissions
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'Location ""' => [
@@ -131,6 +131,78 @@ class ImportLocationsTest extends ImportDataTestCase implements TestsPermissions
);
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $location = Location::factory()->create([
+ 'address' => '123 Pre-existing Street',
+ 'city' => 'PreExistingCity',
+ ])->refresh();
+
+ $this->assertNotEmpty($location->address);
+ $this->assertNotEmpty($location->city);
+
+ // Construct directly (not via ::new()) so address + city land in the
+ // row array. ::new() runs replace() which only overwrites keys the
+ // default definition() already emits; the Location builder default
+ // only has name + phone, so 'address' and 'city' would be dropped
+ // and the CSV would not contain those columns at all.
+ $importFileBuilder = new ImportFileBuilder([[
+ 'name' => $location->name,
+ 'address' => '',
+ 'city' => '',
+ ]]);
+ $import = Import::factory()->locations()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $location->refresh();
+ $this->assertNull($location->address);
+ $this->assertNull($location->city);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $location = Location::factory()->create([
+ 'address' => 'Do Not Lose This',
+ 'city' => 'PreservedCity',
+ ])->refresh();
+
+ $originalAddress = $location->address;
+ $originalCity = $location->city;
+
+ // Import a CSV that only has the identity field (name) plus one
+ // updated column. All other Location fields are absent from the CSV,
+ // so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'name' => $location->name,
+ 'zip' => '99999',
+ ]]);
+ $partialImport = Import::factory()->locations()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $location->refresh();
+ $this->assertEquals('99999', $location->zip);
+ $this->assertEquals($originalAddress, $location->address);
+ $this->assertEquals($originalCity, $location->city);
+ }
+
#[Test]
public function update_mode_logs_location_update_in_actionlog(): void
{
diff --git a/tests/Feature/Importing/Api/ImportManufacturersTest.php b/tests/Feature/Importing/Api/ImportManufacturersTest.php
index f5c9276488..2042be29ca 100644
--- a/tests/Feature/Importing/Api/ImportManufacturersTest.php
+++ b/tests/Feature/Importing/Api/ImportManufacturersTest.php
@@ -46,7 +46,7 @@ class ImportManufacturersTest extends ImportDataTestCase implements TestsPermiss
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 0])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('manufacturers.index')],
]);
@@ -86,7 +86,7 @@ class ImportManufacturersTest extends ImportDataTestCase implements TestsPermiss
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'Manufacturer ""' => [
@@ -131,4 +131,80 @@ class ImportManufacturersTest extends ImportDataTestCase implements TestsPermiss
Arr::except($updatedManufacturer->attributesToArray(), array_merge($updatedAttributes, $manufacturer->getDates())),
);
}
+
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $manufacturer = Manufacturer::factory()->create([
+ 'support_phone' => '555-1234',
+ 'support_url' => 'https://pre-existing.example.com',
+ ])->refresh();
+
+ $this->assertNotEmpty($manufacturer->support_phone);
+ $this->assertNotEmpty($manufacturer->support_url);
+
+ $importFileBuilder = ImportFileBuilder::new([
+ 'name' => $manufacturer->name,
+ 'support_phone' => '',
+ 'support_url' => '',
+ ]);
+ $import = Import::factory()->manufacturers()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ // Explicit column-mappings so the "Support Phone" CSV column resolves
+ // to the 'support_phone' importer field. Matches what the wizard's
+ // auto-map does in production; the default_field_map fallback used
+ // by tests that omit column-mappings does not know about 'support_phone'.
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ 'column-mappings' => [
+ 'name' => 'name',
+ 'Support Phone' => 'support_phone',
+ 'support_url' => 'support_url',
+ ],
+ ])->assertOk();
+
+ $manufacturer->refresh();
+ $this->assertNull($manufacturer->support_phone);
+ $this->assertNull($manufacturer->support_url);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $manufacturer = Manufacturer::factory()->create([
+ 'support_phone' => '555-9876',
+ 'support_url' => 'https://do-not-lose.example.com',
+ ])->refresh();
+
+ $originalPhone = $manufacturer->support_phone;
+ $originalUrl = $manufacturer->support_url;
+
+ // Import a CSV that only has the identity field (name) plus one
+ // updated column. All other Manufacturer fields are absent from the
+ // CSV, so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'name' => $manufacturer->name,
+ 'support_email' => '[email protected]',
+ ]]);
+ $partialImport = Import::factory()->manufacturers()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $manufacturer->refresh();
+ $this->assertEquals('[email protected]', $manufacturer->support_email);
+ $this->assertEquals($originalPhone, $manufacturer->support_phone);
+ $this->assertEquals($originalUrl, $manufacturer->support_url);
+ }
}
diff --git a/tests/Feature/Importing/Api/ImportSuppliersTest.php b/tests/Feature/Importing/Api/ImportSuppliersTest.php
index 1257e1abb0..978b3dcf19 100644
--- a/tests/Feature/Importing/Api/ImportSuppliersTest.php
+++ b/tests/Feature/Importing/Api/ImportSuppliersTest.php
@@ -46,7 +46,7 @@ class ImportSuppliersTest extends ImportDataTestCase implements TestsPermissions
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 0])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('suppliers.index')],
]);
@@ -86,7 +86,7 @@ class ImportSuppliersTest extends ImportDataTestCase implements TestsPermissions
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'Supplier ""' => [
@@ -133,4 +133,71 @@ class ImportSuppliersTest extends ImportDataTestCase implements TestsPermissions
Arr::except($updatedSupplier->attributesToArray(), array_merge($updatedAttributes, $supplier->getDates())),
);
}
+
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $supplier = Supplier::factory()->create([
+ 'phone' => '555-1234',
+ 'url' => 'https://pre-existing.example.com',
+ ])->refresh();
+
+ $this->assertNotEmpty($supplier->phone);
+ $this->assertNotEmpty($supplier->url);
+
+ $importFileBuilder = ImportFileBuilder::new([
+ 'name' => $supplier->name,
+ 'phone' => '',
+ 'url' => '',
+ ]);
+ $import = Import::factory()->suppliers()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $supplier->refresh();
+ $this->assertNull($supplier->phone);
+ $this->assertNull($supplier->url);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $supplier = Supplier::factory()->create([
+ 'phone' => '555-9876',
+ 'url' => 'https://do-not-lose.example.com',
+ ])->refresh();
+
+ $originalPhone = $supplier->phone;
+ $originalUrl = $supplier->url;
+
+ // Import a CSV that only has the identity field (name) plus one
+ // updated column. All other Supplier fields are absent from the CSV,
+ // so their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'name' => $supplier->name,
+ 'city' => 'RenamedCity',
+ ]]);
+ $partialImport = Import::factory()->suppliers()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $supplier->refresh();
+ $this->assertEquals('RenamedCity', $supplier->city);
+ $this->assertEquals($originalPhone, $supplier->phone);
+ $this->assertEquals($originalUrl, $supplier->url);
+ }
}
diff --git a/tests/Feature/Importing/Api/ImportUsersTest.php b/tests/Feature/Importing/Api/ImportUsersTest.php
index ed5538fae8..16fdb49966 100644
--- a/tests/Feature/Importing/Api/ImportUsersTest.php
+++ b/tests/Feature/Importing/Api/ImportUsersTest.php
@@ -63,7 +63,7 @@ class ImportUsersTest extends ImportDataTestCase implements TestsPermissionsRequ
$this->importFileResponse(['import' => $import->id, 'send-welcome' => 1])
->assertOk()
->assertExactJson([
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 1, 'updated' => 0, 'skipped' => 0, 'errored' => 0]],
'status' => 'success',
'messages' => ['redirect_url' => route('users.index')],
]);
@@ -238,7 +238,7 @@ class ImportUsersTest extends ImportDataTestCase implements TestsPermissionsRequ
->assertInternalServerError()
->assertExactJson([
'status' => 'import-errors',
- 'payload' => null,
+ 'payload' => ['tally' => ['created' => 0, 'updated' => 0, 'skipped' => 0, 'errored' => 1]],
'messages' => [
'' => [
'User' => [
@@ -302,6 +302,76 @@ class ImportUsersTest extends ImportDataTestCase implements TestsPermissionsRequ
);
}
+ #[Test]
+ public function update_mode_clears_field_when_csv_column_is_present_but_empty(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $user = User::factory()->create([
+ 'jobtitle' => 'Pre-existing Job Title',
+ 'phone' => '555-1234',
+ ])->refresh();
+
+ $this->assertNotEmpty($user->jobtitle);
+ $this->assertNotEmpty($user->phone);
+
+ $row = ImportFileBuilder::new()->definition();
+ $row['username'] = $user->username;
+ $row['firstName'] = $user->first_name;
+ $row['lastName'] = $user->last_name;
+ $row['position'] = '';
+ $row['phoneNumber'] = '';
+
+ $importFileBuilder = new ImportFileBuilder([$row]);
+ $import = Import::factory()->users()->create([
+ 'file_path' => $importFileBuilder->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $user->refresh();
+ $this->assertNull($user->jobtitle);
+ $this->assertNull($user->phone);
+ }
+
+ #[Test]
+ public function update_mode_preserves_fields_when_csv_column_is_absent(): void
+ {
+ $this->actingAsForApi(User::factory()->superuser()->create());
+
+ $user = User::factory()->create([
+ 'jobtitle' => 'Do Not Lose This',
+ 'phone' => '555-1234',
+ ])->refresh();
+
+ $originalJobTitle = $user->jobtitle;
+ $originalPhone = $user->phone;
+
+ // Import a CSV that only has the identity field (username) plus one
+ // updated column. All other User fields are absent from the CSV, so
+ // their DB values must be preserved on update.
+ $partialFile = new ImportFileBuilder([[
+ 'username' => $user->username,
+ 'firstName' => 'RenamedFirstName',
+ ]]);
+ $partialImport = Import::factory()->users()->create([
+ 'file_path' => $partialFile->saveToImportsDirectory(),
+ ]);
+
+ $this->importFileResponse([
+ 'import' => $partialImport->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $user->refresh();
+ $this->assertEquals('RenamedFirstName', $user->first_name);
+ $this->assertEquals($originalJobTitle, $user->jobtitle);
+ $this->assertEquals($originalPhone, $user->phone);
+ }
+
#[Test]
public function update_mode_logs_user_update_in_actionlog(): void
{