A free open source IT asset/license management system
retrack webhook component
Godfrey M3ad393592055
diff --git a/app/Livewire/IntegrationSettingsForm.php b/app/Livewire/IntegrationSettingsForm.phpnew file mode 100644index 0000000000..c8009af39b--- /dev/null+++ b/app/Livewire/IntegrationSettingsForm.php@@ -0,0 +1,371 @@+<?php++namespace App\Livewire;++use App\Helpers\Helper;+use App\Models\Setting;+use App\Models\Company;+use App\Rules\ExternalUrl;+use GuzzleHttp\Client;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\RateLimiter;+use Illuminate\Support\Facades\Validator;+use Illuminate\Support\Str;+use Livewire\Component;+use Osama\LaravelTeamsNotification\TeamsNotification;++class IntegrationSettingsForm extends Component+{+ public $webhook_endpoint;++ public $webhook_channel;++ public $webhook_botname;++ public $isDisabled = 'disabled';++ public $webhook_name;++ public $webhook_link;++ public $webhook_placeholder;++ public $webhook_icon;++ public $webhook_selected;++ public $teams_webhook_deprecated;++ public array $webhook_text;++ public ?Company $company = null;++ public $save_button;+ public array $savedWebhook = [];++ public $webhook_endpoint_rules;++ public ?string $warning = null;++ public ?string $success = null;++ public ?string $error = null;++ protected function rules(): array+ {+ return [+ 'webhook_endpoint' => [+ 'nullable',+ 'required_with:webhook_channel',+ 'url',+ new ExternalUrl,+ ],+ 'webhook_channel' => 'required_with:webhook_endpoint|starts_with:#|nullable',+ 'webhook_botname' => 'string|nullable',+ ];+ }++ /**+ * Route-level middleware on the notifications settings page requires+ * superuser, but snapshot replay to POST /livewire/update bypasses+ * that gate. Without this check, a low-privilege user with a valid+ * snapshot could invoke testWebhook / clearSettings / submit and+ * mutate global webhook configuration or exfiltrate the configured+ * webhook_endpoint / channel through the render payload.+ */+ public function boot(): void+ {+ if (! auth()->user()?->isSuperUser()) {+ abort(403);+ }+ }++ public function mount(?Company $company = null)+ {+ if ($company) {+ $this->company = $company;+ }++ $this->webhook_text = [+ 'slack' => [+ 'name' => trans('admin/settings/general.slack'),+ 'icon' => 'fab fa-slack',+ 'placeholder' => 'https://hooks.slack.com/services/XXXXXXXXXXXXXXXXXXXXX',+ 'link' => 'https://api.slack.com/messaging/webhooks',+ ],+ 'general' => [+ 'name' => trans('admin/settings/general.general_webhook'),+ 'icon' => 'fab fa-hashtag',+ 'placeholder' => trans('general.url'),+ 'link' => '',+ ],+ 'google' => [+ 'name' => trans('admin/settings/general.google_workspaces'),+ 'icon' => 'fa-brands fa-google',+ 'placeholder' => 'https://chat.googleapis.com/v1/spaces/xxxxxxxx/messages?key=xxxxxx',+ 'link' => 'https://developers.google.com/chat/how-tos/webhooks#register_the_incoming_webhook',+ ],+ 'microsoft' => [+ 'name' => trans('admin/settings/general.ms_teams'),+ 'icon' => 'fa-brands fa-microsoft',+ 'placeholder' => 'https://abcd.webhook.office.com/webhookb2/XXXXXXX',+ 'link' => 'https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498',+ ],+ ];++ $this->loadWebhookSettings();+ $this->updatedWebhookSelected();++ $this->save_button = trans('general.save');+++ $this->teams_webhook_deprecated = !Str::contains($this->webhook_endpoint, 'workflows'); // consider moving this to webhook_link updated? (updatedWebhookLink?)++ if ($this->webhook_endpoint != null && $this->webhook_channel != null) {+ $this->isDisabled = '';+ }+ if ($this->webhook_selected === 'microsoft' && $this->teams_webhook_deprecated) { //since this is URL-aware, maybe also move this?+ $this->warning = trans('admin/settings/message.webhook.ms_teams_deprecation');+ }+ }++ public function updated($field)+ {+ //anything changes; then clear the success message (and error message)+ $this->success = null;+ $this->error = null;+ $this->validateOnly($field);++ }++ public function updatedWebhookSelected()+ {+ $this->webhook_name = $this->webhook_text[$this->webhook_selected]['name'];+ $this->webhook_icon = $this->webhook_text[$this->webhook_selected]['icon'];+ $this->webhook_placeholder = $this->webhook_text[$this->webhook_selected]['placeholder'];+ $this->webhook_link = $this->webhook_text[$this->webhook_selected]['link'];++ if ($this->webhook_selected === $this->savedWebhook['selected']) {+ $this->webhook_endpoint = $this->savedWebhook['endpoint'];+ $this->webhook_channel = $this->savedWebhook['channel'];+ $this->webhook_botname = $this->savedWebhook['botname'];+ } else {+ $this->webhook_endpoint = null;+ $this->webhook_channel = null;+ $this->webhook_botname = null;++ if (in_array($this->webhook_selected, ['microsoft', 'google'])) {+ $this->webhook_channel = '#NA';+ }+ }+ if ($this->webhook_selected != 'slack') { // TODO: hrm. Wouldn't we want to test all of them? Or at least some of them? Maybe not "generic webhook"?+ $this->isDisabled = '';+ $this->save_button = trans('general.save');+ }+ }++ public function updatedWebhookEndpoint()+ {+ if ($this->webhook_selected !== 'microsoft') {+ $this->teams_webhook_deprecated = false;+ $this->warning = null;+ return;+ }++ $this->teams_webhook_deprecated = filled($this->webhook_endpoint)+ && !Str::contains($this->webhook_endpoint, 'workflows');++ $this->warning = $this->webhook_selected === 'microsoft' && $this->teams_webhook_deprecated+ ? trans('admin/settings/message.webhook.ms_teams_deprecation')+ : null;+ }++ public function render()+ {+ if (empty($this->webhook_endpoint) || empty($this->webhook_channel)) {+ $this->isDisabled = 'disabled';+ $this->save_button = trans('admin/settings/general.webhook_presave');+ }++ return view('livewire.integration-settings-form');++ }++ public function clearSettings()+ {++ if (Helper::isDemoMode()) {+ $this->error = trans('general.feature_disabled');+ } else {+ $this->webhook_endpoint = '';+ $this->webhook_channel = '';+ $this->webhook_botname = '';++ $source = $this->webhookSource();++ $source->webhook_endpoint = '';+ $source->webhook_channel = '';+ $source->webhook_botname = '';++ $source->save();++ $this->success = trans('admin/settings/message.update.success');+ }+ }++ public function submit()+ {+ if (Helper::isDemoMode()) {+ $this->error = trans('general.feature_disabled');+ } else {+ $this->validate();+ $source = $this->webhookSource();++ $source->webhook_selected = $this->webhook_selected;+ $source->webhook_endpoint = $this->webhook_endpoint;+ $source->webhook_channel = $this->webhook_channel;+ $source->webhook_botname = $this->webhook_botname;+ $source->save();++ $this->savedWebhook = [+ 'selected' => $this->webhook_selected,+ 'endpoint' => $this->webhook_endpoint,+ 'channel' => $this->webhook_channel,+ 'botname' => $this->webhook_botname,+ ];++ $this->success = trans('admin/settings/message.update.success');+ }++ }++ public function universalWebhookTest()+ {+ $executed = RateLimiter::attempt(+ key: 'test-connection:' . auth()->id(),+ maxAttempts: 5,+ decaySeconds: 60,+ callback: function () {+ $validator = Validator::make(+ ['webhook_endpoint' => $this->webhook_endpoint],+ ['webhook_endpoint' => ['required', 'url', new ExternalUrl]],+ );++ if ($validator->fails()) {+ $this->isDisabled = 'disabled';+ $this->save_button = trans('admin/settings/general.webhook_presave');++ $this->error = $validator->errors()->first('webhook_endpoint');+ return;+ }+ $this->error = '';+ $this->success = '';++ $payload = match ($this->webhook_selected) {+ 'slack', 'general' => [+ 'channel' => e($this->webhook_channel),+ 'text' => trans('general.webhook_test_msg', ['app' => $this->webhook_name]),+ 'username' => e($this->webhook_botname),+ 'icon_emoji' => ':heart:',+ ],+ 'google' => [+ 'text' => trans('general.webhook_test_msg', ['app' => $this->webhook_name]),+ ],+ 'microsoft' => [+ '@type' => 'MessageCard',+ '@context' => 'http://schema.org/extensions',+ 'summary' => trans('mail.snipe_webhook_summary'),+ 'title' => trans('mail.snipe_webhook_test'),+ 'text' => trans('general.webhook_test_msg', ['app' => $this->webhook_name]),+ ],+ default => throw new \Exception("Unknown provider")+ };++ $status_code = null;++ try {+ if ($this->webhook_selected == "microsoft" && !$this->teams_webhook_deprecated) {+ //new-fangled webhook - use package+ $notification = new TeamsNotification($this->webhook_endpoint);+ $message = trans('general.webhook_test_msg', ['app' => $this->webhook_name]);+ $status_code = $notification->success()->sendMessage($message);+ } else {+ $response = Http::withHeaders([+ 'content-type' => 'application/json',+ ])->withOptions(['allow_redirects' => false])+ ->post($this->webhook_endpoint, $payload)/*->throw()*/+ ;+ $status_code = $response->getStatusCode();+ }++ if ($status_code >= 300 && $status_code < 400) {+ //these, still, might happen. It seems like allow_redirects being false just doesn't follow them, it doesn't cause an Exception on them.+ $this->error = trans('admin/settings/message.webhook.error_redirect', ['endpoint' => $this->webhook_endpoint]);+ //TODO: one possibliity here is to re-throw so that everything goes back through the exception handler?+ } elseif ($status_code >= 400 && $status_code < 500) {+ //this _shouldn't_ happen because the "->throw()" should catch it+ $this->error = trans('admin/settings/message.webhook.error_redirect', ['endpoint' => $this->webhook_endpoint]);+ } elseif ($status_code >= 500) {+ //this _shouldn't_ happen because the "->throw()" should catch it+ $this->error = trans('admin/settings/message.webhook.error_server');+ } elseif ($status_code >= 200 && $status_code < 300) {+ $this->isDisabled = '';+ $this->save_button = trans('general.save');++ $this->success = trans('admin/settings/message.webhook.success', ['webhook_name' => $this->webhook_name]);+ return true; // This is just for EqualTiming to use; this method on this controller doesn't actually return anything+ } else {+ throw new \Exception(trans('admin/settings/message.webhook.error_misc'));+ }++ } catch (\Exception $e) {+ Log::warning('Webhook test failed', [+ 'endpoint' => $this->webhook_endpoint,+ 'app' => $this->webhook_name,+ 'exception' => $e::class,+ 'message' => $e->getMessage(),+ 'file' => $e->getFile(),+ 'line' => $e->getLine(),+ ]);++ $this->isDisabled = 'disabled';+ $this->save_button = trans('admin/settings/general.webhook_presave');++ $this->error = trans('admin/settings/message.webhook.error', [+ 'error_message' => $e->getMessage(),+ 'app' => $this->webhook_name,+ ]);+ return false;+ }+ },+ );++ if (!$executed) {+ $this->addError('connection', trans('admin/settings/general.rate_limited'));+ }+ }++ protected function webhookSource(): Company|Setting+ {+ return $this->company ?? Setting::getSettings();+ }++ protected function loadWebhookSettings(): void+ {+ $source = $this->webhookSource();++ $this->webhook_selected = $source->webhook_selected ?: 'slack';+ $this->webhook_endpoint = $source->webhook_endpoint;+ $this->webhook_channel = $source->webhook_channel;+ $this->webhook_botname = $source->webhook_botname;++ $this->savedWebhook = [+ 'selected' => $this->webhook_selected,+ 'endpoint' => $this->webhook_endpoint,+ 'channel' => $this->webhook_channel,+ 'botname' => $this->webhook_botname,+ ];++ }+}\ No newline at end of filediff --git a/resources/views/livewire/integration-settings-form.blade.php b/resources/views/livewire/integration-settings-form.blade.phpnew file mode 100644index 0000000000..95f033ed36--- /dev/null+++ b/resources/views/livewire/integration-settings-form.blade.php@@ -0,0 +1,159 @@+<div><!-- livewire div - do not remove -->+ <form class="form-horizontal" role="form" wire:submit.prevent="submit">+ {{csrf_field()}}+ @if ($warning)+ <x-alert type="warning">+ {!! $warning !!}+ </x-alert>+ @endif+ <div class="row">++ <div class="col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2">++ <div class="panel box box-default">++ <div class="box-header with-border">+ <h2 class="box-title">+ <i class="{{$webhook_icon}}"></i> {{ trans('admin/settings/general.webhook', ['app' => $webhook_name] ) }}+ </h2>+ </div>++ <div class="box-body">+ @if($webhook_selected != 'general')+ <div class="col-md-12">+ <p>+ {!! trans('admin/settings/general.webhook_integration_help',array('webhook_link' => $webhook_link, 'app' => $webhook_name)) !!}+ </p>+ <br>+ </div>+ @endif++ <div class="col-md-12" style="border-top: 0px;">++ @if($success)+ <x-alert type="success">+ {{$success}}+ </x-alert>+ @endif+ @if($error)+ <x-alert type="danger">+ {{$error}}+ </x-alert>+ @endif+ <div class="form-group">+ <div class="col-md-2">+ <label for="webhook_selected">+ {{ trans('general.integration_option') }}++ </label>+ </div>+ <div class="col-md-9 required" wire:ignore>+ <x-input.select+ name="webhook_selected"+ id="select2"+ :options="['slack' => trans('admin/settings/general.slack'), 'general' => trans('admin/settings/general.general_webhook'),'google' => trans('admin/settings/general.google_workspaces'), 'microsoft' => trans('admin/settings/general.ms_teams')]"+ :selected="old('webhook_selected', $webhook_selected)"+ :disabled="Helper::isDemoMode()"+ :for-livewire="true"+ data-minimum-results-for-search="-1"+ class="form-control"+ style="width:100%"+ aria-label="webhook_selected"+ />+ </div>+ </div>++ @if (Helper::isDemoMode())+ @include('partials.forms.demo-mode')+ @endif++ <!--Webhook endpoint-->+ <div class="form-group{{ $errors->has('webhook_endpoint') ? ' error' : '' }}">+ <div class="col-md-2">+ <label for="webhook_endpoint">{{ trans('admin/settings/general.webhook_endpoint',['app' => $webhook_name ]) }}</label>+ </div>+ <div class="col-md-9 required">+ <input type="url" wire:model.change.live="webhook_endpoint" class="form-control" placeholder="{{$webhook_placeholder}}"{{ Helper::isDemoMode() ? ' disabled' : ''}}>+ <x-form.error name="webhook_endpoint" />+ </div>+ </div>++ @if (Helper::isDemoMode())+ @include('partials.forms.demo-mode')+ @endif+++ <!-- Webhook channel -->+ @if($webhook_selected != 'microsoft' && $webhook_selected!= 'google')+ <div class="form-group{{ $errors->has('webhook_channel') ? ' error' : '' }}">+ <div class="col-md-2">+ <label for="webhook_channel">{{ trans('admin/settings/general.webhook_channel',['app' => $webhook_name ]) }}</label>+ </div>+ <div class="col-md-9 required">+ <input type="text" wire:model.change.live="webhook_channel" class="form-control" placeholder="#IT-Ops" {{ Helper::isDemoMode() ? ' disabled' : ''}}>++ <x-form.error name="webhook_channel" />+ </div>+ </div>+ @endif++ @if (Helper::isDemoMode())+ @include('partials.forms.demo-mode')+ @endif++ <!-- Webhook botname -->+ @if($webhook_selected != 'microsoft' && $webhook_selected != 'google')+ <div class="form-group{{ $errors->has('webhook_botname') ? ' error' : '' }}">+ <div class="col-md-2">+ <label for="webhook_botname">{{ trans('admin/settings/general.webhook_botname',['app' => $webhook_name ]) }}</label>+ </div>+ <div class="col-md-9">+ <input type="text" wire:model.change.live="webhook_botname" class='form-control' placeholder="Snipe-Bot" {{ Helper::isDemoMode() ? ' disabled' : ''}}>+ <x-form.error name="webhook_botname" />+ </div><!--col-md-10-->+ </div>+ @endif+ @if (!Helper::isDemoMode())+ @include('partials.forms.demo-mode')+ @endif++ <!--Webhook Integration Test-->++ @if($webhook_endpoint != null && $webhook_channel != null)+ <div class="form-group">+ <div class="col-md-offset-2 col-md-9">+ <a href="#" wire:click.prevent="universalWebhookTest"+ class="btn btn-default btn-sm pull-left">+ <i class="{{$webhook_icon}}" aria-hidden="true"></i>+ {!! trans('admin/settings/general.webhook_test',['app' => ucwords($webhook_selected) ]) !!}+ </a>+ <div wire:loading>+ <span style="padding-left: 5px; font-size: 20px">+ <i class="fas fa-spinner fa-spin" aria-hidden="true"></i>+ </span>+ </div>+ </div>+ </div>+ @endif+ </div><!-- /.col-md-12 -->+ </div><!-- /.box-body -->++ <div class="box-footer">+ <div class="text-right col-md-12">++ <button type="reset" wire:click.prevent="clearSettings" class="col-md-2 text-left btn btn-danger pull-left"{{ Helper::isDemoMode() ? ' disabled' : ''}}>{{ trans('general.clear_and_save') }}</button>++ <a class="btn btn-link pull-left" href="{{ route('settings.index') }}">{{ trans('button.cancel') }}</a>+++ <button type="submit" {{$isDisabled}} class="btn btn-primary"{{ Helper::isDemoMode() ? ' disabled' : ''}}>+ <x-icon type="checkmark" /> {{ $save_button }}</button>++ </div> <!-- /.col-md-12 -->+ </div><!--box-footer-->++ </div> <!-- /.box -->+ </div> <!-- /.col-md-8-->+ </div> <!-- /.row -->+</form>+</div> <!-- /livewire div -->diff --git a/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckinTest.php b/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckinTest.phpnew file mode 100644index 0000000000..8af246aad4--- /dev/null+++ b/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckinTest.php@@ -0,0 +1,296 @@+<?php++namespace Tests\Feature\Notifications\Webhooks;++use App\Events\CheckoutableCheckedIn;+use App\Models\Accessory;+use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\Category;+use App\Models\Component;+use App\Models\LicenseSeat;+use App\Models\Location;+use App\Models\User;+use App\Notifications\CheckinAccessoryNotification;+use App\Notifications\CheckinAssetNotification;+use App\Notifications\CheckinComponentNotification;+use App\Notifications\CheckinLicenseSeatNotification;+use App\Notifications\CheckoutAssetNotification;+use Illuminate\Database\Eloquent\Model;+use Illuminate\Notifications\AnonymousNotifiable;+use Illuminate\Notifications\Messages\SlackMessage;+use Illuminate\Support\Facades\Notification;+use NotificationChannels\GoogleChat\GoogleChatMessage;+use PHPUnit\Framework\Attributes\DataProvider;+use PHPUnit\Framework\Attributes\Group;+use Tests\TestCase;+use App\Models\Setting;++#[Group('notifications')]+class IntegrationNotificationsUponCheckinTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();++ Notification::fake();+ }++ public static function assetCheckInTargets(): array+ {+ return [+ 'Asset checked out to user' => [fn () => User::factory()->create()],+ 'Asset checked out to asset' => [fn () => Asset::factory()->laptopMbp()->create()],+ 'Asset checked out to location' => [fn () => Location::factory()->create()],+ ];+ }++ public static function licenseCheckInTargets(): array+ {+ return [+ 'License checked out to user' => [fn () => User::factory()->create()],+ 'License checked out to asset' => [fn () => Asset::factory()->laptopMbp()->create()],+ ];+ }++ public function test_accessory_checkin_sends_slack_notification_when_setting_enabled()+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckInEvent(+ Accessory::factory()->create(),+ User::factory()->create(),+ );++ $this->assertSlackNotificationSent(CheckinAccessoryNotification::class);+ }++ public function test_accessory_checkin_does_not_send_slack_notification_when_setting_disabled()+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckInEvent(+ Accessory::factory()->create(),+ User::factory()->create(),+ );++ $this->assertNoSlackNotificationSent(CheckinAccessoryNotification::class);+ }++ #[DataProvider('assetCheckInTargets')]+ public function test_asset_checkin_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckInEvent(+ Asset::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckinAssetNotification::class);+ }++ #[DataProvider('assetCheckInTargets')]+ public function test_asset_checkin_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckInEvent(+ Asset::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckinAssetNotification::class);+ }++ #[DataProvider('assetCheckInTargets')]+ public function test_component_checkin_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckInEvent(+ Component::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckinComponentNotification::class);+ }++ #[DataProvider('assetCheckInTargets')]+ public function test_component_checkin_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckInEvent(+ Component::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckinComponentNotification::class);+ }++ public function test_slack_notification_is_still_sent_when_category_email_is_not_set_to_send_emails()+ {+ $this->settings->enableSlackWebhook();++ $category = Category::factory()->create([+ 'checkin_email' => false,+ 'eula_text' => null,+ 'require_acceptance' => false,+ 'use_default_eula' => false,+ ]);+ $assetModel = AssetModel::factory()->for($category)->create();+ $asset = Asset::factory()->for($assetModel, 'model')->assignedToUser()->create();++ $this->fireCheckInEvent(+ $asset,+ User::factory()->create(),+ );++ $this->assertSlackNotificationSent(CheckinAssetNotification::class);+ }++ public function test_asset_checkin_slack_notification_uses_updated_asset_location()+ {+ $this->settings->enableSlackWebhook();++ $previousLocation = Location::factory()->create(['name' => 'Region B']);+ $newLocation = Location::factory()->create(['name' => 'Office A']);+ $target = User::factory()->create(['location_id' => $previousLocation->id]);+ $asset = Asset::factory()->create(['location_id' => $previousLocation->id]);++ // Simulate post-checkin state while keeping a stale in-memory relation loaded.+ $asset->location_id = $newLocation->id;+ $asset->save();++ $this->fireCheckInEvent($asset, $target);++ Notification::assertSentTo(+ new AnonymousNotifiable,+ CheckinAssetNotification::class,+ fn (CheckinAssetNotification $notification): bool => $notification->item->location?->is($newLocation)+ );+ }++ #[DataProvider('licenseCheckInTargets')]+ public function test_license_checkin_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckInEvent(+ LicenseSeat::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckinLicenseSeatNotification::class);+ }++ #[DataProvider('licenseCheckInTargets')]+ public function test_license_checkin_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckInEvent(+ LicenseSeat::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckinLicenseSeatNotification::class);+ }++ private function fireCheckInEvent(Model $checkoutable, Model $target)+ {+ event(new CheckoutableCheckedIn(+ $checkoutable,+ $target,+ User::factory()->superuser()->create(),+ ''+ ));+ }++ #[DataProvider('checkinNotificationCases')]+ public function test_checkin_slack_notifications_can_be_built($createNotification)+ {+ $this->settings->enableSlackWebhook();++ $notification = $createNotification(Setting::getSettings());++ $this->assertInstanceOf(+ SlackMessage::class,+ $notification->toSlack()+ );+ }++ #[DataProvider('checkinNotificationCases')]+ public function test_checkin_google_chat_notifications_can_be_built($createNotification)+ {+ $this->settings->enableGoogleChatWebhook();++ $notification = $createNotification(Setting::getSettings());++ $this->assertInstanceOf(+ GoogleChatMessage::class,+ $notification->toGoogleChat()+ );+ }++ #[DataProvider('checkinNotificationCases')]+ public function test_checkin_microsoft_teams_workflow_notifications_can_be_built($createNotification)+ {+ $this->settings->enableMicrosoftTeamsWebhook();++ $notification = $createNotification(Setting::getSettings());++ $message = $notification->toMicrosoftTeams();++ $this->assertIsArray($message);+ $this->assertCount(2, $message);+ $this->assertIsString($message[0]);+ $this->assertIsArray($message[1]);+ }++ public static function checkinNotificationCases(): array+ {+ return [+ 'Asset' => [+ fn($webhookSource) => new CheckinAssetNotification(+ Asset::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ $webhookSource,+ ),+ ],++ 'Accessory' => [+ fn($webhookSource) => new CheckinAccessoryNotification(+ Accessory::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ $webhookSource,+ ),+ ],++ 'Component' => [+ fn($webhookSource) => new CheckinComponentNotification(+ Component::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ $webhookSource,+ ),+ ],++ 'License seat' => [+ fn($webhookSource) => new CheckinLicenseSeatNotification(+ LicenseSeat::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ $webhookSource,+ ),+ ],+ ];+ }+}diff --git a/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckoutTest.php b/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckoutTest.phpnew file mode 100644index 0000000000..e2395bd96e--- /dev/null+++ b/tests/Feature/Notifications/Webhooks/IntegrationNotificationsUponCheckoutTest.php@@ -0,0 +1,347 @@+<?php++namespace Tests\Feature\Notifications\Webhooks;++use App\Events\CheckoutableCheckedOut;+use App\Models\Accessory;+use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\Category;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\LicenseSeat;+use App\Models\Location;+use App\Models\User;+use App\Notifications\CheckoutAccessoryNotification;+use App\Notifications\CheckoutAssetNotification;+use App\Notifications\CheckoutComponentNotification;+use App\Notifications\CheckoutConsumableNotification;+use App\Notifications\CheckoutLicenseSeatNotification;+use Illuminate\Database\Eloquent\Model;+use Illuminate\Notifications\AnonymousNotifiable;+use Illuminate\Support\Facades\Mail;+use Illuminate\Support\Facades\Notification;+use PHPUnit\Framework\Attributes\DataProvider;+use PHPUnit\Framework\Attributes\Group;+use Tests\TestCase;+use Illuminate\Notifications\Messages\SlackMessage;+use NotificationChannels\GoogleChat\GoogleChatMessage;+use App\Models\Setting;+++#[Group('notifications')]+class IntegrationNotificationsUponCheckoutTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();++ Notification::fake();+ Mail::fake();+ }++ public static function assetCheckoutTargets(): array+ {+ return [+ 'Asset checked out to user' => [fn () => User::factory()->create(['email' => null])],+ 'Asset checked out to asset' => [fn () => Asset::factory()->laptopMbp()->create()],+ 'Asset checked out to location' => [fn () => Location::factory()->create()],+ ];+ }++ public static function licenseCheckoutTargets(): array+ {+ return [+ 'License checked out to user' => [fn () => User::factory()->create(['email' => null])],+ 'License checked out to asset' => [fn () => Asset::factory()->laptopMbp()->create()],+ ];+ }++ public function test_accessory_checkout_sends_slack_notification_when_setting_enabled()+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckOutEvent(+ Accessory::factory()->create(),+ User::factory()->create(),+ );++ $this->assertSlackNotificationSent(CheckoutAccessoryNotification::class);+ }++ public function test_accessory_checkout_does_not_send_slack_notification_when_setting_disabled()+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckOutEvent(+ Accessory::factory()->create(),+ User::factory()->create(),+ );++ $this->assertNoSlackNotificationSent(CheckoutAccessoryNotification::class);+ }++ #[DataProvider('assetCheckoutTargets')]+ public function test_asset_checkout_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckOutEvent(+ Asset::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckoutAssetNotification::class);+ }++ #[DataProvider('assetCheckoutTargets')]+ public function test_asset_checkout_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckOutEvent(+ Asset::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckoutAssetNotification::class);+ }++ #[DataProvider('assetCheckoutTargets')]+ public function test_component_checkout_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();+ $component = Component::factory()->create([+ 'category_id' => Category::factory()->create([+ 'require_acceptance' => false,+ 'eula_text' => null,+ ]),+ ]);+ $this->fireCheckOutEvent(+ $component,+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckoutComponentNotification::class);+ }++ #[DataProvider('assetCheckoutTargets')]+ public function test_component_checkout_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();+ $component = Component::factory()->create([+ 'category_id' => Category::factory()->create([+ 'require_acceptance' => false,+ 'eula_text' => null,+ ]),+ ]);+ $this->fireCheckOutEvent(+ $component,+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckoutComponentNotification::class);+ }++ public function test_slack_notification_is_still_sent_when_category_email_is_not_set_to_send_emails()+ {+ $this->settings->enableSlackWebhook();++ $category = Category::factory()->create([+ 'checkin_email' => false,+ 'eula_text' => null,+ 'require_acceptance' => false,+ 'use_default_eula' => false,+ ]);+ $assetModel = AssetModel::factory()->for($category)->create();+ $asset = Asset::factory()->for($assetModel, 'model')->create();++ $this->fireCheckOutEvent(+ $asset,+ User::factory()->create(),+ );++ $this->assertSlackNotificationSent(CheckoutAssetNotification::class);+ }++ public function test_asset_checkout_slack_notification_uses_updated_asset_location()+ {+ $this->settings->enableSlackWebhook();++ $previousLocation = Location::factory()->create(['name' => 'Office A']);+ $newLocation = Location::factory()->create(['name' => 'Region B']);+ $target = User::factory()->create(['location_id' => $newLocation->id, 'email' => null]);+ $asset = Asset::factory()->create(['location_id' => $previousLocation->id]);++ // Simulate post-checkout state while keeping a stale in-memory relation loaded.+ $asset->location_id = $newLocation->id;+ $asset->save();++ $this->fireCheckOutEvent($asset, $target);++ Notification::assertSentTo(+ new AnonymousNotifiable,+ CheckoutAssetNotification::class,+ fn (CheckoutAssetNotification $notification): bool => $notification->item->location?->is($newLocation)+ );+ }++ public function test_consumable_checkout_sends_slack_notification_when_setting_enabled()+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckOutEvent(+ Consumable::factory()->create(),+ User::factory()->create(),+ );++ $this->assertSlackNotificationSent(CheckoutConsumableNotification::class);+ }++ public function test_consumable_checkout_does_not_send_slack_notification_when_setting_disabled()+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckOutEvent(+ Consumable::factory()->create(),+ User::factory()->create(),+ );++ $this->assertNoSlackNotificationSent(CheckoutConsumableNotification::class);+ }++ #[DataProvider('licenseCheckoutTargets')]+ public function test_license_checkout_sends_slack_notification_when_setting_enabled($checkoutTarget)+ {+ $this->settings->enableSlackWebhook();++ $this->fireCheckOutEvent(+ LicenseSeat::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertSlackNotificationSent(CheckoutLicenseSeatNotification::class);+ }++ #[DataProvider('licenseCheckoutTargets')]+ public function test_license_checkout_does_not_send_slack_notification_when_setting_disabled($checkoutTarget)+ {+ $this->settings->disableSlackWebhook();++ $this->fireCheckOutEvent(+ LicenseSeat::factory()->create(),+ $checkoutTarget(),+ );++ $this->assertNoSlackNotificationSent(CheckoutLicenseSeatNotification::class);+ }++ private function fireCheckOutEvent(Model $checkoutable, Model $target)+ {+ event(new CheckoutableCheckedOut(+ $checkoutable,+ $target,+ User::factory()->superuser()->create(),+ '',+ ));+ }++ #[DataProvider('checkoutNotificationCases')]+ public function test_checkout_slack_notifications_can_be_built($createNotification)+ {+ $this->settings->enableSlackWebhook();++ $notification = $createNotification(Setting::getSettings());++ $this->assertInstanceOf(+ SlackMessage::class,+ $notification->toSlack()+ );+ }++ #[DataProvider('checkoutNotificationCases')]+ public function test_checkout_google_chat_notifications_can_be_built($createNotification)+ {+ $this->settings->enableGoogleChatWebhook();+ $notification = $createNotification(Setting::getSettings());++ $this->assertInstanceOf(+ GoogleChatMessage::class,+ $notification->toGoogleChat()+ );+ }++ #[DataProvider('checkoutNotificationCases')]+ public function test_checkout_microsoft_teams_workflow_notifications_can_be_built($createNotification)+ {+ $this->settings->enableMicrosoftTeamsWebhook();+ $notification = $createNotification(Setting::getSettings());++ $message = $notification->toMicrosoftTeams();++ $this->assertIsArray($message);+ $this->assertCount(2, $message);+ $this->assertIsString($message[0]);+ $this->assertIsArray($message[1]);+ }++ public static function checkoutNotificationCases(): array+ {+ return [+ 'Accessory' => [+ fn($webhookSource) => new CheckoutAccessoryNotification(+ Accessory::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ 'Test note',+ $webhookSource,+ ),+ ],++ 'Asset' => [+ fn($webhookSource) => new CheckoutAssetNotification(+ Asset::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ 'Test note',+ $webhookSource,+ ),+ ],++ 'Component' => [+ fn($webhookSource) => new CheckoutComponentNotification(+ Component::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ 'Test note',+ $webhookSource,+ ),+ ],++ 'Consumable' => [+ fn($webhookSource) => new CheckoutConsumableNotification(+ Consumable::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ 'Test note',+ $webhookSource,+ ),+ ],++ 'License seat' => [+ fn($webhookSource) => new CheckoutLicenseSeatNotification(+ LicenseSeat::factory()->create(),+ User::factory()->create(),+ User::factory()->superuser()->create(),+ null,+ 'Test note',+ $webhookSource,+ ),+ ],+ ];+ }+}