Skip to content

Commit

Permalink
Merge branch 'develop' into refacto_ms_teams_notifs
Browse files Browse the repository at this point in the history
# Conflicts:
#	app/Listeners/CheckoutableListener.php
  • Loading branch information
Godmartinz committed Oct 30, 2024
2 parents 9a0eee8 + f68df1f commit d6ba303
Show file tree
Hide file tree
Showing 533 changed files with 3,767 additions and 2,096 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/tests-mysql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,7 @@ jobs:
DB_PORT: ${{ job.services.mysql.ports[3306] }}
DB_USERNAME: root
run: php artisan test

- name: Test failure
if: ${{ failure() }}
run: docker exec "$PROJECT_NAME-php-fpm" cat storage/logs/laravel.log
4 changes: 4 additions & 0 deletions .github/workflows/tests-postgres.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,7 @@ jobs:
DB_USERNAME: snipeit
DB_PASSWORD: password
run: php artisan test

- name: Test failure
if: ${{ failure() }}
run: docker exec "$PROJECT_NAME-php-fpm" cat storage/logs/laravel.log
4 changes: 4 additions & 0 deletions .github/workflows/tests-sqlite.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,7 @@ jobs:
env:
DB_CONNECTION: sqlite_testing
run: php artisan test

- name: Test failure
if: ${{ failure() }}
run: docker exec "$PROJECT_NAME-php-fpm" cat storage/logs/laravel.log
1 change: 1 addition & 0 deletions app/Http/Controllers/Account/AcceptanceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -338,4 +338,5 @@ public function store(Request $request, $id) : RedirectResponse
return redirect()->to('account/accept')->with('success', $return_msg);

}

}
17 changes: 2 additions & 15 deletions app/Http/Controllers/Api/ReportsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,6 @@ public function index(Request $request) : JsonResponse | array
});
}

if ($request->filled('action_type')) {
$actionlogs = $actionlogs->where('action_type', '=', $request->input('action_type'))->orderBy('created_at', 'desc');
}

if ($request->filled('created_by')) {
$actionlogs = $actionlogs->where('created_by', '=', $request->input('created_by'));
}

if ($request->filled('action_source')) {
$actionlogs = $actionlogs->where('action_source', '=', $request->input('action_source'))->orderBy('created_at', 'desc');
}

if ($request->filled('remote_ip')) {
$actionlogs = $actionlogs->where('remote_ip', '=', $request->input('remote_ip'))->orderBy('created_at', 'desc');
}

if ($request->filled('uploads')) {
$actionlogs = $actionlogs->whereNotNull('filename')->orderBy('created_at', 'desc');
Expand All @@ -74,6 +59,8 @@ public function index(Request $request) : JsonResponse | array
'note',
'remote_ip',
'user_agent',
'target_type',
'item_type',
'action_source',
'action_date',
];
Expand Down
33 changes: 25 additions & 8 deletions app/Http/Controllers/Assets/AssetsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,10 @@ public function store(ImageUploadRequest $request) : RedirectResponse

$settings = Setting::getSettings();

$success = false;
$successes = [];
$failures = [];
$serials = $request->input('serials');
$asset = null;

for ($a = 1; $a <= count($asset_tags); $a++) {
$asset = new Asset();
Expand Down Expand Up @@ -199,20 +201,35 @@ public function store(ImageUploadRequest $request) : RedirectResponse
$asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), $request->input('expected_checkin', null), 'Checked out on asset creation', $request->get('name'), $location);
}

$success = true;

$successes[] = "<a href='" . route('hardware.show', ['hardware' => $asset->id]) . "' style='color: white;'>" . e($asset->asset_tag) . "</a>";

} else {
$failures[] = join(",", $asset->getErrors()->all());
}
}

session()->put(['redirect_option' => $request->get('redirect_option'), 'checkout_to_type' => $request->get('checkout_to_type')]);


