Skip to content

A free open source IT asset/license management system

Send all in batch and add API endpoint

snipe2cd7a7a795b1
diff --git a/app/Console/Commands/SendAcceptanceReminder.php b/app/Console/Commands/SendAcceptanceReminder.php
index 801b48193d..0b4f78066a 100644
--- a/app/Console/Commands/SendAcceptanceReminder.php
+++ b/app/Console/Commands/SendAcceptanceReminder.php
@@ -2,52 +2,50 @@
namespace App\Console\Commands;
-use App\Mail\UnacceptedAssetReminderMail;
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\User;
+use App\Notifications\UnacceptedAssetReminderNotification;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Exception\TransportException;
class SendAcceptanceReminder extends Command
{
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
protected $signature = 'snipeit:acceptance-reminder';
- /**
- * The console command description.
- *
- * @var string
- */
protected $description = 'This will resend users with unaccepted items a reminder to accept or decline them.';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
+ public function handle()
{
- parent::__construct();
+ $result = self::dispatchAll();
+
+ $this->info($result['sent'].' users notified.');
+ if ($result['failed'] > 0) {
+ $this->warn($result['failed'].' reminder(s) failed to send due to mail transport errors. See log for details.');
+ }
+
+ if (! empty($result['no_email'])) {
+ $this->info('The following users do not have an email address:');
+ $this->table(['ID', 'Name'], array_map(fn ($u) => [$u['id'], $u['name']], $result['no_email']));
+ }
+
+ return 0;
}
/**
- * Execute the console command.
+ * Nudge every assignee who still has a pending acceptance.
+ * Shared between the artisan command and the API's send-all
+ * path so both land in one implementation. Returns a tally so
+ * the API can surface the sent count in its JSON response.
*
- * @return mixed
+ * @return array{sent: int, failed: int, no_email: array<int, array{id: ?int, name: ?string}>}
*/
- public function handle()
+ public static function dispatchAll(): array
{
$pending = CheckoutAcceptance::query()
->with([
@@ -71,67 +69,45 @@ class SendAcceptanceReminder extends Command
->pending()
->get();
- $count = 0;
+ $byAssignee = $pending
+ ->map(fn ($acceptance) => ['assetItem' => $acceptance->checkoutable, 'acceptance' => $acceptance])
+ ->groupBy(fn ($item) => $item['acceptance']->assignedTo ? $item['acceptance']->assignedTo->id : '');
+
+ $sent = 0;
$failed = 0;
- $unacceptedAssetGroups = $pending
- ->map(function ($acceptance) {
- return ['assetItem' => $acceptance->checkoutable, 'acceptance' => $acceptance];
- })
- ->groupBy(function ($item) {
- return $item['acceptance']->assignedTo ? $item['acceptance']->assignedTo->id : '';
- });
- $no_email_list = [];
-
- foreach ($unacceptedAssetGroups as $unacceptedAssetGroup) {
- // The [0] is weird, but it allows for the item_count to work and grabs the appropriate info for each user.
- // Collapsing and flattening the collection doesn't work above.
- $acceptance = $unacceptedAssetGroup[0]['acceptance'];
-
- $locale = $acceptance->assignedTo?->locale;
- $email = $acceptance->assignedTo?->email;
-
- if (! $email) {
- $no_email_list[] = [
- 'id' => $acceptance->assignedTo?->id,
- 'name' => $acceptance->assignedTo?->display_name,
+ $noEmail = [];
+
+ foreach ($byAssignee as $group) {
+ // The [0] grab here is intentional. groupBy keeps the
+ // group as a Collection, and we need both one
+ // representative acceptance (header for the mail) and the
+ // group's size (count for the mail). flattening either
+ // way drops one of the two.
+ $acceptance = $group[0]['acceptance'];
+ $user = $acceptance->assignedTo;
+
+ if (! $user?->email) {
+ $noEmail[] = [
+ 'id' => $user?->id,
+ 'name' => $user?->display_name,
];
continue;
}
- $item_count = $unacceptedAssetGroup->count();
-
try {
- if ($locale) {
- Mail::to($email)->send((new UnacceptedAssetReminderMail($acceptance, $item_count))->locale($locale));
- } else {
- Mail::to($email)->send((new UnacceptedAssetReminderMail($acceptance, $item_count)));
- }
- $count++;
+ $user->notify(new UnacceptedAssetReminderNotification($acceptance, $group->count()));
+ $sent++;
} catch (TransportException $e) {
$failed++;
- $message = 'Failed to send acceptance reminder to '.$email.': '.$e->getMessage();
- Log::warning($message);
- $this->error($message);
+ Log::warning('Failed to send acceptance reminder to '.$user->email.': '.$e->getMessage());
}
}
- $this->info($count.' users notified.');
- if ($failed > 0) {
- $this->warn($failed.' reminder(s) failed to send due to mail transport errors. See log for details.');
- }
- $headers = ['ID', 'Name'];
- $rows = [];
-
- foreach ($no_email_list as $user) {
- $rows[] = [$user['id'], $user['name']];
- }
-
- if (! empty($rows)) {
- $this->info('The following users do not have an email address:');
- $this->table($headers, $rows);
- }
-
- return 0;
+ return [
+ 'sent' => $sent,
+ 'failed' => $failed,
+ 'no_email' => $noEmail,
+ ];
}
}
diff --git a/app/Http/Controllers/Api/UnacceptedAcceptancesController.php b/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
index f8f373c39b..f88784540e 100644
--- a/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
+++ b/app/Http/Controllers/Api/UnacceptedAcceptancesController.php
@@ -2,7 +2,7 @@
namespace App\Http\Controllers\Api;
-use App\Actions\Acceptances\DispatchUnacceptedAssetRemindersAction;
+use App\Console\Commands\SendAcceptanceReminder;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Transformers\AcceptancesTransformer;
@@ -13,10 +13,10 @@ use App\Models\Component;
use App\Models\Consumable;
use App\Models\License;
use App\Models\LicenseSeat;
+use App\Notifications\UnacceptedAssetReminderNotification;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Gate;
/**
@@ -41,7 +41,7 @@ class UnacceptedAcceptancesController extends Controller
// entirely, preventing even a type-shape leak.
$viewableTypes = array_filter(
[Asset::class, LicenseSeat::class, Accessory::class, Component::class, Consumable::class],
- fn(string $type) => Gate::allows('view', $type === LicenseSeat::class ? License::class : $type),
+ fn (string $type) => Gate::allows('view', $type === LicenseSeat::class ? License::class : $type),
);
if ($viewableTypes === []) {
@@ -59,7 +59,7 @@ class UnacceptedAcceptancesController extends Controller
Consumable::class => ['category', 'company'],
]);
},
- 'assignedTo' => fn($q) => $q->withTrashed(),
+ 'assignedTo' => fn ($q) => $q->withTrashed(),
])
->whereHasMorph('checkoutable', $viewableTypes)
->orderByDesc('checkout_acceptances.created_at');
@@ -73,7 +73,7 @@ class UnacceptedAcceptancesController extends Controller
}
$acceptances = $query->get()
- ->filter(fn(CheckoutAcceptance $acceptance) => $acceptance->checkoutable !== null)
+ ->filter(fn (CheckoutAcceptance $acceptance) => $acceptance->checkoutable !== null)
->values();
// Pagination lives in PHP because bs-table-client-side wants
@@ -99,24 +99,73 @@ class UnacceptedAcceptancesController extends Controller
$ids = array_values(array_unique(array_filter(array_map('intval', (array) $request->input('ids', [])))));
if ($ids === []) {
- Artisan::call('snipeit:acceptance-reminder');
+ $result = SendAcceptanceReminder::dispatchAll();
return response()->json(
Helper::formatStandardApiResponse(
'success',
- ['mode' => 'all'],
- trans('admin/reports/general.reminder_sent'),
+ [
+ 'mode' => 'all',
+ 'sent' => $result['sent'],
+ 'skipped' => [
+ 'failed' => $result['failed'],
+ 'no_email' => count($result['no_email']),
+ ],
+ ],
+ trans_choice('admin/reports/general.reminder_sent_count', $result['sent'], ['count' => $result['sent']]),
),
);
}
- $result = DispatchUnacceptedAssetRemindersAction::run($ids);
+ $acceptancesByAssignee = CheckoutAcceptance::pending()
+ ->whereIn('id', $ids)
+ ->with(['assignedTo' => fn ($q) => $q->withTrashed()])
+ ->get()
+ ->filter(fn (CheckoutAcceptance $a) => $a->assignedTo && $a->isAccessibleToCurrentUser())
+ ->groupBy(fn (CheckoutAcceptance $a) => $a->assignedTo->id);
+
+ $sent = 0;
+ $skipped = [
+ 'no_email' => 0,
+ 'none_pending' => 0,
+ ];
+ // Any id in the request that didn't survive the pending +
+ // FMCS filter above falls out as not_found. Tracked here so
+ // the response can tell the caller how many of their ids
+ // never reached the dispatch loop.
+ $notFound = count($ids) - $acceptancesByAssignee->sum(fn ($g) => $g->count());
+
+ foreach ($acceptancesByAssignee as $group) {
+ /** @var CheckoutAcceptance $first */
+ $first = $group->first();
+ $assignee = $first->assignedTo;
+
+ if (empty($assignee->email) || $assignee->activated == '0') {
+ $skipped['no_email']++;
+
+ continue;
+ }
+
+ $pending = $assignee->getAssignedItemsWithPendingAcceptance();
+ if ($pending->isEmpty()) {
+ $skipped['none_pending']++;
+
+ continue;
+ }
+
+ $assignee->notify(new UnacceptedAssetReminderNotification($first, $pending->count()));
+ $sent++;
+ }
return response()->json(
Helper::formatStandardApiResponse(
'success',
- ['mode' => 'ids'] + $result,
- trans_choice('admin/reports/general.reminder_sent_count', $result['sent'], ['count' => $result['sent']]),
+ [
+ 'mode' => 'ids',
+ 'sent' => $sent,
+ 'skipped' => $skipped + ['not_found_or_fmcs' => max(0, $notFound)],
+ ],
+ trans_choice('admin/reports/general.reminder_sent_count', $sent, ['count' => $sent]),
),
);
}
diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.php
index 69b9eb832d..9f0cdc0389 100644
--- a/app/Http/Controllers/ReportsController.php
+++ b/app/Http/Controllers/ReportsController.php
@@ -4,38 +4,24 @@ namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Http\Requests\CustomAssetReportRequest;
-use App\Mail\CheckoutAccessoryMail;
-use App\Mail\CheckoutAssetMail;
-use App\Mail\CheckoutComponentMail;
-use App\Mail\CheckoutConsumableMail;
-use App\Mail\CheckoutLicenseMail;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
-use App\Models\Checkoutable;
-use App\Models\CheckoutAcceptance;
use App\Models\Company;
-use App\Models\Component;
-use App\Models\Consumable;
use App\Models\CustomField;
use App\Models\Depreciation;
use App\Models\License;
-use App\Models\LicenseSeat;
use App\Models\Maintenance;
use App\Models\ReportTemplate;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;
-use Illuminate\Database\Eloquent\Relations\MorphTo;
-use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
-use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Mail;
use League\Csv\EscapeFormula;
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -62,11 +48,6 @@ class ReportsController extends Controller
$audit_alert_count = Asset::DueOrOverdueForAudit($settings)->count();
$checkin_alert_count = Asset::DueOrOverdueForCheckin($settings)->count();
- // CheckoutAcceptance has no company_id column; scope through the checkoutable
- // relationship so each type's CompanyableTrait global scope is applied.
- $pending_acceptance_count = CheckoutAcceptance::pending()
- ->whereHasMorph('checkoutable', [Asset::class, LicenseSeat::class, Accessory::class, Component::class, Consumable::class])
- ->count();
$licenses_low_count = License::withCount(['freeSeats as free_seats_count'])
->get()
->filter(fn ($l) => $l->free_seats_count <= 0)
@@ -75,7 +56,6 @@ class ReportsController extends Controller
return view('reports/index', compact(
'audit_alert_count',
'checkin_alert_count',
- 'pending_acceptance_count',
'licenses_low_count',
));
}
@@ -1393,332 +1373,6 @@ class ReportsController extends Controller
return $response;
}
- /**
- * getAssetAcceptanceReport
- *
- * @author Vincent Sposato <[email protected]>
- *
- * @version v1.0
- */
- public function getAssetAcceptanceReport($deleted = false): View
- {
- // Reports.view still opens the full report with reminder /
- // delete actions. Non-report checkoutable viewers reach this
- // page from the dashboard's Needs Attention widget, where an
- // "Unaccepted acceptances" row is shown to anyone who can
- // view at least one checkoutable type. Without widening
- // here, that link 403s for scoped viewers. The list is
- // filtered per-viewer below (viewable types + FMCS), and
- // the reminder / delete action buttons stay gated behind
- // reports.view in the blade so this widening is read-only.
- $hasReportsView = Gate::allows('reports.view');
- $viewableAcceptanceTypes = array_filter(
- [Asset::class, LicenseSeat::class, Accessory::class, Component::class, Consumable::class],
- fn (string $type) => Gate::allows('view', $type === LicenseSeat::class ? License::class : $type),
- );
- abort_unless($hasReportsView || $viewableAcceptanceTypes !== [], 403);
-
- $this->disableDebugbar();
-
- $showDeleted = $deleted == 'deleted';
-
- $query = CheckoutAcceptance::Pending()
- ->with([
- 'checkoutable' => function (MorphTo $query) {
- $query->withTrashed()->morphWith([
- Asset::class => ['model.category', 'assignedTo', 'company'],
- Accessory::class => ['category', 'checkouts', 'company'],
- LicenseSeat::class => ['user', 'license'],
- Component::class => ['assignedTo', 'company'],
- Consumable::class => ['company'],
- ]);
- },
- 'assignedTo' => function ($query) {
- $query->withTrashed();
- },
- ])->orderByDesc('checkout_acceptances.created_at');
-
- if ($showDeleted) {
- $query->withTrashed();
- }
-
- $itemsForReport = $query->get()
- ->filter(fn ($unaccepted) => $unaccepted->checkoutable)
- // Type filter for scoped-viewer access. Only show
- // acceptances whose checkoutable type this viewer can
- // read. Skipped for reports.view holders since they see
- // every type on the report by definition (matches
- // pre-widen behavior). Scoped viewers get their own
- // types, matching pendingAcceptancesCount in
- // App\Livewire\NeedsAttention::mount().
- ->filter(fn ($unaccepted) => $hasReportsView
- || in_array($unaccepted->checkoutable::class, $viewableAcceptanceTypes, true))
- // FMCS scope, mirrors sentAssetAcceptanceReminder + deleteAssetAcceptance.
- // CheckoutAcceptance has no company_id column and does not use
- // CompanyableTrait / CompanyableChildTrait, so it is not covered
- // by the CompanyableScope global scope. Without this per-row
- // check, a reports.view user scoped to Company A sees pending
- // acceptances for items owned by Company B in both the page
- // render and the CSV export. Same helper the two mutating
- // actions already use.
- ->filter(fn ($unaccepted) => $this->currentUserCanAccessAcceptance($unaccepted))
- ->map(fn ($unaccepted) => Checkoutable::fromAcceptance($unaccepted));
-
- $canManageAcceptances = $hasReportsView;
-
- return view('reports/unaccepted_assets', compact('itemsForReport', 'showDeleted', 'canManageAcceptances'));
- }
-
- /**
- * sentAssetAcceptanceReminder
- *
- *
- * @version v1.0
- */
- public function sentAssetAcceptanceReminder(Request $request): RedirectResponse
- {
- $this->authorize('reports.view');
- $id = $request->input('acceptance_id');
- $query = CheckoutAcceptance::query()
- ->with([
- 'checkoutable' => function (MorphTo $query) {
- $query->withTrashed()->morphWith([
- Asset::class => ['model.category', 'assignedTo', 'company', 'checkouts'],
- Accessory::class => ['category', 'company', 'checkouts'],
- LicenseSeat::class => ['user', 'license', 'checkouts'],
- Component::class => ['assignedTo', 'company', 'checkouts'],
- Consumable::class => ['company', 'checkouts'],
- ]);
- },
- 'assignedTo' => fn ($q) => $q->withTrashed(),
- ])
- ->pending();
- $acceptance = $query->find($id);
- if (! $acceptance) {
- Log::debug('No pending acceptances');
-
- // Redirect to the unaccepted items report page with error
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.bad_data'));
- }
-
- if (! $this->currentUserCanAccessAcceptance($acceptance)) {
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.insufficient_permissions'));
- }
-
- $item = $acceptance->checkoutable;
- $assignee = $acceptance->assignedTo ?? $item->assignedTo ?? null;
- $email = $assignee?->email;
- $locale = $assignee?->locale;
-
- Log::debug(print_r($acceptance, true));
-
- if (is_null($acceptance->created_at)) {
- Log::debug('No acceptance created_at');
-
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.bad_data'));
- } else {
- if ($item instanceof LicenseSeat) {
- $logItem_res = $item->license->checkouts()->with('adminuser')->where('created_at', '=', $acceptance->created_at)->get();
- } else {
- $logItem_res = $item->checkouts()->with('adminuser')->where('created_at', '=', $acceptance->created_at)->get();
- }
- if ($logItem_res->isEmpty()) {
- Log::debug('Acceptance date mismatch');
-
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.bad_data'));
- }
- $logItem = $logItem_res[0];
- }
-
- if (is_null($email) || $email === '') {
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.no_email'));
- }
- $mailable = $this->getCheckoutMailType($acceptance, $logItem);
- Mail::to($email)->send($mailable->locale($locale));
-
- return redirect()->route('reports/unaccepted_assets')->with('success', trans('admin/reports/general.reminder_sent'));
- }
-
- private function currentUserCanAccessAcceptance(CheckoutAcceptance $acceptance): bool
- {
- if (! Company::isFullMultipleCompanySupportEnabled()) {
- return true;
- }
-
- if (auth()->user()->isSuperUser()) {
- return true;
- }
-
- // Bypass Eloquent global scopes so cross-company items are still resolved for the check.
- $checkoutableType = $acceptance->checkoutable_type;
- $checkoutable = $checkoutableType::withoutGlobalScopes()->find($acceptance->checkoutable_id);
-
- // LicenseSeat has no company_id of its own; the parent License carries the company.
- if ($checkoutable instanceof LicenseSeat) {
- $checkoutable = License::withoutGlobalScopes()->find($checkoutable->license_id);
- }
-
- return Company::isCurrentUserHasAccess($checkoutable);
- }
-
- private function getCheckoutMailType(CheckoutAcceptance $acceptance, $logItem): Mailable
- {
- $lookup = [
- Accessory::class => CheckoutAccessoryMail::class,
- Asset::class => CheckoutAssetMail::class,
- LicenseSeat::class => CheckoutLicenseMail::class,
- Consumable::class => CheckoutConsumableMail::class,
- Component::class => CheckoutComponentMail::class,
- ];
- $mailable = $lookup[get_class($acceptance->checkoutable)];
-
- return new $mailable(
- $acceptance->checkoutable,
- $acceptance->checkedOutTo ?? $acceptance->assignedTo,
- $logItem->adminuser,
- $acceptance,
- $acceptance->note,
- firstTimeSending: false,
- );
- }
-
- /**
- * sentAssetAcceptanceReminder
- *
- * @param int|null $acceptanceId
- *
- * @version v1.0
- */
- public function deleteAssetAcceptance($acceptanceId = null): RedirectResponse
- {
- $this->authorize('reports.view');
-
- $acceptance = CheckoutAcceptance::pending()
- ->with(['checkoutable' => function (MorphTo $morphTo) {
- $morphTo->morphWith([LicenseSeat::class => ['license']]);
- }])
- ->find($acceptanceId);
-
- if (! $acceptance) {
- // Redirect to the unaccepted assets report page with error
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.bad_data'));
- }
-
- if (! $this->currentUserCanAccessAcceptance($acceptance)) {
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.insufficient_permissions'));
- }
-
- if ($acceptance->delete()) {
- return redirect()->route('reports/unaccepted_assets')->with('success', trans('admin/reports/general.acceptance_deleted'));
- } else {
- return redirect()->route('reports/unaccepted_assets')->with('error', trans('general.deletion_failed'));
- }
- }
-
- /**
- * Exports the AssetAcceptance report to CSV
- *
- * @author Vincent Sposato <[email protected]>
- *
- * @version v1.0
- */
- public function postAssetAcceptanceReport($deleted = false): Response
- {
- $this->authorize('reports.view');
- $showDeleted = request('deleted') === 'deleted';
-
- /**
- * Get all assets with pending checkout acceptances
- */
- $acceptances = CheckoutAcceptance::pending()
- ->with([
- 'checkoutable' => function (MorphTo $acceptance) {
- $acceptance->withTrashed()->morphWith([
- Asset::class => ['model.category', 'assignedTo', 'company'],
- Accessory::class => ['category', 'checkouts', 'company'],
- LicenseSeat::class => ['user', 'license'],
- Component::class => ['assignedTo', 'company'],
- Consumable::class => ['company'],
- ]);
- },
- 'assignedTo',
- ])->orderByDesc('checkout_acceptances.created_at');
-
- if ($showDeleted) {
- $acceptances->withTrashed();
- }
-
- $itemsForReport = $acceptances->get()
- ->filter(fn ($unaccepted) => $unaccepted->checkoutable)
- // FMCS scope, same rationale as getAssetAcceptanceReport.
- // The CSV export path had the same missing filter as the page
- // render, so a reports.view user scoped to Company A could
- // download pending acceptances for Company B items.
- ->filter(fn ($unaccepted) => $this->currentUserCanAccessAcceptance($unaccepted))
- ->map(fn ($unaccepted) => Checkoutable::fromAcceptance($unaccepted));
-
- $header = [
- trans('general.date'),
- trans('general.type'),
- trans('admin/companies/table.title'),
- trans('general.category'),
- trans('admin/hardware/form.model'),
- trans('general.name'),
- trans('admin/hardware/table.asset_tag'),
- trans('admin/hardware/table.checkoutto'),
- ];
-
- $header = array_map('trim', $header);
-
- // Formula-escape data rows using the same helper + setting as the
- // sibling exports in this file. Row values (company / category /
- // model / item name / asset tag / assignee display name) are all
- // user-editable free-text fields that a low-privilege user could
- // set to a spreadsheet formula. Without escaping, the payload
- // evaluates when a reports.view user opens the downloaded CSV in
- // Excel / LibreOffice / Google Sheets. Same backtick prefix used
- // by every other export in ReportsController.
- $formatter = new EscapeFormula('`');
-
- // Build the CSV via fputcsv so cells containing commas, quotes,
- // or newlines get RFC 4180 quoted rather than concatenated into
- // the row/record stream. The prior implode(',') + implode("\n")
- // approach let a mid-cell newline become a real record break,
- // dropping the second half of the cell onto its own line where
- // EscapeFormula's leading-character check no longer applied.
- $handle = fopen('php://temp', 'r+');
- fputcsv($handle, $header);
-
- foreach ($itemsForReport as $item) {
- $row = [
- $item->acceptance->created_at,
- $item->type,
- $item->plain_text_company,
- $item->plain_text_category,
- $item->plain_text_model,
- $item->plain_text_name,
- $item->asset_tag,
- $item->acceptance->assignedto ? $item->acceptance->assignedto->display_name : trans('admin/reports/general.deleted_user'),
- ];
-
- if (config('app.escape_formulas') !== false) {
- $row = $formatter->escapeRecord($row);
- }
-
- fputcsv($handle, $row);
- }
-
- rewind($handle);
- $csv = stream_get_contents($handle);
- fclose($handle);
-
- $response = response()->make($csv, 200);
- $response->header('Content-Type', 'text/csv');
- $response->header('Content-disposition', 'attachment;filename=report.csv');
-
- return $response;
- }
-
/**
* getCheckedOutAssetsRequiringAcceptance
*
diff --git a/app/Http/Controllers/UnacceptedAcceptancesController.php b/app/Http/Controllers/UnacceptedAcceptancesController.php
index 86f279c547..7a318ede84 100644
--- a/app/Http/Controllers/UnacceptedAcceptancesController.php
+++ b/app/Http/Controllers/UnacceptedAcceptancesController.php
@@ -2,28 +2,15 @@
namespace App\Http\Controllers;
-use App\Mail\CheckoutAccessoryMail;
-use App\Mail\CheckoutAssetMail;
-use App\Mail\CheckoutComponentMail;
-use App\Mail\CheckoutConsumableMail;
-use App\Mail\CheckoutLicenseMail;
-use App\Models\Accessory;
-use App\Models\Asset;
use App\Models\CheckoutAcceptance;
-use App\Models\Company;
-use App\Models\Component;
-use App\Models\Consumable;
-use App\Models\License;
-use App\Models\LicenseSeat;
+use App\Notifications\UnacceptedAssetReminderNotification;
use Illuminate\Contracts\View\View;
-use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
-use Illuminate\Mail\Mailable;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Mail;
-
+/**
+ * Unaccepted-acceptances
+ */
class UnacceptedAcceptancesController extends Controller
{
public function index(): View
@@ -39,25 +26,15 @@ class UnacceptedAcceptancesController extends Controller
{
$this->authorize('canCheckoutAtLeastOneItemType');
- $acceptance = $this->loadPendingAcceptance($request->input('acceptance_id'));
-
- if (! $acceptance) {
- Log::debug('No pending acceptances');
-
- return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.bad_data'));
- }
+ $id = $request->integer('acceptance_id');
+ $sent = $this->dispatchReminders($id > 0 ? [$id] : []);
- if (! $this->currentUserCanAccessAcceptance($acceptance)) {
- return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.insufficient_permissions'));
- }
-
- $result = $this->dispatchReminder($acceptance);
-
- if ($result === 'sent') {
- return redirect()->route('unaccepted-acceptances.index')->with('success', trans('admin/reports/general.reminder_sent'));
- }
-
- return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.'.$result));
+ return redirect()->route('unaccepted-acceptances.index')->with(
+ $sent > 0 ? 'success' : 'error',
+ $sent > 0
+ ? trans('admin/reports/general.reminder_sent')
+ : trans('general.bad_data'),
+ );
}
public function bulkSendReminders(Request $request): RedirectResponse
@@ -65,104 +42,24 @@ class UnacceptedAcceptancesController extends Controller
$this->authorize('canCheckoutAtLeastOneItemType');
$ids = array_values(array_unique(array_filter(array_map('intval', (array) $request->input('ids', [])))));
-
- if ($ids === []) {
- return redirect()->route('unaccepted-acceptances.index')
- ->with('warning', trans('general.bulk_checkin_delete.nothing_selected', ['object_type' => trans('general.unaccepted_asset_report')]));
- }
-
- $sent = 0;
- // Keyed-by-reason-code tally so the flash message can tell the
- // admin WHY rows skipped (missing acceptance / FMCS / no email)
- // rather than a flat count that silently hides whichever class
- // of problem is in effect.
- $skippedByReason = [
- 'not_found' => 0,
- 'fmcs' => 0,
- 'no_email' => 0,
- 'bad_data' => 0,
- ];
-
- foreach ($ids as $id) {
- $acceptance = $this->loadPendingAcceptance($id);
-
- if (! $acceptance) {
- $skippedByReason['not_found']++;
-
- continue;
- }
-
- if (! $this->currentUserCanAccessAcceptance($acceptance)) {
- $skippedByReason['fmcs']++;
-
- continue;
- }
-
- $result = $this->dispatchReminder($acceptance);
- if ($result === 'sent') {
- $sent++;
- } else {
- $skippedByReason[$result] = ($skippedByReason[$result] ?? 0) + 1;
- }
- }
-
- $totalSkipped = array_sum($skippedByReason);
+ $sent = $this->dispatchReminders($ids);
return redirect()->route('unaccepted-acceptances.index')->with(
$sent > 0 ? 'success' : 'warning',
- trans('admin/reports/general.bulk_reminders_sent', [
- 'sent' => $sent,
- 'skipped' => $totalSkipped,
- 'breakdown' => $this->formatSkipBreakdown($skippedByReason),
- ]),
+ trans_choice('admin/reports/general.reminder_sent_count', $sent, ['count' => $sent]),
);
}
- /**
- * Compose the ", (N no email, N FMCS blocked, ...)" suffix for the
- * bulk-send flash. Reasons with zero skips are omitted so the
- * message stays short in the common case. Returns an empty string
- * when nothing skipped.
- *
- * @param array<string, int> $skippedByReason
- */
- private function formatSkipBreakdown(array $skippedByReason): string
- {
- $labels = [
- 'not_found' => trans('admin/reports/general.skip_not_found'),
- 'fmcs' => trans('admin/reports/general.skip_fmcs'),
- 'no_email' => trans('admin/reports/general.skip_no_email'),
- 'bad_data' => trans('admin/reports/general.skip_bad_data'),
- ];
-
- $parts = [];
- foreach ($skippedByReason as $reason => $count) {
- if ($count > 0 && isset($labels[$reason])) {
- $parts[] = $count.' '.$labels[$reason];
- }
- }
-
- return $parts === [] ? '' : ' ('.implode(', ', $parts).')';
- }
-
public function destroy(int $acceptanceId): RedirectResponse
{
$this->authorize('canCheckoutAtLeastOneItemType');
- $acceptance = CheckoutAcceptance::pending()
- ->with(['checkoutable' => function (MorphTo $morphTo) {
- $morphTo->morphWith([LicenseSeat::class => ['license']]);
- }])
- ->find($acceptanceId);
+ $acceptance = CheckoutAcceptance::pending()->find($acceptanceId);
- if (! $acceptance) {
+ if (! $acceptance || ! $acceptance->isAccessibleToCurrentUser()) {
return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.bad_data'));
}
- if (! $this->currentUserCanAccessAcceptance($acceptance)) {
- return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.insufficient_permissions'));
- }
-
if ($acceptance->delete()) {
return redirect()->route('unaccepted-acceptances.index')->with('success', trans('admin/reports/general.acceptance_deleted'));
}
@@ -170,116 +67,46 @@ class UnacceptedAcceptancesController extends Controller
return redirect()->route('unaccepted-acceptances.index')->with('error', trans('general.deletion_failed'));
}
- private function loadPendingAcceptance(mixed $id): ?CheckoutAcceptance
- {
- if (! is_numeric($id)) {
- return null;
- }
-
- return CheckoutAcceptance::query()
- ->with([
- 'checkoutable' => function (MorphTo $query) {
- $query->withTrashed()->morphWith([
- Asset::class => ['model.category', 'assignedTo', 'company', 'checkouts'],
- Accessory::class => ['category', 'company', 'checkouts'],
- LicenseSeat::class => ['user', 'license', 'checkouts'],
- Component::class => ['assignedTo', 'company', 'checkouts'],
- Consumable::class => ['company', 'checkouts'],
- ]);
- },
- 'assignedTo' => fn ($q) => $q->withTrashed(),
- ])
- ->pending()
- ->find((int) $id);
- }
-
/**
- * Send the reminder email for a given pending acceptance. Returns
- * 'sent' on success or a general.* lang-key suffix on failure.
- * Keys match the row-level flow this method replaces: bad_data,
- * no_email.
+ * Resolve the ids to pending acceptances, FMCS-filter, dedupe
+ * by assignee so a user with five selected acceptances gets one
+ * notification (with count=5), then fire
+ * UnacceptedAssetReminderNotification per unique assignee.
+ *
+ * @param array<int> $acceptanceIds
*/
- private function dispatchReminder(CheckoutAcceptance $acceptance): string
+ private function dispatchReminders(array $acceptanceIds): int
{
- $item = $acceptance->checkoutable;
- $assignee = $acceptance->assignedTo ?? $item->assignedTo ?? null;
- $email = $assignee?->email;
- $locale = $assignee?->locale;
-
- if (is_null($acceptance->created_at)) {
- return 'bad_data';
- }
-
- // Pull the action_log row that recorded the checkout so the
- // reminder email can attribute "sent by" to the admin who
- // handed the item out. A 1-second window instead of exact-
- // equality on created_at accommodates sub-second drift between
- // the acceptance row and its action_log sibling (seen on busy
- // installs where the two writes land in different ticks). If
- // no log row matches at all we proceed with a null adminuser
- // rather than fail the whole send.
- $acceptanceCreated = $acceptance->created_at;
- $window = [
- $acceptanceCreated->copy()->subSecond(),
- $acceptanceCreated->copy()->addSecond(),
- ];
- $logItem = $item instanceof LicenseSeat
- ? $item->license?->checkouts()->with('adminuser')->whereBetween('created_at', $window)->orderByDesc('created_at')->first()
- : $item->checkouts()->with('adminuser')->whereBetween('created_at', $window)->orderByDesc('created_at')->first();
-
- if (is_null($email) || $email === '') {
- return 'no_email';
+ if ($acceptanceIds === []) {
+ return 0;
}
- Mail::to($email)->send($this->getCheckoutMailType($acceptance, $logItem)->locale($locale));
+ $acceptancesByAssignee = CheckoutAcceptance::pending()
+ ->whereIn('id', $acceptanceIds)
+ ->with(['assignedTo' => fn ($q) => $q->withTrashed()])
+ ->get()
+ ->filter(fn (CheckoutAcceptance $a) => $a->assignedTo && $a->isAccessibleToCurrentUser())
+ ->groupBy(fn (CheckoutAcceptance $a) => $a->assignedTo->id);
- return 'sent';
- }
-
- private function getCheckoutMailType(CheckoutAcceptance $acceptance, $logItem): Mailable
- {
- $lookup = [
- Accessory::class => CheckoutAccessoryMail::class,
- Asset::class => CheckoutAssetMail::class,
- LicenseSeat::class => CheckoutLicenseMail::class,
- Consumable::class => CheckoutConsumableMail::class,
- Component::class => CheckoutComponentMail::class,
- ];
- $mailable = $lookup[get_class($acceptance->checkoutable)];
-
- return new $mailable(
- $acceptance->checkoutable,
- $acceptance->checkedOutTo ?? $acceptance->assignedTo,
- $logItem?->adminuser,
- $acceptance,
- $acceptance->note,
- firstTimeSending: false,
- );
- }
-
- /**
- * Per-row FMCS scope check. CheckoutAcceptance has no company_id of
- * its own and does not use CompanyableTrait, so it falls outside
- * CompanyableScope. Without this check, a company-A caller could
- * remind or delete a company-B acceptance.
- */
- private function currentUserCanAccessAcceptance(CheckoutAcceptance $acceptance): bool
- {
- if (! Company::isFullMultipleCompanySupportEnabled()) {
- return true;
- }
+ $sent = 0;
+ foreach ($acceptancesByAssignee as $group) {
+ /** @var CheckoutAcceptance $first */
+ $first = $group->first();
+ $assignee = $first->assignedTo;
- if (auth()->user()->isSuperUser()) {
- return true;
- }
+ if (empty($assignee->email) || $assignee->activated == '0') {
+ continue;
+ }
- $checkoutableType = $acceptance->checkoutable_type;
- $checkoutable = $checkoutableType::withoutGlobalScopes()->find($acceptance->checkoutable_id);
+ $pending = $assignee->getAssignedItemsWithPendingAcceptance();
+ if ($pending->isEmpty()) {
+ continue;
+ }
- if ($checkoutable instanceof LicenseSeat) {
- $checkoutable = License::withoutGlobalScopes()->find($checkoutable->license_id);
+ $assignee->notify(new UnacceptedAssetReminderNotification($first, $pending->count()));
+ $sent++;
}
- return Company::isCurrentUserHasAccess($checkoutable);
+ return $sent;
}
}
diff --git a/app/Http/Controllers/Users/UsersController.php b/app/Http/Controllers/Users/UsersController.php
index 9d31ebd553..b534a2a65a 100755
--- a/app/Http/Controllers/Users/UsersController.php
+++ b/app/Http/Controllers/Users/UsersController.php
@@ -9,7 +9,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\DeleteUserRequest;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\SaveUserRequest;
-use App\Mail\UnacceptedAssetReminderMail;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
@@ -22,13 +21,13 @@ use App\Models\License;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\CurrentInventory;
+use App\Notifications\UnacceptedAssetReminderNotification;
use App\Notifications\WelcomeNotification;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use League\Csv\EscapeFormula;
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -816,6 +815,9 @@ class UsersController extends Controller
/**
* Resend pending acceptance reminder email for a specific user.
+ * Routes through UnacceptedAssetReminderNotification so the
+ * console command, this button, and the bulk UI all share the
+ * same channel.
*/
public function resendAcceptanceReminder(User $user): RedirectResponse
{
@@ -845,13 +847,7 @@ class UsersController extends Controller
return redirect()->back()->with('warning', trans('admin/users/message.error.no_pending_acceptances'));
}
- $mailable = new UnacceptedAssetReminderMail($firstAcceptance, $pendingItems->count());
-
- if (! empty($user->locale)) {
- $mailable->locale($user->locale);
- }
-
- Mail::to($user->email)->send($mailable);
+ $user->notify(new UnacceptedAssetReminderNotification($firstAcceptance, $pendingItems->count()));
return redirect()->back()->with('success', trans_choice('admin/users/message.success.acceptance_reminder_sent', $pendingItems->count(), ['count' => $pendingItems->count()]));
}
diff --git a/app/Mail/UnacceptedAssetReminderMail.php b/app/Mail/UnacceptedAssetReminderMail.php
deleted file mode 100644
index 5d29f1652c..0000000000
--- a/app/Mail/UnacceptedAssetReminderMail.php
+++ /dev/null
@@ -1,67 +0,0 @@
-<?php
-
-namespace App\Mail;
-
-use Illuminate\Bus\Queueable;
-use Illuminate\Mail\Mailables\Address;
-use Illuminate\Mail\Mailables\Attachment;
-use Illuminate\Mail\Mailables\Content;
-use Illuminate\Mail\Mailables\Envelope;
-use Illuminate\Queue\SerializesModels;
-
-class UnacceptedAssetReminderMail extends BaseMailable
-{
- use Queueable, SerializesModels;
-
- /**
- * Create a new message instance.
- */
- public function __construct($checkout_info, $count)
- {
-
- $this->count = $count;
- $this->target = $checkout_info?->assignedTo;
- $this->acceptance = $checkout_info;
- }
-
- /**
- * Get the message envelope.
- */
- public function envelope(): Envelope
- {
- $from = new Address(config('mail.from.address'), config('mail.from.name'));
-
- return new Envelope(
- from: $from,
- subject: trans('mail.unaccepted_asset_reminder'),
- );
- }
-
- /**
- * Get the message content definition.
- */
- public function content(): Content
- {
- $accept_url = route('account.accept');
-
- return new Content(
- markdown: 'notifications.markdown.asset-reminder',
- with: [
- 'count' => $this->count,
- 'assigned_to' => $this->target?->present()->fullName,
- 'link' => route('account.accept'),
- 'accept_url' => $accept_url,
- ]
- );
- }
-
- /**
- * Get the attachments for the message.
- *
- * @return array<int, Attachment>
- */
- public function attachments(): array
- {
- return [];
- }
-}
diff --git a/app/Models/CheckoutAcceptance.php b/app/Models/CheckoutAcceptance.php
index 334f1437eb..7343c389a2 100644
--- a/app/Models/CheckoutAcceptance.php
+++ b/app/Models/CheckoutAcceptance.php
@@ -54,6 +54,35 @@ class CheckoutAcceptance extends Model
};
}
+ /**
+ * FMCS tenant check for the acceptance's checkoutable. The row
+ * itself has no company_id and does not use CompanyableTrait /
+ * CompanyableChildTrait, so Company::isCurrentUserHasAccess has
+ * to be routed through the polymorphic parent. LicenseSeat is
+ * company-less too, so hop up to its license. Bypasses global
+ * scopes on the lookup so a scope-filtered foreign row still
+ * resolves for the check (otherwise FMCS admins would see a
+ * silent true for anything their own scope filters out).
+ */
+ public function isAccessibleToCurrentUser(): bool
+ {
+ if (!Company::isFullMultipleCompanySupportEnabled()) {
+ return true;
+ }
+
+ if (auth()->user()?->isSuperUser()) {
+ return true;
+ }
+
+ $checkoutable = $this->checkoutable_type::withoutGlobalScopes()->find($this->checkoutable_id);
+
+ if ($checkoutable instanceof LicenseSeat) {
+ $checkoutable = License::withoutGlobalScopes()->find($checkoutable->license_id);
+ }
+
+ return Company::isCurrentUserHasAccess($checkoutable);
+ }
+
/**
* Accessor for the checkoutable item's category name.
*
diff --git a/app/Notifications/UnacceptedAssetReminderNotification.php b/app/Notifications/UnacceptedAssetReminderNotification.php
new file mode 100644
index 0000000000..854857f8fa
--- /dev/null
+++ b/app/Notifications/UnacceptedAssetReminderNotification.php
@@ -0,0 +1,50 @@
+<?php
+
+namespace App\Notifications;
+
+use App\Models\CheckoutAcceptance;
+use Illuminate\Bus\Queueable;
+use Illuminate\Notifications\Messages\MailMessage;
+use Illuminate\Notifications\Notification;
+
+/**
+ * Nudges a user about pending acceptances still on their plate. One
+ * notification per assignee with the total count, not one per
+ * acceptance. Replaced the standalone UnacceptedAssetReminderMail so
+ * every reminder flow (snipeit:acceptance-reminder console command,
+ * the per-user Resend-reminder button on the user show page, the
+ * /unaccepted-acceptances bulk UI, and the API send-reminders
+ * endpoint) ships through the same Laravel notification channel.
+ */
+class UnacceptedAssetReminderNotification extends Notification
+{
+ use Queueable;
+
+ public function __construct(
+ public CheckoutAcceptance $acceptance,
+ public int $count,
+ ) {}
+
+ /**
+ * @return array<int, string>
+ */
+ public function via($notifiable): array
+ {
+ return ['mail'];
+ }
+
+ public function toMail($notifiable): MailMessage
+ {
+ // Locale is picked up automatically from User::preferredLocale()
+ // (HasLocalePreference contract), so this doesn't need to
+ // branch on $notifiable->locale the way the old Mailable did.
+ return (new MailMessage)
+ ->subject(trans('mail.unaccepted_asset_reminder'))
+ ->markdown('notifications.markdown.asset-reminder', [
+ 'count' => $this->count,
+ 'assigned_to' => $this->acceptance->assignedTo?->present()->fullName,
+ 'link' => route('account.accept'),
+ 'accept_url' => route('account.accept'),
+ ]);
+ }
+}
diff --git a/resources/lang/en-US/mail.php b/resources/lang/en-US/mail.php
index 0aef3f3e29..bff2cd7ff8 100644
--- a/resources/lang/en-US/mail.php
+++ b/resources/lang/en-US/mail.php
@@ -77,7 +77,7 @@ return [
'initiated_declined' => 'A checkout you initiated was declined',
'inventory_report' => 'Inventory Report',
'item' => 'Item',
- 'item_checked_reminder' => 'This is a reminder that you currently have :count items checked out to you that you have not accepted or declined. Please click the link below to confirm your decision.',
+ 'item_checked_reminder' => '{1}This is a reminder that you currently have one item checked out to you that you have not accepted or declined. Please click the link below to confirm your decision.|[2,*]This is a reminder that you currently have :count items checked out to you that you have not accepted or declined. Please click the link below to confirm your decision.',
'license_expiring_alert' => 'There is :count license expiring or terminating in the next :threshold days.|There are :count licenses expiring or terminating in the next :threshold days.',
'link_to_update_password' => 'Please click on the following link to update your :web password:',
'login' => 'Login',
diff --git a/resources/views/notifications/markdown/asset-reminder.blade.php b/resources/views/notifications/markdown/asset-reminder.blade.php
index 691f454a36..11c16ba4e9 100644
--- a/resources/views/notifications/markdown/asset-reminder.blade.php
+++ b/resources/views/notifications/markdown/asset-reminder.blade.php
@@ -1,7 +1,7 @@
@component('mail::message')
# {{ trans('mail.hello') }} {{ $assigned_to}},
-{{trans('mail.item_checked_reminder', ['count' => $count])}}
+{{trans_choice('mail.item_checked_reminder', $count, ['count' => $count])}}
[{{ trans('general.click_here')}}]({{$accept_url}})
{{ trans('mail.best_regards') }}
diff --git a/tests/Feature/Api/UnacceptedAcceptances/SendRemindersApiTest.php b/tests/Feature/Api/UnacceptedAcceptances/SendRemindersApiTest.php
index d394b0d415..c90b3dda9a 100644
--- a/tests/Feature/Api/UnacceptedAcceptances/SendRemindersApiTest.php
+++ b/tests/Feature/Api/UnacceptedAcceptances/SendRemindersApiTest.php
@@ -2,13 +2,12 @@
namespace Tests\Feature\Api\UnacceptedAcceptances;
-use App\Mail\UnacceptedAssetReminderMail;
use App\Models\Asset;
use App\Models\CheckoutAcceptance;
use App\Models\Company;
use App\Models\User;
-use Illuminate\Support\Facades\Artisan;
-use Illuminate\Support\Facades\Mail;
+use App\Notifications\UnacceptedAssetReminderNotification;
+use Illuminate\Support\Facades\Notification;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
@@ -32,66 +31,88 @@ class SendRemindersApiTest extends TestCase
}
#[Test]
- public function missing_ids_delegates_to_the_artisan_command(): void
+ public function missing_ids_sends_to_every_pending_assignee(): void
{
- Mail::fake();
- Artisan::spy();
+ Notification::fake();
+
+ $userA = User::factory()->create(['email' => '[email protected]']);
+ $userB = User::factory()->create(['email' => '[email protected]']);
+ $userNoEmail = User::factory()->create(['email' => '']);
+
+ CheckoutAcceptance::factory()->pending()->count(2)->create(['assigned_to_id' => $userA->id]);
+ CheckoutAcceptance::factory()->pending()->create(['assigned_to_id' => $userB->id]);
+ CheckoutAcceptance::factory()->pending()->create(['assigned_to_id' => $userNoEmail->id]);
$this->actingAsForApi(User::factory()->superuser()->create())
->postJson(route('api.unaccepted-acceptances.send-reminders'))
->assertOk()
->assertJsonPath('status', 'success')
- ->assertJsonPath('payload.mode', 'all');
+ ->assertJsonPath('payload.mode', 'all')
+ ->assertJsonPath('payload.sent', 2)
+ ->assertJsonPath('payload.skipped.no_email', 1);
- Artisan::shouldHaveReceived('call')->with('snipeit:acceptance-reminder')->once();
+ Notification::assertSentTo($userA, UnacceptedAssetReminderNotification::class);
+ Notification::assertSentTo($userB, UnacceptedAssetReminderNotification::class);
+ Notification::assertNotSentTo($userNoEmail, UnacceptedAssetReminderNotification::class);
}
#[Test]
- public function empty_ids_array_also_delegates_to_the_artisan_command(): void
+ public function empty_ids_array_also_sends_to_every_pending_assignee(): void
{
- // Explicitly-empty array arrives from well-formed clients that
- // always include the key. Should behave the same as missing.
- Artisan::spy();
+ // Explicitly-empty array arrives from well-formed clients
+ // that always include the key. Should behave the same as a
+ // missing one.
+ Notification::fake();
+
+ $user = User::factory()->create(['email' => '[email protected]']);
+ CheckoutAcceptance::factory()->pending()->create(['assigned_to_id' => $user->id]);
$this->actingAsForApi(User::factory()->superuser()->create())
->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => []])
->assertOk()
- ->assertJsonPath('payload.mode', 'all');
+ ->assertJsonPath('payload.mode', 'all')
+ ->assertJsonPath('payload.sent', 1);
- Artisan::shouldHaveReceived('call')->with('snipeit:acceptance-reminder')->once();
+ Notification::assertSentTo($user, UnacceptedAssetReminderNotification::class);
}
#[Test]
- public function ids_in_body_sends_per_row_and_bypasses_the_console_command(): void
+ public function ids_in_body_narrows_to_only_the_targeted_assignees(): void
{
- Mail::fake();
- Artisan::spy();
+ // Verifies ids-mode doesn't accidentally mail every pending
+ // assignee the way the no-ids send-all path does.
+ Notification::fake();
- $assignee = User::factory()->create(['email' => '[email protected]']);
- $asset = Asset::factory()->create();
- $acceptance = CheckoutAcceptance::factory()
+ $targeted = User::factory()->create(['email' => '[email protected]']);
+ $unrelated = User::factory()->create(['email' => '[email protected]']);
+
+ $targetedAcceptance = CheckoutAcceptance::factory()
->pending()
- ->for($asset, 'checkoutable')
- ->for($assignee, 'assignedTo')
+ ->for(Asset::factory(), 'checkoutable')
+ ->for($targeted, 'assignedTo')
+ ->create();
+
+ // Unrelated user has a pending acceptance that's NOT in the ids list.
+ CheckoutAcceptance::factory()
+ ->pending()
+ ->for(Asset::factory(), 'checkoutable')
+ ->for($unrelated, 'assignedTo')
->create();
$this->actingAsForApi(User::factory()->superuser()->create())
- ->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => [$acceptance->id]])
+ ->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => [$targetedAcceptance->id]])
->assertOk()
->assertJsonPath('payload.mode', 'ids')
- ->assertJsonPath('payload.sent', 1)
- ->assertJsonPath('payload.skipped.not_found', 0)
- ->assertJsonPath('payload.skipped.fmcs', 0)
- ->assertJsonPath('payload.skipped.no_email', 0);
+ ->assertJsonPath('payload.sent', 1);
- Mail::assertSent(UnacceptedAssetReminderMail::class);
- Artisan::shouldNotHaveReceived('call');
+ Notification::assertSentTo($targeted, UnacceptedAssetReminderNotification::class);
+ Notification::assertNotSentTo($unrelated, UnacceptedAssetReminderNotification::class);
}
#[Test]
- public function id_pointing_at_a_non_pending_acceptance_is_counted_as_not_found(): void
+ public function id_pointing_at_a_non_pending_acceptance_sends_nothing(): void
{
- Mail::fake();
+ Notification::fake();
$assignee = User::factory()->create(['email' => '[email protected]']);
$asset = Asset::factory()->create();
@@ -103,16 +124,15 @@ class SendRemindersApiTest extends TestCase
$this->actingAsForApi(User::factory()->superuser()->create())
->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => [$acceptance->id]])
->assertOk()
- ->assertJsonPath('payload.sent', 0)
- ->assertJsonPath('payload.skipped.not_found', 1);
+ ->assertJsonPath('payload.sent', 0);
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
#[Test]
- public function acceptance_without_assignee_email_is_counted_as_no_email(): void
+ public function acceptance_without_assignee_email_sends_nothing(): void
{
- Mail::fake();
+ Notification::fake();
$assignee = User::factory()->create(['email' => '']);
$asset = Asset::factory()->create();
@@ -125,16 +145,15 @@ class SendRemindersApiTest extends TestCase
$this->actingAsForApi(User::factory()->superuser()->create())
->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => [$acceptance->id]])
->assertOk()
- ->assertJsonPath('payload.sent', 0)
- ->assertJsonPath('payload.skipped.no_email', 1);
+ ->assertJsonPath('payload.sent', 0);
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
#[Test]
public function fmcs_blocks_cross_company_ids_without_leaking_to_the_mail_queue(): void
{
- Mail::fake();
+ Notification::fake();
$this->settings->enableMultipleFullCompanySupport();
[$companyA, $companyB] = Company::factory()->count(2)->create();
@@ -155,16 +174,15 @@ class SendRemindersApiTest extends TestCase
$this->actingAsForApi($callerInA)
->postJson(route('api.unaccepted-acceptances.send-reminders'), ['ids' => [$acceptance->id]])
->assertOk()
- ->assertJsonPath('payload.sent', 0)
- ->assertJsonPath('payload.skipped.fmcs', 1);
+ ->assertJsonPath('payload.sent', 0);
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
#[Test]
- public function mixed_batch_reports_each_outcome_separately(): void
+ public function mixed_batch_sends_only_valid_rows(): void
{
- Mail::fake();
+ Notification::fake();
$goodAssignee = User::factory()->create(['email' => '[email protected]']);
$noEmailAssignee = User::factory()->create(['email' => '']);
@@ -186,10 +204,34 @@ class SendRemindersApiTest extends TestCase
'ids' => [$goodAcceptance->id, $noEmailAcceptance->id, 999999],
])
->assertOk()
- ->assertJsonPath('payload.sent', 1)
- ->assertJsonPath('payload.skipped.no_email', 1)
- ->assertJsonPath('payload.skipped.not_found', 1);
+ ->assertJsonPath('payload.sent', 1);
+
+ Notification::assertSentTimes(UnacceptedAssetReminderNotification::class, 1);
+ }
+
+ #[Test]
+ public function selecting_multiple_acceptances_for_one_user_dedupes_to_one_email(): void
+ {
+ // Regression pin for the dedupe behavior. A user with three
+ // pending acceptances who gets all three selected in the
+ // bulk UI should receive one UnacceptedAssetReminderNotification
+ // with count=3, not three separate emails.
+ Notification::fake();
+
+ $assignee = User::factory()->create(['email' => '[email protected]']);
+ $acceptances = CheckoutAcceptance::factory()->count(3)
+ ->pending()
+ ->for(Asset::factory(), 'checkoutable')
+ ->for($assignee, 'assignedTo')
+ ->create();
+
+ $this->actingAsForApi(User::factory()->superuser()->create())
+ ->postJson(route('api.unaccepted-acceptances.send-reminders'), [
+ 'ids' => $acceptances->pluck('id')->all(),
+ ])
+ ->assertOk()
+ ->assertJsonPath('payload.sent', 1);
- Mail::assertSent(UnacceptedAssetReminderMail::class, 1);
+ Notification::assertSentTimes(UnacceptedAssetReminderNotification::class, 1);
}
}
diff --git a/tests/Feature/Console/SendAcceptanceReminderTest.php b/tests/Feature/Console/SendAcceptanceReminderTest.php
index e9630b3714..ae3b1e2e53 100644
--- a/tests/Feature/Console/SendAcceptanceReminderTest.php
+++ b/tests/Feature/Console/SendAcceptanceReminderTest.php
@@ -2,11 +2,12 @@
namespace Tests\Feature\Console;
-use App\Mail\UnacceptedAssetReminderMail;
use App\Models\CheckoutAcceptance;
use App\Models\User;
+use App\Notifications\UnacceptedAssetReminderNotification;
+use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Mail;
+use Illuminate\Support\Facades\Notification;
use Mockery;
use Symfony\Component\Mailer\Exception\TransportException;
use Tests\TestCase;
@@ -15,7 +16,7 @@ class SendAcceptanceReminderTest extends TestCase
{
public function test_acceptance_reminder_command()
{
- Mail::fake();
+ Notification::fake();
$userA = User::factory()->create(['email' => '[email protected]']);
$userB = User::factory()->create(['email' => '[email protected]']);
@@ -28,20 +29,14 @@ class SendAcceptanceReminderTest extends TestCase
$this->artisan('snipeit:acceptance-reminder')->assertExitCode(0);
- Mail::assertSent(UnacceptedAssetReminderMail::class, function ($mail) {
- return $mail->hasTo('[email protected]');
- });
-
- Mail::assertSent(UnacceptedAssetReminderMail::class, function ($mail) {
- return $mail->hasTo('[email protected]');
- });
-
- Mail::assertSent(UnacceptedAssetReminderMail::class, 2);
+ Notification::assertSentTo($userA, UnacceptedAssetReminderNotification::class);
+ Notification::assertSentTo($userB, UnacceptedAssetReminderNotification::class);
+ Notification::assertSentTimes(UnacceptedAssetReminderNotification::class, 2);
}
public function test_acceptance_reminder_command_handles_user_without_email()
{
- Mail::fake();
+ Notification::fake();
$userA = User::factory()->create(['email' => '']);
CheckoutAcceptance::factory()->pending()->create([
@@ -56,7 +51,7 @@ class SendAcceptanceReminderTest extends TestCase
->expectsTable($headers, $rows)
->assertExitCode(0);
- Mail::assertNotSent(UnacceptedAssetReminderMail::class);
+ Notification::assertNotSentTo($userA, UnacceptedAssetReminderNotification::class);
}
public function test_survives_transport_exception_and_logs_warning(): void
@@ -64,9 +59,13 @@ class SendAcceptanceReminderTest extends TestCase
$user = User::factory()->create(['email' => '[email protected]']);
CheckoutAcceptance::factory()->pending()->create(['assigned_to_id' => $user->id]);
- $pending = Mockery::mock();
- $pending->shouldReceive('send')->andThrow(new TransportException('SMTP auth failed'));
- Mail::shouldReceive('to')->andReturn($pending);
+ // Mock the notification channel manager so the mail driver
+ // throws a transport exception on dispatch. The console
+ // command catches TransportException and logs a warning
+ // rather than bubbling up.
+ $channelManager = Mockery::mock(ChannelManager::class);
+ $channelManager->shouldReceive('send')->andThrow(new TransportException('SMTP auth failed'));
+ $this->app->instance(ChannelManager::class, $channelManager);
Log::spy();
diff --git a/tests/Feature/Reporting/SentReminderAuthorizationTest.php b/tests/Feature/Reporting/SentReminderAuthorizationTest.php
index 5f2998d8a3..86e813567a 100644
--- a/tests/Feature/Reporting/SentReminderAuthorizationTest.php
+++ b/tests/Feature/Reporting/SentReminderAuthorizationTest.php
@@ -2,12 +2,12 @@
namespace Tests\Feature\Reporting;
-use App\Mail\UnacceptedAssetReminderMail;
use App\Models\Asset;
use App\Models\CheckoutAcceptance;
use App\Models\Company;
use App\Models\User;
-use Illuminate\Support\Facades\Mail;
+use App\Notifications\UnacceptedAssetReminderNotification;
+use Illuminate\Support\Facades\Notification;
use Tests\TestCase;
/**
@@ -20,7 +20,7 @@ class SentReminderAuthorizationTest extends TestCase
{
public function test_user_without_checkout_grant_cannot_send_reminder()
{
- Mail::fake();
+ Notification::fake();
$assignee = User::factory()->create(['email' => '[email protected]']);
$asset = Asset::factory()->create();
@@ -34,7 +34,7 @@ class SentReminderAuthorizationTest extends TestCase
->post(route('unaccepted-acceptances.send-reminder'), ['acceptance_id' => $acceptance->id])
->assertForbidden();
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
public function test_user_with_reports_view_only_cannot_send_reminder()
@@ -42,7 +42,7 @@ class SentReminderAuthorizationTest extends TestCase
// Regression pin for the v8.9 move. reports.view alone no
// longer unlocks a reminder send. The actor must hold a
// checkout grant on at least one type.
- Mail::fake();
+ Notification::fake();
$assignee = User::factory()->create(['email' => '[email protected]']);
$asset = Asset::factory()->create();
@@ -56,12 +56,12 @@ class SentReminderAuthorizationTest extends TestCase
->post(route('unaccepted-acceptances.send-reminder'), ['acceptance_id' => $acceptance->id])
->assertForbidden();
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
public function test_checkout_user_can_send_reminder_for_their_own_company()
{
- Mail::fake();
+ Notification::fake();
$this->settings->enableMultipleFullCompanySupport();
[$companyA] = Company::factory()->count(2)->create();
@@ -80,12 +80,12 @@ class SentReminderAuthorizationTest extends TestCase
->assertRedirectToRoute('unaccepted-acceptances.index')
->assertSessionHas('success');
- Mail::assertSent(UnacceptedAssetReminderMail::class);
+ Notification::assertSentTo($assignee, UnacceptedAssetReminderNotification::class);
}
public function test_checkout_user_cannot_send_reminder_for_another_company()
{
- Mail::fake();
+ Notification::fake();
$this->settings->enableMultipleFullCompanySupport();
[$companyA, $companyB] = Company::factory()->count(2)->create();
@@ -104,12 +104,12 @@ class SentReminderAuthorizationTest extends TestCase
->assertRedirectToRoute('unaccepted-acceptances.index')
->assertSessionHas('error');
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
public function test_pivot_only_user_cannot_send_reminder_for_another_company()
{
- Mail::fake();
+ Notification::fake();
$this->settings->enableMultipleFullCompanySupport();
[$companyA, $companyB] = Company::factory()->count(2)->create();
@@ -130,12 +130,12 @@ class SentReminderAuthorizationTest extends TestCase
->assertRedirectToRoute('unaccepted-acceptances.index')
->assertSessionHas('error');
- Mail::assertNothingSent();
+ Notification::assertNothingSent();
}
public function test_superuser_can_send_reminder_for_any_company()
{
- Mail::fake();
+ Notification::fake();
$this->settings->enableMultipleFullCompanySupport();
[$companyA, $companyB] = Company::factory()->count(2)->create();
@@ -154,6 +154,6 @@ class SentReminderAuthorizationTest extends TestCase
->assertRedirectToRoute('unaccepted-acceptances.index')
->assertSessionHas('success');
- Mail::assertSent(UnacceptedAssetReminderMail::class);
+ Notification::assertSentTo($assignee, UnacceptedAssetReminderNotification::class);
}
}
diff --git a/tests/Feature/Users/Ui/ResendAcceptanceReminderTest.php b/tests/Feature/Users/Ui/ResendAcceptanceReminderTest.php
index 044f7a8d2a..6d62d4a20e 100644
--- a/tests/Feature/Users/Ui/ResendAcceptanceReminderTest.php
+++ b/tests/Feature/Users/Ui/ResendAcceptanceReminderTest.php
@@ -2,17 +2,17 @@
namespace Tests\Feature\Users\Ui;
-use App\Mail\UnacceptedAssetReminderMail;
use App\Models\CheckoutAcceptance;
use App\Models\User;
-use Illuminate\Support\Facades\Mail;
+use App\Notifications\UnacceptedAssetReminderNotification;
+use Illuminate\Support\Facades\Notification;
use Tests\TestCase;
class ResendAcceptanceReminderTest extends TestCase
{
- public function test_it_sends_acceptance_reminder_email_for_user_with_pending_acceptances(): void
+ public function test_it_sends_acceptance_reminder_for_user_with_pending_acceptances(): void
{
- Mail::fake();
+ Notification::fake();
$viewer = User::factory()->viewUsers()->create();
$targetUser = User::factory()->create(['email' => '[email protected]']);
@@ -26,14 +26,12 @@ class ResendAcceptanceReminderTest extends TestCase
->assertRedirect()
->assertSessionHas('success');
- Mail::assertSent(UnacceptedAssetReminderMail::class, function (UnacceptedAssetReminderMail $mail) use ($targetUser) {
- return $mail->hasTo($targetUser->email);
- });
+ Notification::assertSentTo($targetUser, UnacceptedAssetReminderNotification::class);
}
public function test_it_does_not_send_when_user_has_no_pending_acceptances(): void
{
- Mail::fake();
+ Notification::fake();
$viewer = User::factory()->viewUsers()->create();
$targetUser = User::factory()->create(['email' => '[email protected]']);
@@ -43,12 +41,12 @@ class ResendAcceptanceReminderTest extends TestCase
->assertRedirect()
->assertSessionHas('warning');
- Mail::assertNotSent(UnacceptedAssetReminderMail::class);
+ Notification::assertNotSentTo($targetUser, UnacceptedAssetReminderNotification::class);
}
public function test_it_does_not_send_when_user_has_no_email(): void
{
- Mail::fake();
+ Notification::fake();
$viewer = User::factory()->viewUsers()->create();
$targetUser = User::factory()->create(['email' => '']);
@@ -62,6 +60,6 @@ class ResendAcceptanceReminderTest extends TestCase
->assertRedirect()
->assertSessionHas('error');
- Mail::assertNotSent(UnacceptedAssetReminderMail::class);
+ Notification::assertNotSentTo($targetUser, UnacceptedAssetReminderNotification::class);
}
}