Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions app/Console/Commands/NotifyInactiveProjects.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

namespace App\Console\Commands;

use App\Models\Project;
use App\Models\User;
use App\Notifications\ProjectInactivityReminderNotification;
use App\Notifications\ProjectInactivityReportToAdmins;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;

class NotifyInactiveProjects extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'nmrxiv:notify-inactive-projects {--months= : Number of months of inactivity (defaults to config inactivity.grace_months)} {--list : Only list inactive projects without notifying} {--report-admins : Email admins a report of inactive projects}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Notify project owners if the project has had no updates for N months (default 6).';

/**
* Execute the console command.
*/
public function handle(): int
{
$months = (int) ($this->option('months') ?? config('inactivity.grace_months', 6));
$threshold = Carbon::now()->subMonths($months);

return DB::transaction(function () use ($threshold) {
// Identify inactive projects and mark them inactive
$projects = Project::with('owner', 'users')
->where('is_public', false)
->where('is_deleted', false)
->where('is_archived', false)
->where('updated_at', '<', $threshold)
->get();

if ($this->option('list')) {
$this->table(['ID', 'Name', 'Owner Email', 'Updated At'], $projects->map(function ($p) {
return [$p->id, $p->name, optional($p->owner)->email, (string) $p->updated_at];
})->toArray());
$this->info('Total inactive projects: '.count($projects));

return self::SUCCESS;
}

// Mark these projects as inactive in DB (idempotent) without touching updated_at
if ($projects->count() > 0) {
$ids = $projects->pluck('id');
Project::withoutTimestamps(function () use ($ids) {
Project::whereIn('id', $ids)->update(['active' => false]);
});
}

// Aggregate by recipient so each user gets a single digest listing all of their inactive projects
$recipientProjects = [];
foreach ($projects as $project) {
foreach ($this->prepareSendList($project) as $recipient) {
$recipientProjects[$recipient->id]['user'] = $recipient;
$recipientProjects[$recipient->id]['projects'][] = $project;
}
}

// Send one email per recipient with their list of inactive projects
$sentCount = 0;
foreach ($recipientProjects as $entry) {
/** @var \App\Models\User $user */
$user = $entry['user'];
$list = collect($entry['projects'])->map(function ($p) {
return [
'id' => $p->id,
'name' => $p->name,
'updated_at' => (string) $p->updated_at,
'url' => url(config('app.url').'/dashboard/projects/'.$p->id),
];
})->values()->all();

Notification::send($user, new ProjectInactivityReminderNotification($list));
$sentCount++;
}

$this->info('Inactive project digests sent: '.$sentCount.' (covering '.count($projects).' projects)');

if ($this->option('report-admins') && $projects->count() > 0) {
$payload = $projects->map(function ($p) {
return [
'id' => $p->id,
'name' => $p->name,
'owner' => optional($p->owner)->email ?? 'N/A',
'updated_at' => (string) $p->updated_at,
];
})->values()->all();

Notification::send(User::role(['super-admin'])->get(), new ProjectInactivityReportToAdmins($payload));
$this->info('Admin report sent to super-admins.');
}

return self::SUCCESS;
});
}