if ($success) {
if ($successes) {
if ($failures) {
//some succeeded, some failed
return redirect()->to(Helper::getRedirectOption($request, $asset->id, 'Assets')) //FIXME - not tested
->with('success-unescaped', trans_choice('admin/hardware/message.create.multi_success_linked', $successes, ['links' => join(", ", $successes)]))
->with('warning', trans_choice('admin/hardware/message.create.partial_failure', $failures, ['failures' => join("; ", $failures)]));
} else {
if (count($successes) == 1) {
//the most common case, keeping it so we don't have to make every use of that translation string be trans_choice'ed
//and re-translated
return redirect()->to(Helper::getRedirectOption($request, $asset->id, 'Assets'))
->with('success-unescaped', trans('admin/hardware/message.create.success_linked', ['link' => route('hardware.show', ['hardware' => $asset->id]), 'id', 'tag' => e($asset->asset_tag)]));
} else {
//multi-success
return redirect()->to(Helper::getRedirectOption($request, $asset->id, 'Assets'))
->with('success-unescaped', trans_choice('admin/hardware/message.create.multi_success_linked', $successes, ['links' => join(", ", $successes)]));
}
}

return redirect()->to(Helper::getRedirectOption($request, $asset->id, 'Assets'))
->with('success-unescaped', trans('admin/hardware/message.create.success_linked', ['link' => route('hardware.show', ['hardware' => $asset->id]), 'id', 'tag' => e($asset->asset_tag)]));


}

return redirect()->back()->withInput()->withErrors($asset->getErrors());
Expand Down
168 changes: 87 additions & 81 deletions app/Listeners/CheckoutableListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@
namespace App\Listeners;

use App\Events\CheckoutableCheckedOut;
use App\Mail\CheckinAccessoryMail;
use App\Mail\CheckinLicenseMail;
use App\Mail\CheckoutAccessoryMail;
use App\Mail\CheckoutAssetMail;
use App\Mail\CheckinAssetMail;
use App\Mail\CheckoutConsumableMail;
use App\Mail\CheckoutLicenseMail;
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\CheckoutAcceptance;
use App\Models\Component;
use App\Models\Consumable;
use App\Models\LicenseSeat;
use App\Models\Recipients\AdminRecipient;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\CheckinAccessoryNotification;
Expand All @@ -20,10 +26,10 @@
use App\Notifications\CheckoutConsumableNotification;
use App\Notifications\CheckoutLicenseSeatNotification;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Exception;
use Illuminate\Support\Facades\Log;
use Osama\LaravelTeamsNotification\TeamsNotification;

class CheckoutableListener
{
Expand All @@ -44,41 +50,42 @@ public function onCheckedOut($event)
/**
* Make a checkout acceptance and attach it in the notification
*/
$settings = Setting::getSettings();
$acceptance = $this->getCheckoutAcceptance($event);
$notifiables = $this->getNotifiables($event);
$adminCcEmailsArray = [];

if($settings->admin_cc_email !== '') {
$adminCcEmail = $settings->admin_cc_email;
$adminCcEmailsArray = array_map('trim', explode(',', $adminCcEmail));
}
$ccEmails = array_filter($adminCcEmailsArray);
$notifiable = $event->checkedOutTo;
$mailable = $this->getCheckoutMailType($event, $acceptance);
// Send email notifications
try {
// foreach ($notifiables as $notifiable) {
// if ($notifiable instanceof User && $notifiable->email != '') {
// if (! $event->checkedOutTo->locale){
// Notification::locale(Setting::getSettings()->locale)->send($notifiable, $this->getCheckoutNotification($event, $acceptance));
// }
// else {
// Notification::send($notifiable, $this->getCheckoutNotification($event, $acceptance));
// }
// }
// }

// Send Webhook notification
if ($this->shouldSendWebhookNotification()) {
// Slack doesn't include the URL in its messaging format, so this is needed to hit the endpoint
if (Setting::getSettings()->webhook_selected === 'slack' || Setting::getSettings()->webhook_selected === 'general') {
Notification::route('slack', Setting::getSettings()->webhook_endpoint)
->notify($this->getCheckoutNotification($event, $acceptance));
if (!$event->checkedOutTo->locale){
$mailable->locale($event->checkedOutTo->locale);
}
// Handling Microsoft Teams notification
else if (Setting::getSettings()->webhook_selected === 'microsoft') {

$message = $this->getCheckoutNotification($event)->toMicrosoftTeams();
$notification = new TeamsNotification(Setting::getSettings()->webhook_endpoint);
$notification->success()->sendMessage($message[0], $message[1]); // Send the message to Microsoft Teams
}
else {
/**
* Send an email if any of the following conditions are met:
* 1. The asset requires acceptance
* 2. The item has a EULA
* 3. The item should send an email at check-in/check-out
*/
if ($notifiable instanceof User && $notifiable->email != '') {
if ($event->checkoutable->requireAcceptance() || $event->checkoutable->getEula() ||
(method_exists($event->checkoutable, 'checkin_email') && $event->checkoutable->checkin_email())) {
Mail::to($notifiable)->cc($ccEmails)->send($mailable);
Log::info('Sending email, Locale: ' . ($event->checkedOutTo->locale ?? 'default'));
}
}

// Send Webhook notification
if ($this->shouldSendWebhookNotification()) {
Notification::route(Setting::getSettings()->webhook_selected, Setting::getSettings()->webhook_endpoint)
->notify($this->getCheckoutNotification($event, $acceptance));
}
}
} catch (ClientException $e) {
Log::debug("Exception caught during checkout notification: " . $e->getMessage());
} catch (Exception $e) {
Expand Down Expand Up @@ -112,39 +119,41 @@ public function onCheckedIn($event)
}
}
}
$settings = Setting::getSettings();
$adminCcEmailsArray = [];

if($settings->admin_cc_email !== '') {
$adminCcEmail = $settings->admin_cc_email;
$adminCcEmailsArray = array_map('trim', explode(',', $adminCcEmail));
}
$ccEmails = array_filter($adminCcEmailsArray);
$notifiable = $event->checkedOutTo;
$mailable = $this->getCheckinMailType($event);

$notifiables = $this->getNotifiables($event);
// Send email notifications
try {
// foreach ($notifiables as $notifiable) {
// if ($notifiable instanceof User && $notifiable->email != '') {
// if (! $event->checkedOutTo->locale){
// Notification::locale(Setting::getSettings()->locale)->send($notifiable, $this->getCheckoutNotification($event, $acceptance));
// }
// else {
// Notification::send($notifiable, $this->getCheckinNotification($event));
// }
// }
// }
if (!$event->checkedOutTo->locale){
$mailable->locale($event->checkedOutTo->locale);
}
/**
* Send an email if any of the following conditions are met:
* 1. The asset requires acceptance
* 2. The item has a EULA
* 3. The item should send an email at check-in/check-out
*/

if ($notifiable instanceof User && $notifiable->email != '') {
if ($event->checkoutable->requireAcceptance() || $event->checkoutable->getEula() ||
(method_exists($event->checkoutable, 'checkin_email') && $event->checkoutable->checkin_email())) {
Mail::to($notifiable)->cc($ccEmails)->send($mailable);
Log::info('Sending email, Locale: ' . $event->checkedOutTo->locale);
}
}
// Send Webhook notification
if ($this->shouldSendWebhookNotification()) {
// Slack doesn't include the URL in its messaging format, so this is needed to hit the endpoint
if (Setting::getSettings()->webhook_selected === 'slack' || Setting::getSettings()->webhook_selected === 'general') {
Notification::route('slack', Setting::getSettings()->webhook_endpoint)
->notify($this->getCheckinNotification($event));
} // Handling Microsoft Teams notification
else if (Setting::getSettings()->webhook_selected === 'microsoft') {

$message = $this->getCheckinNotification($event)->toMicrosoftTeams();
$notification = new TeamsNotification(Setting::getSettings()->webhook_endpoint);
$notification->success()->sendMessage($message[0], $message[1]); // Send the message to Microsoft Teams
}
else {
Notification::route(Setting::getSettings()->webhook_selected, Setting::getSettings()->webhook_endpoint)
->notify($this->getCheckinNotification($event));
}
}

} catch (ClientException $e) {
Log::warning("Exception caught during checkout notification: " . $e->getMessage());
} catch (Exception $e) {
Expand Down Expand Up @@ -175,33 +184,6 @@ private function getCheckoutAcceptance($event)
return $acceptance;
}

/**
* Gets the entities to be notified of the passed event
*
* @param Event $event
* @return Collection
*/
private function getNotifiables($event)
{
$notifiables = collect();

/**
* Notify who checked out the item as long as the model can route notifications
*/
if (method_exists($event->checkedOutTo, 'routeNotificationFor')) {
$notifiables->push($event->checkedOutTo);
}

/**
* Notify Admin users if the settings is activated
*/
if ((Setting::getSettings()) && (Setting::getSettings()->admin_cc_email != '')) {
$notifiables->push(new AdminRecipient());
}

return $notifiables;
}

/**
* Get the appropriate notification for the event
*
Expand Down Expand Up @@ -250,7 +232,7 @@ private function getCheckoutNotification($event, $acceptance = null)
break;
case Consumable::class:
$notificationClass = CheckoutConsumableNotification::class;
break;
break;
case LicenseSeat::class:
$notificationClass = CheckoutLicenseSeatNotification::class;
break;
Expand All @@ -259,6 +241,30 @@ private function getCheckoutNotification($event, $acceptance = null)

return new $notificationClass($event->checkoutable, $event->checkedOutTo, $event->checkedOutBy, $acceptance, $event->note);
}
private function getCheckoutMailType($event, $acceptance){
$lookup = [
Accessory::class => CheckoutAccessoryMail::class,
Asset::class => CheckoutAssetMail::class,
LicenseSeat::class => CheckoutLicenseMail::class,
Consumable::class => CheckoutConsumableMail::class,
];
$mailable= $lookup[get_class($event->checkoutable)];

return new $mailable($event->checkoutable, $event->checkedOutTo, $event->checkedOutBy, $event->note, $acceptance);

}
private function getCheckinMailType($event){
$lookup = [
Accessory::class => CheckinAccessoryMail::class,
Asset::class => CheckinAssetMail::class,
LicenseSeat::class => CheckinLicenseMail::class,
];

$mailable= $lookup[get_class($event->checkoutable)];

return new $mailable($event->checkoutable, $event->checkedOutTo, $event->checkedInBy, $event->note);

}

/**
* Register the listeners for the subscriber.
Expand Down
Loading

0 comments on commit d6ba303

Please sign in to comment.