Skip to content
Merged

Dev #3399

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
86 changes: 86 additions & 0 deletions app/Console/Commands/CertificateClearGeneration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace App\Console\Commands;

use App\Excellence;
use App\Jobs\GenerateCertificateBatchJob;
use App\Jobs\SendCertificateBatchJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class CertificateClearGeneration extends Command
{
protected $signature = 'certificate:clear-generation
{--edition=2025 : Target edition year}
{--type=all : excellence|super-organiser|all}
{--clear-send-state : Also clear notified_at and certificate_sent_error}
{--yes : Skip confirmation prompt}';

protected $description = 'Clear certificate generation state for a year/type (optionally send state too)';

public function handle(): int
{
$edition = (int) $this->option('edition');
$typeOption = strtolower(trim((string) $this->option('type')));
$clearSendState = (bool) $this->option('clear-send-state');
$skipConfirm = (bool) $this->option('yes');

$types = $this->resolveTypes($typeOption);
if ($types === null) {
$this->error("Invalid --type value: {$typeOption}. Use 'excellence', 'super-organiser', or 'all'.");
return self::FAILURE;
}

if (! $skipConfirm) {
$typeLabel = implode(', ', $types);
$message = "This will clear certificate generation state for edition {$edition}, type(s): {$typeLabel}."
. ($clearSendState ? ' It will ALSO clear send state (notified_at/sent_error).' : '');
if (! $this->confirm($message . ' Continue?', false)) {
$this->warn('Cancelled.');
return self::SUCCESS;
}
}

$update = [
'certificate_url' => null,
'certificate_generation_error' => null,
];
if ($clearSendState) {
$update['notified_at'] = null;
$update['certificate_sent_error'] = null;
}

$totalUpdated = 0;
foreach ($types as $type) {
$updated = Excellence::query()
->where('edition', $edition)
->where('type', $type)
->update($update);

$totalUpdated += $updated;
$this->info("Updated rows for {$type}: {$updated}");

Cache::forget(sprintf(GenerateCertificateBatchJob::CACHE_KEY_RUNNING, $edition, $type));
Cache::forget(sprintf(GenerateCertificateBatchJob::CACHE_KEY_CANCELLED, $edition, $type));
Cache::forget(sprintf(SendCertificateBatchJob::CACHE_KEY_SEND_RUNNING, $edition, $type));
}

$this->info("Done. Total rows updated: {$totalUpdated}");
$this->line('Tip: run certificate:stats next to verify counts.');

return self::SUCCESS;
}

/**
* @return array<int, string>|null
*/
private function resolveTypes(string $typeOption): ?array
{
return match ($typeOption) {
'all' => ['Excellence', 'SuperOrganiser'],
'excellence' => ['Excellence'],
'super-organiser', 'superorganiser' => ['SuperOrganiser'],
default => null,
};
}
}
125 changes: 125 additions & 0 deletions app/Console/Commands/CertificateFailuresReport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php

namespace App\Console\Commands;

use App\Excellence;
use Illuminate\Console\Command;

class CertificateFailuresReport extends Command
{
protected $signature = 'certificate:failures-report
{--edition=2025 : Target edition year}
{--type=all : excellence|super-organiser|all}
{--limit=0 : Show first N rows (0 = all)}
{--export= : Optional CSV export path (absolute or relative to project root)}';

protected $description = 'List/export certificate generation failures for review before sending emails';

public function handle(): int
{
$edition = (int) $this->option('edition');
$typeOption = strtolower(trim((string) $this->option('type')));
$limit = max(0, (int) $this->option('limit'));
$exportPath = trim((string) $this->option('export'));

$types = $this->resolveTypes($typeOption);
if ($types === null) {
$this->error("Invalid --type value: {$typeOption}. Use 'excellence', 'super-organiser', or 'all'.");
return self::FAILURE;
}

$rows = Excellence::query()
->where('edition', $edition)
->whereIn('type', $types)
->whereNotNull('certificate_generation_error')
->with('user')
->orderBy('type')
->orderBy('id')
->get();

if ($rows->isEmpty()) {
$this->info("No generation failures found for edition {$edition}, type {$typeOption}.");
return self::SUCCESS;
}

$displayRows = $limit > 0 ? $rows->take($limit) : $rows;
$table = $displayRows->map(function (Excellence $e) {
$name = $e->name_for_certificate;
if (! $name && $e->user) {
$name = trim(($e->user->firstname ?? '') . ' ' . ($e->user->lastname ?? ''));
}
return [
'id' => $e->id,
'type' => $e->type,
'user_id' => $e->user_id,
'email' => $e->user?->email ?? '',
'name' => $name ?? '',
'error' => $e->certificate_generation_error,
];
})->values()->all();

$this->info('Generation failures: ' . $rows->count());
if ($limit > 0 && $rows->count() > $limit) {
$this->line("Showing first {$limit} rows.");
}
$this->table(['id', 'type', 'user_id', 'email', 'name', 'error'], $table);

if ($exportPath !== '') {
$fullPath = $this->resolvePath($exportPath);
$dir = dirname($fullPath);
if (! is_dir($dir) && ! @mkdir($dir, 0775, true) && ! is_dir($dir)) {
$this->error("Failed to create directory: {$dir}");
return self::FAILURE;
}

$fh = @fopen($fullPath, 'wb');
if (! $fh) {
$this->error("Failed to open export file: {$fullPath}");
return self::FAILURE;
}

fputcsv($fh, ['id', 'type', 'edition', 'user_id', 'email', 'name_for_certificate', 'certificate_generation_error']);
foreach ($rows as $e) {
$name = $e->name_for_certificate;
if (! $name && $e->user) {
$name = trim(($e->user->firstname ?? '') . ' ' . ($e->user->lastname ?? ''));
}
fputcsv($fh, [
$e->id,
$e->type,
$e->edition,
$e->user_id,
$e->user?->email ?? '',
$name ?? '',
$e->certificate_generation_error,
]);
}
fclose($fh);
$this->info("Exported CSV: {$fullPath}");
}

$this->line('Note: send flows already exclude rows without certificate_url, so failed generation rows are not emailed.');
return self::SUCCESS;
}

/**
* @return array<int, string>|null
*/
private function resolveTypes(string $typeOption): ?array
{
return match ($typeOption) {
'all' => ['Excellence', 'SuperOrganiser'],
'excellence' => ['Excellence'],
'super-organiser', 'superorganiser' => ['SuperOrganiser'],
default => null,
};
}

private function resolvePath(string $path): string
{
if (str_starts_with($path, '/')) {
return $path;
}
return base_path($path);
}
}
8 changes: 1 addition & 7 deletions app/Http/Controllers/CertificateBackendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,15 +228,14 @@ public function startSend(Request $request): JsonResponse
$pending = Excellence::query()
->where('edition', $edition)
->where('type', $type)
->whereNotNull('certificate_url')
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
->limit(1)
->exists();