/**
* Prepare recipients list (owner and creators).
*/
protected function prepareSendList(Project $project): array
{
$sendTo = [];
$add = function ($user) use (&$sendTo) {
if ($user && isset($user->id)) {
$sendTo[$user->id] = $user;
}
};

foreach ($project->allUsers() as $member) {
if ($member->projectMembership->role == 'creator' || $member->projectMembership->role == 'owner') {
$add($member);
}
}

$add($project->owner);

return array_values($sendTo);
}
}
47 changes: 47 additions & 0 deletions app/Mail/ProjectInactivityReminder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ProjectInactivityReminder extends Mailable
{
use Queueable, SerializesModels;

public $projectOrList;

/**
* Accept either a single Project or an array list for digest emails.
*/
public function __construct($projectOrList)
{
$this->projectOrList = $projectOrList;
}

/**
* Build the message.
*/
public function build()
{
// Digest mode when an array is passed
if (is_array($this->projectOrList)) {
return $this->markdown('vendor.mail.project-inactivity-reminder', [
'digest' => true,
'projects' => $this->projectOrList,
'thresholdMonths' => (int) config('inactivity.grace_months', 6),
])->subject(__('Your inactive projects digest'));
}

// Single project mode (backwards compatible)
$project = $this->projectOrList;

return $this->markdown('vendor.mail.project-inactivity-reminder', [
'url' => url(config('app.url').'/dashboard/projects/'.$project->id),
'projectName' => $project->name,
'lastUpdated' => explode(' ', \Illuminate\Support\Carbon::parse($project->updated_at))[0],
'digest' => false,
])->subject(__('Your project has been inactive'.' - '.$project->name));
}
}
26 changes: 26 additions & 0 deletions app/Mail/ProjectInactivityReportToAdmins.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ProjectInactivityReportToAdmins extends Mailable
{
use Queueable, SerializesModels;

/** @param array<int, array{id:int,name:string,owner:string,updated_at:string}> $projects */
public function __construct(private array $projects)
{
//
}

public function build(): self
{
return $this->markdown('vendor.mail.project-inactivity-report-admins', [
'projects' => $this->projects,
'thresholdMonths' => (int) config('inactivity.grace_months', 6),
])->subject(__('Inactive projects report'));
}
}
28 changes: 28 additions & 0 deletions app/Models/Project.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Events\ProjectDeletion;
use App\Notifications\ProjectDeletionFailureNotification;
use App\Notifications\ProjectDeletionReminderNotification;
use App\Notifications\ProjectInactivityReminderNotification;
use App\Traits\CacheClear;
use Auth;
use Carbon\Carbon;
Expand Down Expand Up @@ -42,6 +43,7 @@ class Project extends Model implements Auditable
'starred',
'location',
'is_public',
'active',
'obfuscationcode',
'description',
'type',
Expand All @@ -59,6 +61,16 @@ class Project extends Model implements Auditable
'species',
];

/**
* Casts for the model attributes.
*/
protected function casts(): array
{
return [
'active' => 'boolean',
];
}

protected static $marks = [
Like::class,
Bookmark::class,
Expand Down Expand Up @@ -285,6 +297,19 @@ public function validation(): BelongsTo
return $this->belongsTo(Validation::class, 'validation_id');
}

/**
* Model boot method to ensure that any meaningful update re-activates the project.
*/
protected static function booted(): void
{
static::saving(function (Project $project): void {
// If something changes other than 'active' itself, mark as active again
if ($project->isDirty() && ! $project->isDirty('active')) {
$project->active = true;
}
});
}

/**
* Determine if the model should be searchable.
*
Expand Down Expand Up @@ -354,6 +379,9 @@ public function sendNotification($notifyType, $sendTo)
case 'publish':
event(new DraftProcessed($this, $sendTo));
break;
case 'inactivityReminder':
Notification::send($sendTo, new ProjectInactivityReminderNotification($this));
break;
}
}
}
46 changes: 46 additions & 0 deletions app/Notifications/ProjectInactivityReminderNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Notifications;

use App\Mail\ProjectInactivityReminder as ProjectInactivityReminderMailable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Notification;

class ProjectInactivityReminderNotification extends Notification implements ShouldQueue
{
use Queueable;

/**
* @param mixed $payload Either a Project instance or an array of projects for digest
*/
public function __construct(private $payload)
{
//
}

/**
* Get the notification's delivery channels.
*/
public function via($notifiable): array
{
return ['mail'];
}

/**
* Get the mail representation of the notification.
*/
public function toMail($notifiable): Mailable
{
return (new ProjectInactivityReminderMailable($this->payload))->to($notifiable->email);
}

/**
* Get the array representation of the notification.
*/
public function toArray($notifiable): array
{
return [];
}
}
35 changes: 35 additions & 0 deletions app/Notifications/ProjectInactivityReportToAdmins.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Notifications;

use App\Mail\ProjectInactivityReportToAdmins as ProjectInactivityReportToAdminsMailable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Notification;

class ProjectInactivityReportToAdmins extends Notification implements ShouldQueue
{
use Queueable;

/** @param array<int, array{id:int,name:string,owner:string,updated_at:string}> $projects */
public function __construct(private array $projects)
{
//
}

public function via($notifiable): array
{
return ['mail'];
}

public function toMail($notifiable): Mailable
{
return (new ProjectInactivityReportToAdminsMailable($this->projects))->to($notifiable->email);
}

public function toArray($notifiable): array
{
return [];
}
}
6 changes: 6 additions & 0 deletions config/inactivity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php

return [
// Inactivity grace period in months before notifications and potential actions
'grace_months' => (int) env('INACTIVITY_GRACE_MONTHS', 6),
];
1 change: 1 addition & 0 deletions database/factories/ProjectFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public function definition(): array
'is_public' => false,
'is_deleted' => false,
'is_archived' => false,
'active' => true,
'status' => 'draft',
'process_logs' => null,
'location' => null, // todo: Adjust when location field is provided in nmrXiv
Expand Down
Loading
Loading