Skip to content

A free open source IT asset/license management system

Update license importer to look for pre-existing license

snipeb7d1f84adb15
diff --git a/app/Importer/LicenseImporter.php b/app/Importer/LicenseImporter.php
index 8f1cc01e30..66cf3b2cba 100644
--- a/app/Importer/LicenseImporter.php
+++ b/app/Importer/LicenseImporter.php
@@ -108,17 +108,45 @@ class LicenseImporter extends ItemImporter
$name = $this->item['name'] ?? '';
$editingLicense = false;
- $license = License::where('serial', $serial)->where('name', $name)->first();
+
+ // When the CSV row supplies a serial, match on serial + name. When
+ // the row has no serial (either the column is absent from the CSV
+ // or the cell is empty), match on name plus "no serial", where
+ // "no serial" covers both NULL and empty-string DB values. Without
+ // this null-or-empty branch, users importing a seat-assignment CSV
+ // that omits the serial column would create a new License per row
+ // instead of matching to the one they just created above, because
+ // the fillable insert path stores absent columns as NULL while the
+ // match query previously compared against ''.
+ $query = License::where('name', $name);
+ if ($serial !== '') {
+ $query->where('serial', $serial);
+ } else {
+ $query->where(function ($q) {
+ $q->whereNull('serial')->orWhere('serial', '');
+ });
+ }
+ $license = $query->first();
+
+ // 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') : '';
+
if ($license) {
if (! $this->updating) {
-
+ // Duplicate license record. Don't recreate it, but still
+ // honor the row's seat-assignment intent so users can run
+ // a "assign these users to seats" CSV in create mode
+ // without every row silently dropping the checkout.
if ($serial !== '') {
- $this->log('A matching License '.$name.' with serial '.$serial.' already exists');
+ $this->log('A matching License '.$name.' with serial '.$serial.' already exists, checking for seat assignment');
} else {
- $this->log('A matching License '.$name.' with no serial number already exists');
+ $this->log('A matching License '.$name.' with no serial number already exists, checking for seat assignment');
}
$this->recordSkipped();
+ $this->assignSeatIfCheckoutTargetSet($license, $asset_tag);
return;
}
@@ -129,10 +157,6 @@ class LicenseImporter extends ItemImporter
$this->log('No Matching License, Creating a new one');
$license = new License;
}
- // 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');
@@ -179,49 +203,74 @@ class LicenseImporter extends ItemImporter
$this->recordCreated();
}
- // Lets try to checkout seats if the fields exist and we have seats.
- if ($license->seats > 0) {
- $checkout_target = $this->item['checkout_target'];
- $asset = Asset::where('asset_tag', $asset_tag)->first();
- $targetLicense = $license->freeSeat();
+ $this->assignSeatIfCheckoutTargetSet($license, $asset_tag);
- if (is_null($targetLicense)) {
- return;
- }
+ return;
+ }
+ $this->recordErrored();
+ $this->logError($license, 'License "'.$name.'"');
+ }
- if ($checkout_target) {
- if (! $license->canCheckoutTo($checkout_target)) {
- $this->log(trans('general.error_checkout_company_mismatch', [
- 'item' => trans('general.license').' "'.$license->name.'"',
- 'item_company' => $license->company?->name ?? trans('general.unassigned'),
- 'target' => ($checkout_target->name ?? $checkout_target->username ?? $checkout_target->id),
- ]));
- } else {
- $targetLicense->assigned_to = $checkout_target->id;
- $targetLicense->created_by = $this->created_by;
- if ($asset) {
- $targetLicense->asset_id = $asset->id;
- }
- $targetLicense->save();
- }
- } elseif ($asset) {
- if (! $license->canCheckoutTo($asset)) {
- $this->log(trans('general.error_checkout_company_mismatch', [
- 'item' => trans('general.license').' "'.$license->name.'"',
- 'item_company' => $license->company?->name ?? trans('general.unassigned'),
- 'target' => trans('general.asset').' "'.$asset->display_name.'"',
- ]));
- } else {
- $targetLicense->created_by = $this->created_by;
- $targetLicense->asset_id = $asset->id;
- $targetLicense->save();
- }
- }
+ /**
+ * Attempt a single-seat checkout on $license for the checkout_target
+ * captured on $this->item in handle(). Called from all three create-or-
+ * update paths (created, updated, skipped-because-duplicate) so a
+ * seat-assignment CSV works regardless of whether the license record
+ * itself was newly created, updated, or already existed.
+ *
+ * If $license has no free seats, no checkout_target was supplied, or
+ * a company mismatch trips the canCheckoutTo gate, this is a no-op
+ * with a log line.
+ */
+ protected function assignSeatIfCheckoutTargetSet(License $license, string $asset_tag): void
+ {
+ if ($license->seats <= 0) {
+ return;
+ }
+
+ $checkout_target = $this->item['checkout_target'] ?? null;
+ $asset = $asset_tag !== '' ? Asset::where('asset_tag', $asset_tag)->first() : null;
+
+ if (! $checkout_target && ! $asset) {
+ return;
+ }
+
+ $targetLicense = $license->freeSeat();
+ if (is_null($targetLicense)) {
+ return;
+ }
+
+ if ($checkout_target) {
+ if (! $license->canCheckoutTo($checkout_target)) {
+ $this->log(trans('general.error_checkout_company_mismatch', [
+ 'item' => trans('general.license').' "'.$license->name.'"',
+ 'item_company' => $license->company?->name ?? trans('general.unassigned'),
+ 'target' => ($checkout_target->name ?? $checkout_target->username ?? $checkout_target->id),
+ ]));
+
+ return;
+ }
+ $targetLicense->assigned_to = $checkout_target->id;
+ $targetLicense->created_by = $this->created_by;
+ if ($asset) {
+ $targetLicense->asset_id = $asset->id;
}
+ $targetLicense->save();
return;
}
- $this->recordErrored();
- $this->logError($license, 'License "'.$name.'"');
+
+ if (! $license->canCheckoutTo($asset)) {
+ $this->log(trans('general.error_checkout_company_mismatch', [
+ 'item' => trans('general.license').' "'.$license->name.'"',
+ 'item_company' => $license->company?->name ?? trans('general.unassigned'),
+ 'target' => trans('general.asset').' "'.$asset->display_name.'"',
+ ]));
+
+ return;
+ }
+ $targetLicense->created_by = $this->created_by;
+ $targetLicense->asset_id = $asset->id;
+ $targetLicense->save();
}
}
diff --git a/tests/Feature/Importing/Api/ImportLicenseTest.php b/tests/Feature/Importing/Api/ImportLicenseTest.php
index daf593b474..76c1c7dcca 100644
--- a/tests/Feature/Importing/Api/ImportLicenseTest.php
+++ b/tests/Feature/Importing/Api/ImportLicenseTest.php
@@ -589,4 +589,78 @@ class ImportLicenseTest extends ImportDataTestCase implements TestsPermissionsRe
$checkedOutSeat = LicenseSeat::where('license_id', $license->id)->where('assigned_to', $user->id)->first();
$this->assertNotNull($checkedOutSeat, 'License seat should be checked out to a no-company user when floater mode is on');
}
+
+ #[Test]
+ public function multiple_rows_without_serial_column_assign_seats_to_a_single_license_in_update_mode(): void
+ {
+ // Regression from the 8.7.0 importer rewrite. Users importing a
+ // seat-assignment CSV (username + license name, no serial column)
+ // were seeing every row create a new License in update mode instead
+ // of matching to an existing null-serial license. Reason:
+ // setItemFromCsvIfPresent skips absent columns so the insert path
+ // stored serial as NULL, but the match query looked for serial = ''
+ // which never matches NULL in SQL. Match now checks
+ // (serial IS NULL OR serial = '').
+ [$firstUser, $secondUser] = User::factory()->count(2)->create();
+ $existingLicense = License::factory()->create([
+ 'serial' => null,
+ 'seats' => 5,
+ ]);
+
+ $rowShape = [
+ 'licenseName' => $existingLicense->name,
+ 'category' => 'Software',
+ 'seats' => 5,
+ ];
+
+ $file = new ImportFileBuilder([
+ array_merge($rowShape, ['checkoutUsername' => $firstUser->username]),
+ array_merge($rowShape, ['checkoutUsername' => $secondUser->username]),
+ ]);
+
+ $import = Import::factory()->license()->create(['file_path' => $file->saveToImportsDirectory()]);
+
+ $this->actingAsForApi(User::factory()->superuser()->create());
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ // Only the one existing License should exist; both rows should have
+ // matched into it. Without the fix, each row created a new license.
+ $licenses = License::where('name', $existingLicense->name)->get();
+ $this->assertCount(1, $licenses, 'Both rows should have matched the existing null-serial license, not created duplicates.');
+
+ // Two seats should be checked out, one per row.
+ $this->assertSame(2, LicenseSeat::where('license_id', $existingLicense->id)->whereNotNull('assigned_to')->count());
+ }
+
+ #[Test]
+ public function update_matches_existing_license_with_null_serial_when_csv_omits_serial(): void
+ {
+ // Same class of bug as multiple_rows_without_serial_column, on the
+ // update path: an existing License with serial NULL in the DB and a
+ // CSV row that omits the serial column altogether. The old match
+ // query used serial = '' which does not match NULL, so a duplicate
+ // was created. Now checks (serial IS NULL OR serial = '').
+ $license = License::factory()->create(['serial' => null]);
+
+ $file = new ImportFileBuilder([[
+ 'licenseName' => $license->name,
+ 'category' => 'Software',
+ 'seats' => 3,
+ 'notes' => 'Updated via seat-assign CSV',
+ ]]);
+
+ $import = Import::factory()->license()->create(['file_path' => $file->saveToImportsDirectory()]);
+
+ $this->actingAsForApi(User::factory()->superuser()->create());
+ $this->importFileResponse([
+ 'import' => $import->id,
+ 'import-update' => true,
+ ])->assertOk();
+
+ $this->assertSame(1, License::where('name', $license->name)->count(), 'Existing null-serial license should have been matched, not duplicated.');
+ $this->assertSame('Updated via seat-assign CSV', $license->fresh()->notes);
+ }
}