if (! $pending) {
return response()->json(['ok' => false, 'message' => 'No pending recipients with generated certificates.']);
return response()->json(['ok' => false, 'message' => 'No pending recipients to send.']);
}

SendCertificateBatchJob::dispatch($edition, $type, 0);
Expand Down Expand Up @@ -326,7 +325,6 @@ public function resendAllFailed(Request $request): JsonResponse
$count = Excellence::query()
->where('edition', $edition)
->where('type', $type)
->whereNotNull('certificate_url')
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
Expand Down Expand Up @@ -451,10 +449,6 @@ public function manualCreateSend(Request $request): JsonResponse
]);
}

if ($sendOnly && ! $excellence->certificate_url) {
return response()->json(['ok' => false, 'message' => 'No certificate yet. Generate first.']);
}

try {
if ($type === 'SuperOrganiser') {
$this->sendCertificateMail($user->email, new NotifySuperOrganiser($user, $edition, $excellence->certificate_url));
Expand Down
5 changes: 2 additions & 3 deletions app/Jobs/SendCertificateBatchJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ public function handle(): void
$runningKey = sprintf(self::CACHE_KEY_SEND_RUNNING, $this->edition, $this->type);
Cache::put($runningKey, time(), self::CACHE_TTL);

// Send to: has cert and (not yet sent or had send error)
// Send to: all qualified recipients for this edition/type that are unsent or had send error.
// certificate_url may be null; email templates fall back to certificate pages where users generate themselves.
$query = Excellence::query()
->where('edition', $this->edition)
->where('type', $this->type)
->whereNotNull('certificate_url')
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
Expand Down Expand Up @@ -73,7 +73,6 @@ public function handle(): void
$hasMore = Excellence::query()
->where('edition', $this->edition)
->where('type', $this->type)
->whereNotNull('certificate_url')
->where(function ($q) {
$q->whereNull('notified_at')->orWhereNotNull('certificate_sent_error');
})
Expand Down
2 changes: 1 addition & 1 deletion resources/views/certificate-backend/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
<button type="button" id="btn-generate" class="px-6 py-3 mr-2 font-semibold text-white rounded-full duration-300 cursor-pointer bg-primary hover:opacity-90">Generate certificates</button>
<button type="button" id="btn-cancel" class="px-6 py-3 font-semibold text-white rounded-full duration-300 cursor-pointer bg-primary hover:opacity-90">Cancel generation</button>
</div>
<p style="margin-bottom: 0.5rem;"><strong>Step 2 – Send:</strong> (only after certificates are generated)</p>
<p style="margin-bottom: 0.5rem;"><strong>Step 2 – Send:</strong> (sends to all qualified recipients; certificate can be generated from email link)</p>
<div>
<button type="button" id="btn-send" class="px-6 py-3 mr-2 font-semibold text-white rounded-full duration-300 cursor-pointer bg-primary hover:opacity-90">Send emails (batches of 100)</button>
<button type="button" id="btn-resend-all-failed" class="px-6 py-3 font-semibold text-white rounded-full duration-300 cursor-pointer bg-primary hover:opacity-90">Resend all failed / unsent</button>
Expand Down
Loading