Skip to content

A free open source IT asset/license management system

Importer: Small UI improvements, send welcome email if user created

snipea38ebfea794e
diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php
index 171d936206..12f6773f1b 100644
--- a/app/Importer/AccessoryImporter.php
+++ b/app/Importer/AccessoryImporter.php
@@ -210,6 +210,7 @@ class AccessoryImporter extends ItemImporter
false,
));
$this->log('Accessory '.$accessory->name.' checked out to '.($target->name ?? $target->username ?? $target->id));
+ $this->maybeSendWelcomeEmail($target);
} else {
$this->logError($checkout, 'AccessoryCheckout');
}
diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php
index 4dcf98bbb6..7031d9b84b 100644
--- a/app/Importer/AssetImporter.php
+++ b/app/Importer/AssetImporter.php
@@ -267,6 +267,24 @@ class AssetImporter extends ItemImporter
$target = $this->item['checkout_target'];
}
+ // Log a warning when the operator populated a checkout column for
+ // this row but no target could be resolved. Prior behavior silently
+ // no-op'd the checkout side of the import in this case, so the
+ // row's other fields updated but no checkout event fired and
+ // nothing surfaced to the operator. Common triggers: the named
+ // location doesn't exist yet AND autocreate failed, or the older
+ // two-column shape where checkout_class was required and not
+ // mapped. See the determineCheckout comment.
+ $checkoutColumnPopulated = $this->findCsvMatch($row, 'checkout_location')
+ || $this->findCsvMatch($row, 'checkout_asset')
+ || $this->findCsvMatch($row, 'checkout_user')
+ || $this->findCsvMatch($row, 'checkout_class')
+ || $this->findCsvMatch($row, 'email')
+ || $this->findCsvMatch($row, 'username');
+ if ($checkoutColumnPopulated && empty($target)) {
+ $this->log('WARNING: A checkout column was populated for asset tag "'.$asset_tag.'" but no checkout target could be resolved from the row. The asset will be updated but no checkout event will fire.');
+ }
+
$item = $this->sanitizeItemForStoring($asset, $editingAsset);
// The location id fetched by the csv reader is actually the rtd_location_id.
@@ -364,6 +382,8 @@ class AssetImporter extends ItemImporter
}
$asset->checkOut($target, $this->created_by, $checkout_date, null, 'Checkout from CSV Importer', $asset->name);
+
+ $this->maybeSendWelcomeEmail($target);
}
}
}
diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php
index 32d2e1a271..81ad5d4ad1 100644
--- a/app/Importer/ConsumableImporter.php
+++ b/app/Importer/ConsumableImporter.php
@@ -208,5 +208,6 @@ class ConsumableImporter extends ItemImporter
));
$this->log('Consumable '.$consumable->name.' checked out to '.($target->username ?? $target->id));
+ $this->maybeSendWelcomeEmail($target);
}
}
diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php
index dab76b52fa..f6d5a4bb4e 100644
--- a/app/Importer/Importer.php
+++ b/app/Importer/Importer.php
@@ -30,6 +30,49 @@ abstract class Importer
*/
protected $updating;
+ /**
+ * True when the operator ticked the "send welcome email to users"
+ * wizard checkbox. Set by setShouldNotify from ItemImportRequest.
+ * UserImporter overrides this default in its own class body; the
+ * base declaration here means subclasses like AssetImporter can
+ * read the flag without triggering PHPStan property-not-found on
+ * the dynamic assignment.
+ *
+ * @var bool
+ */
+ protected $send_welcome = false;
+
+ /**
+ * Send the "welcome to Snipe-IT" email to a user that was JUST
+ * created as a checkout target in this row, if the operator opted
+ * in on the wizard. wasRecentlyCreated is only true on the model
+ * instance that a save() call minted, so matched existing users
+ * don't retrigger the email on subsequent imports. Guarded on
+ * email + activated for parity with UserImporter's welcome path.
+ * Called from AssetImporter / AccessoryImporter / ConsumableImporter
+ * / LicenseImporter after a successful checkout to a user target.
+ */
+ protected function maybeSendWelcomeEmail($target): void
+ {
+ if (! $this->send_welcome) {
+ return;
+ }
+
+ if (! ($target instanceof User) || ! $target->wasRecentlyCreated) {
+ return;
+ }
+
+ if (! $target->email || $target->activated != '1') {
+ return;
+ }
+
+ try {
+ $target->notify(new \App\Notifications\WelcomeNotification($target));
+ } catch (\Exception $e) {
+ Log::warning('Could not send welcome notification for imported user: '.$e->getMessage());
+ }
+ }
+
/**
* Default Map of item fields->csv names
*
@@ -45,8 +88,10 @@ abstract class Importer
'asset_tag' => 'asset tag',
'activated' => 'activated',
'category' => 'category',
- 'checkout_class' => 'checkout type', // Supports Location or User for assets. Using checkout_class instead of checkout_type because type exists on asset already.
+ 'checkout_class' => 'checkout type', // Supports Location, User, or Asset for assets. Using checkout_class instead of checkout_type because type exists on asset already.
'checkout_location' => 'checkout location',
+ 'checkout_asset' => 'checkout asset',
+ 'checkout_user' => 'checkout user',
'company' => 'company',
'item_name' => 'item name',
'item_number' => 'item number',
@@ -600,7 +645,12 @@ abstract class Importer
// can flow through to the user record. Previously this value
// was hard-coded to '' and the Department was orphaned.
'department_id' => $this->item['department_id'] ?? '',
- 'username' => $this->findCsvMatch($row, 'username'),
+ // Prefer an explicit username column; fall back to checkout_user
+ // (single-column shortcut for asset checkout to an existing or
+ // newly-created user, keyed on username). This preserves the
+ // create-or-fetch path when the operator only maps checkout_user
+ // and does not add a separate username column.
+ 'username' => $this->findCsvMatch($row, 'username') ?: $this->findCsvMatch($row, 'checkout_user'),
'activated' => $this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')),
'remote' => $this->fetchHumanBoolean(($this->findCsvMatch($row, 'remote'))),
];
diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php
index 069f153170..25563dbcd9 100644
--- a/app/Importer/ItemImporter.php
+++ b/app/Importer/ItemImporter.php
@@ -120,11 +120,84 @@ class ItemImporter extends Importer
return;
}
- if (strtolower($this->item['checkout_class']) === 'location' && $this->findCsvMatch($row, 'checkout_location') != null) {
- return Location::findOrFail($this->createOrFetchLocation($this->findCsvMatch($row, 'checkout_location')));
+ $checkoutClass = strtolower((string) $this->item['checkout_class']);
+ $checkoutLocation = $this->findCsvMatch($row, 'checkout_location');
+ $checkoutAsset = $this->findCsvMatch($row, 'checkout_asset');
+ $checkoutUser = $this->findCsvMatch($row, 'checkout_user');
+
+ // Checkout intent is inferred from which target-shape column has a
+ // value: checkout_asset (asset tag of parent asset), checkout_location
+ // (location name), checkout_user (username), or the multi-column
+ // user-identity path (email / username / full_name / etc.).
+ // checkout_class is only required as an explicit override when a row
+ // has more than one populated and needs disambiguation, or for
+ // backward-compat with pre-inference CSVs. Prior behavior required
+ // both a checkout_location AND a checkout_class column set to
+ // "Location" on every row; when checkout_class was missing the code
+ // silently fell through to user lookup, produced a null target, and
+ // no checkout event fired with no error surfaced. checkout_user is
+ // keyed on username specifically because email is not enforced as
+ // unique on the users table (the unique index was dropped in the
+ // 2015_07_25_055415 migration) and would silently match the wrong
+ // user in installs with duplicates. createOrFetchUser reads
+ // checkout_user as a username fallback, so the user path (lookup
+ // OR create when the row has enough identity data) works whether
+ // the operator maps username, checkout_user, or both.
+
+ // Explicit checkout_class wins when set and has a matching target
+ // column populated. Preserves the disambiguation escape hatch
+ // (e.g. checkout_class=user beats a populated checkout_location).
+ if ($checkoutClass === 'asset' && $checkoutAsset) {
+ return $this->findAssetCheckoutTarget($checkoutAsset);
+ }
+ if ($checkoutClass === 'location' && $checkoutLocation) {
+ return Location::findOrFail($this->createOrFetchLocation($checkoutLocation));
+ }
+ if (in_array($checkoutClass, ['user', 'person'], true)) {
+ return $this->createOrFetchUser($row);
+ }
+
+ // Inference paths. Any target-shape column populated is enough to
+ // route to that target type when no checkout_class contradicted it.
+ if ($checkoutAsset) {
+ return $this->findAssetCheckoutTarget($checkoutAsset);
+ }
+
+ if ($checkoutLocation) {
+ return Location::findOrFail($this->createOrFetchLocation($checkoutLocation));
+ }
+
+ // User path handles both checkout_user (single-column shortcut) and
+ // the multi-column user-identity shape. createOrFetchUser looks up
+ // by username first and creates a new user if the row has enough
+ // additional identity data (full_name / first_name / email).
+ return $this->createOrFetchUser($row);
+ }
+
+ /**
+ * Look up an existing asset by tag to use as a checkout target. We do
+ * NOT auto-create assets here the way createOrFetchLocation does. A
+ * checkout target is an existing physical thing; creating a phantom
+ * asset just to satisfy a checkout row would mask CSV typos and
+ * pollute the inventory. Returns null when the tag doesn't resolve,
+ * which the caller in AssetImporter surfaces as a per-row warning
+ * (see the checkoutColumnPopulated block there).
+ */
+ protected function findAssetCheckoutTarget($assetTag)
+ {
+ if (empty($assetTag)) {
+ return null;
}
- return $this->createOrFetchUser($row);
+ $asset = \App\Models\Asset::where('asset_tag', (string) $assetTag)->first();
+
+ if (! $asset) {
+ $this->log('WARNING: checkout_asset "'.$assetTag.'" does not match any existing asset tag. The checkout will be skipped.');
+
+ return null;
+ }
+
+ return $asset;
}
/**
diff --git a/app/Importer/LicenseImporter.php b/app/Importer/LicenseImporter.php
index 77ec2ad64e..f0b4203a28 100644
--- a/app/Importer/LicenseImporter.php
+++ b/app/Importer/LicenseImporter.php
@@ -285,6 +285,8 @@ class LicenseImporter extends ItemImporter
}
$targetLicense->save();
+ $this->maybeSendWelcomeEmail($checkout_target);
+
return;
}
diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.php
index 3341190937..61e507520e 100644
--- a/app/Livewire/Importer.php
+++ b/app/Livewire/Importer.php
@@ -405,9 +405,12 @@ class Importer extends Component
'supplier' => trans('general.supplier'),
'warranty_months' => trans('admin/hardware/form.warranty'),
/**
- * Checkout fields:
- * Assets can be checked out to other assets, people, or locations, but we currently
- * only support checkout to people and locations in the importer
+ * Checkout fields. Assets can be checked out to other assets, people, or
+ * locations. Which target the importer picks is inferred from which of the
+ * three target-shape columns has a value on the row (checkout_asset,
+ * checkout_location, or the user-identity columns). checkout_class stays
+ * available as an explicit override when a row has more than one populated
+ * and needs disambiguation, or for backward-compat with pre-inference CSVs.
**/
'checkout_class' => trans('general.importer.checkout_type'),
'first_name' => trans('general.importer.checked_out_to_first_name'),
@@ -416,6 +419,8 @@ class Importer extends Component
'email' => trans('general.importer.checked_out_to_email'),
'username' => trans('general.importer.checked_out_to_username'),
'checkout_location' => trans('general.importer.checkout_location'),
+ 'checkout_asset' => trans('general.importer.checkout_asset'),
+ 'checkout_user' => trans('general.importer.checkout_user'),
/**
* These are here so users can import history, to replace the dinosaur that
* was the history importer
@@ -1281,6 +1286,41 @@ class Importer extends Component
//
}
+ /**
+ * True when the current field_map maps any user-identifying column
+ * (username, email, first/last/full/display name, or checkout_user).
+ * Asset / accessory / consumable / license imports may check items
+ * out to users, in which case the wizard should surface the
+ * send-welcome checkbox even though the import type isn't 'user'.
+ * The welcome email itself only fires when a new user is actually
+ * created; existing-user matches don't retrigger it.
+ */
+ #[Computed]
+ public function hasUserCheckoutMapping(): bool
+ {
+ if (empty($this->field_map) || ! is_array($this->field_map)) {
+ return false;
+ }
+
+ $userIdentityFields = [
+ 'username',
+ 'checkout_user',
+ 'email',
+ 'first_name',
+ 'last_name',
+ 'full_name',
+ 'display_name',
+ ];
+
+ foreach ($this->field_map as $mapped) {
+ if (in_array($mapped, $userIdentityFields, true)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
#[Computed]
public function files()
{
diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon
index 2dd49b489d..71e0dc00d2 100644
--- a/phpstan-baseline.neon
+++ b/phpstan-baseline.neon
@@ -4768,13 +4768,13 @@ parameters:
-
message: '#^Method App\\Importer\\ItemImporter\:\:determineCheckout\(\) should return App\\Importer\\SnipeModel\|null but returns App\\Models\\Location\|Illuminate\\Database\\Eloquent\\Collection\<int, App\\Models\\Location\>\.$#'
identifier: return.type
- count: 1
+ count: 2
path: app/Importer/ItemImporter.php
-
message: '#^Method App\\Importer\\ItemImporter\:\:determineCheckout\(\) should return App\\Importer\\SnipeModel\|null but returns App\\Models\\User\.$#'
identifier: return.type
- count: 1
+ count: 2
path: app/Importer/ItemImporter.php
-
diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.php
index bddaf7fd48..43569a1a99 100644
--- a/resources/lang/en-US/general.php
+++ b/resources/lang/en-US/general.php
@@ -644,6 +644,8 @@ return [
'manager_employee_num' => 'Manager Employee Number',
'checkout_type' => 'Checkout Type',
'checkout_location' => 'Checkout to Location',
+ 'checkout_asset' => 'Checkout to Asset Tag',
+ 'checkout_user' => 'Checkout to Username',
'image_filename' => 'Image Filename',
'do_not_import' => 'Do Not Import',
'vip' => 'VIP',
diff --git a/resources/views/livewire/importer.blade.php b/resources/views/livewire/importer.blade.php
index 43b795af1a..f59369a1ef 100644
--- a/resources/views/livewire/importer.blade.php
+++ b/resources/views/livewire/importer.blade.php
@@ -422,7 +422,15 @@
</div>
@endif
- @if ($typeOfImport === 'user')
+ @if ($typeOfImport === 'user' || $this->hasUserCheckoutMapping)
+ {{-- Also shown for non-user imports (asset,
+ accessory, etc.) when the current column
+ mapping includes any user-identifying
+ field, since those imports may check
+ items out to users. The welcome email
+ only fires for users that are actually
+ created by the importer; existing-user
+ matches don't retrigger it. --}}
<x-form.checkbox-row
name="send_welcome"
:label="trans('general.send_welcome_email_to_users')"
diff --git a/tests/Feature/Importing/AssetImportCheckoutAcceptanceTest.php b/tests/Feature/Importing/AssetImportCheckoutAcceptanceTest.php
new file mode 100644
index 0000000000..1166355152
--- /dev/null
+++ b/tests/Feature/Importing/AssetImportCheckoutAcceptanceTest.php
@@ -0,0 +1,157 @@
+<?php
+
+namespace Tests\Feature\Importing;
+
+use App\Models\Asset;
+use App\Models\AssetModel;
+use App\Models\Category;
+use App\Models\CheckoutAcceptance;
+use App\Models\Company;
+use App\Models\Import;
+use App\Models\Location;
+use App\Models\Statuslabel;
+use App\Models\User;
+use Illuminate\Http\UploadedFile;
+use PHPUnit\Framework\Attributes\Test;
+use Tests\TestCase;
+
+/**
+ * Pin the "CSV import creates a checkout_acceptance row when the imported
+ * asset requires acceptance and is being checked out to a user" behavior.
+ *
+ * The import path routes through Asset::checkOut which fires
+ * CheckoutableCheckedOut. CheckoutableListener::handleAcceptance responds
+ * by calling CreateCheckoutAcceptanceAction::run when the target is a
+ * User and the checkoutable's category requires acceptance. This is the
+ * same code path the UI checkout uses. No importer-specific gate exists.
+ * Without this regression test a future refactor of the listener or the
+ * importer could silently drop acceptance creation on imported checkouts,
+ * leaving imported assets in an unaccepted-but-checked-out state that
+ * would only surface later in the acceptance-alerting cron.
+ */
+class AssetImportCheckoutAcceptanceTest extends TestCase
+{
+ private function createFakeUploadedFile(string $filename, string $content): UploadedFile
+ {
+ $path = tempnam(sys_get_temp_dir(), 'csv');
+ file_put_contents($path, $content);
+
+ return new UploadedFile($path, $filename, 'text/csv', null, true);
+ }
+
+ #[Test]
+ public function importing_a_user_checkout_creates_an_acceptance_record_when_category_requires_it(): void
+ {
+ $category = Category::factory()->create([
+ 'category_type' => 'asset',
+ 'require_acceptance' => true,
+ ]);
+ Location::factory()->create();
+ $statusLabel = Statuslabel::factory()->create();
+ Company::factory()->create();
+ $assetModel = AssetModel::factory()->for($category, 'category')->create(['name' => 'Acceptance Test Model']);
+
+ $target = User::factory()->create(['username' => 'accepting_user']);
+ $importer = User::factory()->canImport()->create();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'ACCEPT-001', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user\n";
+ $csv .= "ACCEPT-001,{$target->username}\n";
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.store'), [
+ 'files' => [
+ $this->createFakeUploadedFile('acceptance.csv', $csv),
+ ],
+ ])
+ ->assertSuccessful();
+
+ $import = Import::latest()->first();
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.importFile', $import->id), [
+ 'import-type' => 'asset',
+ 'import-update' => true,
+ 'column-mappings' => [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ ],
+ ])
+ ->assertSuccessful();
+
+ $imported = Asset::where('asset_tag', 'ACCEPT-001')->firstOrFail();
+ $this->assertSame($target->id, $imported->assigned_to);
+
+ $this->assertDatabaseHas('checkout_acceptances', [
+ 'checkoutable_type' => Asset::class,
+ 'checkoutable_id' => $imported->id,
+ 'assigned_to_id' => $target->id,
+ 'accepted_at' => null,
+ 'declined_at' => null,
+ ]);
+ }
+
+ #[Test]
+ public function importing_a_location_checkout_does_not_create_an_acceptance_record(): void
+ {
+ // Locations can't "accept" anything; the listener guards on
+ // target instanceof User. Pinning this so a future change to the
+ // guard doesn't accidentally start creating orphan acceptance
+ // rows for location checkouts.
+ $category = Category::factory()->create([
+ 'category_type' => 'asset',
+ 'require_acceptance' => true,
+ ]);
+ $statusLabel = Statuslabel::factory()->create();
+ Company::factory()->create();
+ $assetModel = AssetModel::factory()->for($category, 'category')->create();
+ $destination = Location::factory()->create(['name' => 'Storage Room B']);
+
+ $importer = User::factory()->canImport()->create();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'ACCEPT-002', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout location\n";
+ $csv .= "ACCEPT-002,{$destination->name}\n";
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.store'), [
+ 'files' => [
+ $this->createFakeUploadedFile('acceptance-location.csv', $csv),
+ ],
+ ])
+ ->assertSuccessful();
+
+ $import = Import::latest()->first();
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.importFile', $import->id), [
+ 'import-type' => 'asset',
+ 'import-update' => true,
+ 'column-mappings' => [
+ 'asset tag' => 'asset_tag',
+ 'checkout location' => 'checkout_location',
+ ],
+ ])
+ ->assertSuccessful();
+
+ $imported = Asset::where('asset_tag', 'ACCEPT-002')->firstOrFail();
+ $this->assertSame($destination->id, $imported->assigned_to);
+ $this->assertSame(Location::class, $imported->assigned_type);
+
+ $this->assertSame(
+ 0,
+ CheckoutAcceptance::where('checkoutable_type', Asset::class)
+ ->where('checkoutable_id', $imported->id)
+ ->count(),
+ 'A location checkout must not create an acceptance record.',
+ );
+ }
+}
diff --git a/tests/Feature/Importing/AssetImportCheckoutLocationTest.php b/tests/Feature/Importing/AssetImportCheckoutLocationTest.php
new file mode 100644
index 0000000000..3b09e0fb6d
--- /dev/null
+++ b/tests/Feature/Importing/AssetImportCheckoutLocationTest.php
@@ -0,0 +1,376 @@
+<?php
+
+namespace Tests\Feature\Importing;
+
+use App\Models\Asset;
+use App\Models\AssetModel;
+use App\Models\Category;
+use App\Models\Company;
+use App\Models\Import;
+use App\Models\Location;
+use App\Models\Statuslabel;
+use App\Models\User;
+use App\Notifications\WelcomeNotification;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Notification;
+use PHPUnit\Framework\Attributes\Test;
+use Tests\TestCase;
+
+/**
+ * Regression coverage for the reporter case where a CSV with a single
+ * "checked out to: Location" column mapped to checkout_location did not
+ * actually check the asset out to the location. The prior code required
+ * BOTH a checkout_class column (with value "Location") AND a
+ * checkout_location column; missing the first silently fell through to
+ * user lookup, produced no target, and skipped the checkout with no
+ * error surfaced. Location intent is now inferred when checkout_location
+ * has a value and no explicit checkout_class contradicts it.
+ */
+class AssetImportCheckoutLocationTest extends TestCase
+{
+ private function seedBaseline(): array
+ {
+ $category = Category::factory()->create(['category_type' => 'asset']);
+ Location::factory()->create();
+ $statusLabel = Statuslabel::factory()->create();
+ Company::factory()->create();
+ $assetModel = AssetModel::factory()->for($category, 'category')->create(['name' => 'Checkout Location Test Model']);
+
+ return [$category, $statusLabel, $assetModel];
+ }
+
+ private function importCsv(string $csv, array $mappings, array $extraPayload = []): void
+ {
+ $importer = User::factory()->canImport()->create();
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.store'), [
+ 'files' => [
+ $this->createFakeUploadedFile('checkout-location.csv', $csv),
+ ],
+ ])
+ ->assertSuccessful();
+
+ $import = Import::latest()->first();
+
+ $this->actingAsForApi($importer)
+ ->postJson(route('api.imports.importFile', $import->id), array_merge([
+ 'import-type' => 'asset',
+ 'import-update' => true,
+ 'column-mappings' => $mappings,
+ ], $extraPayload))
+ ->assertSuccessful();
+ }
+
+ private function createFakeUploadedFile(string $filename, string $content): UploadedFile
+ {
+ $path = tempnam(sys_get_temp_dir(), 'csv');
+ file_put_contents($path, $content);
+
+ return new UploadedFile($path, $filename, 'text/csv', null, true);
+ }
+
+ #[Test]
+ public function checkout_location_column_alone_checks_asset_out_to_the_named_location(): void
+ {
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+ $destination = Location::factory()->create(['name' => 'BIC_ALS Office_AD']);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHKLOC-001', 'assigned_to' => null]);
+
+ $csv = "asset tag,checked out to: Location\n";
+ $csv .= "CHKLOC-001,{$destination->name}\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checked out to: Location' => 'checkout_location',
+ ]);
+
+ $imported = Asset::where('asset_tag', 'CHKLOC-001')->firstOrFail();
+
+ $this->assertSame(
+ $destination->id,
+ $imported->assigned_to,
+ 'checkout_location alone must be enough to route a checkout to the location.',
+ );
+ $this->assertSame(
+ Location::class,
+ $imported->assigned_type,
+ 'The checkout target type must be Location.',
+ );
+ }
+
+ #[Test]
+ public function checkout_class_location_plus_checkout_location_still_works(): void
+ {
+ // Backward-compat pin. Operators who already have the two-column
+ // shape from earlier docs must not regress when the inference path
+ // is added.
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+ $destination = Location::factory()->create(['name' => 'Legacy Two Column Room']);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHKLOC-002', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout type,checkout location\n";
+ $csv .= "CHKLOC-002,Location,{$destination->name}\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout type' => 'checkout_class',
+ 'checkout location' => 'checkout_location',
+ ]);
+
+ $imported = Asset::where('asset_tag', 'CHKLOC-002')->firstOrFail();
+
+ $this->assertSame($destination->id, $imported->assigned_to);
+ $this->assertSame(Location::class, $imported->assigned_type);
+ }
+
+ #[Test]
+ public function checkout_asset_column_alone_checks_asset_out_to_the_named_parent_asset(): void
+ {
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+
+ $parent = Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'PARENT-001']);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHILD-001', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout asset\n";
+ $csv .= "CHILD-001,{$parent->asset_tag}\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout asset' => 'checkout_asset',
+ ]);
+
+ $child = Asset::where('asset_tag', 'CHILD-001')->firstOrFail();
+
+ $this->assertSame($parent->id, $child->assigned_to);
+ $this->assertSame(Asset::class, $child->assigned_type);
+ }
+
+ #[Test]
+ public function checkout_asset_with_unknown_tag_skips_checkout_and_does_not_assign(): void
+ {
+ // Assets are never auto-created as checkout targets; a typo in
+ // the tag column produces a skipped checkout, not a phantom asset.
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHILD-002', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout asset\n";
+ $csv .= "CHILD-002,DOES-NOT-EXIST\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout asset' => 'checkout_asset',
+ ]);
+
+ $child = Asset::where('asset_tag', 'CHILD-002')->firstOrFail();
+
+ $this->assertNull($child->assigned_to, 'A checkout_asset value that does not match must not assign.');
+ }
+
+ #[Test]
+ public function checkout_user_column_alone_checks_asset_out_to_the_matching_user(): void
+ {
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+ $targetUser = User::factory()->create(['username' => 'checkout_user_target']);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHKUSR-001', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user\n";
+ $csv .= "CHKUSR-001,{$targetUser->username}\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ ]);
+
+ $imported = Asset::where('asset_tag', 'CHKUSR-001')->firstOrFail();
+
+ $this->assertSame($targetUser->id, $imported->assigned_to);
+ $this->assertSame(User::class, $imported->assigned_type);
+ }
+
+ #[Test]
+ public function checkout_user_creates_new_user_when_row_has_enough_identity_data(): void
+ {
+ // Preserves the existing "create user on the fly" behavior of
+ // createOrFetchUser: if the row carries additional identity
+ // columns (email, full_name, etc.) alongside a checkout_user
+ // username that does not yet exist, the user is created and the
+ // asset is checked out to them in a single import pass.
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHKUSR-002', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user,first name,last name,email\n";
+ $csv .= "CHKUSR-002,newhire,New,Hire,[email protected]\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ 'first name' => 'first_name',
+ 'last name' => 'last_name',
+ 'email' => 'email',
+ ]);
+
+ $newUser = User::where('username', 'newhire')->firstOrFail();
+ $imported = Asset::where('asset_tag', 'CHKUSR-002')->firstOrFail();
+
+ $this->assertSame($newUser->id, $imported->assigned_to);
+ $this->assertSame(User::class, $imported->assigned_type);
+ }
+
+ #[Test]
+ public function send_welcome_email_fires_when_checkout_creates_a_new_user_and_the_flag_is_on(): void
+ {
+ Notification::fake();
+
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'WELCOME-001', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user,first name,last name,email\n";
+ $csv .= "WELCOME-001,welcome_new,Welcome,New,[email protected]\n";
+
+ $this->importCsv(
+ $csv,
+ [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ 'first name' => 'first_name',
+ 'last name' => 'last_name',
+ 'email' => 'email',
+ ],
+ ['send-welcome' => true],
+ );
+
+ $newUser = User::where('username', 'welcome_new')->firstOrFail();
+ Notification::assertSentTo($newUser, WelcomeNotification::class);
+ }
+
+ #[Test]
+ public function send_welcome_email_does_not_fire_for_existing_users(): void
+ {
+ Notification::fake();
+
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+ $existing = User::factory()->create([
+ 'username' => 'existing_user',
+ 'email' => '[email protected]',
+ ]);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'WELCOME-002', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user\n";
+ $csv .= "WELCOME-002,{$existing->username}\n";
+
+ $this->importCsv(
+ $csv,
+ [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ ],
+ ['send-welcome' => true],
+ );
+
+ Notification::assertNotSentTo($existing, WelcomeNotification::class);
+ }
+
+ #[Test]
+ public function send_welcome_email_does_not_fire_when_the_flag_is_off_even_for_a_new_user(): void
+ {
+ Notification::fake();
+
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'WELCOME-003', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout user,first name,last name,email\n";
+ $csv .= "WELCOME-003,welcome_off,Welcome,Off,[email protected]\n";
+
+ $this->importCsv(
+ $csv,
+ [
+ 'asset tag' => 'asset_tag',
+ 'checkout user' => 'checkout_user',
+ 'first name' => 'first_name',
+ 'last name' => 'last_name',
+ 'email' => 'email',
+ ],
+ // no 'send-welcome' key
+ );
+
+ $newUser = User::where('username', 'welcome_off')->firstOrFail();
+ Notification::assertNotSentTo($newUser, WelcomeNotification::class);
+ }
+
+ #[Test]
+ public function explicit_checkout_class_user_overrides_present_checkout_location(): void
+ {
+ // Disambiguation escape hatch: if the operator explicitly names
+ // "user" as the checkout class AND the row has user-identity
+ // fields, the user path wins even when checkout_location is also
+ // mapped. This preserves the older opt-in-to-user semantic for
+ // anyone using the two-column disambiguating shape.
+ [$category, $statusLabel, $assetModel] = $this->seedBaseline();
+ Location::factory()->create(['name' => 'Not Used']);
+ $targetUser = User::factory()->create(['username' => 'checkout_target_user']);
+
+ Asset::factory()
+ ->for($assetModel, 'model')
+ ->for($statusLabel, 'status')
+ ->create(['asset_tag' => 'CHKLOC-003', 'assigned_to' => null]);
+
+ $csv = "asset tag,checkout type,checkout location,username\n";
+ $csv .= "CHKLOC-003,User,Not Used,{$targetUser->username}\n";
+
+ $this->importCsv($csv, [
+ 'asset tag' => 'asset_tag',
+ 'checkout type' => 'checkout_class',
+ 'checkout location' => 'checkout_location',
+ 'username' => 'username',
+ ]);
+
+ $imported = Asset::where('asset_tag', 'CHKLOC-003')->firstOrFail();
+
+ $this->assertSame(
+ $targetUser->id,
+ $imported->assigned_to,
+ 'Explicit checkout_class=user must route to the user even when checkout_location is present.',
+ );
+ $this->assertSame(User::class, $imported->assigned_type);
+ }
+}