Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: process protocols #142

Merged
merged 6 commits into from
Jan 19, 2024
Merged
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
21 changes: 21 additions & 0 deletions .env.ci
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
APP_ENV=ci
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=tests
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=array
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=array

MAIL_MAILER=log
82 changes: 82 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: Tests

on: [push]

jobs:
test:
name: PHP ${{ matrix.php-version }}
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
php-version:
- "8.2"

env:
extensions: mbstring, pdo, pdo_mysql, intl, gd

services:
mysql:
image: mysql:8
env:
MYSQL_DATABASE: tests
MYSQL_ALLOW_EMPTY_PASSWORD: yes
ports:
- 3306/tcp
options: >-
--health-cmd "mysqladmin ping"
--health-interval 10s
--health-timeout 5s
--health-retries 3

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup cache environment
id: extcache
uses: shivammathur/cache-extensions@v1
with:
php-version: ${{ matrix.php-version }}
extensions: ${{ env.extensions }}
key: php-extensions-cache

- name: Cache extensions
uses: actions/cache@v3
with:
path: ${{ steps.extcache.outputs.dir }}
key: ${{ steps.extcache.outputs.key }}
restore-keys: ${{ steps.extcache.outputs.key }}

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: ${{ env.extensions }}
coverage: pcov
tools: composer:v2

- name: Get composer cache directory
id: composercache
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

- name: Cache composer dependencies
uses: actions/cache@v3
with:
path: ${{ steps.composercache.outputs.dir }}
key: dependencies-composer-${{ hashFiles('composer.lock') }}-php-${{ matrix.php-version }}
restore-keys: dependencies-composer-

- name: Install composer dependencies
run: composer install --prefer-dist --no-interaction

- name: Setup env
run: |
cp .env.ci .env
php artisan key:generate --ansi

- name: Run tests
run: php artisan test
env:
DB_PORT: ${{ job.services.mysql.ports[3306] }}
34 changes: 34 additions & 0 deletions app/Console/Commands/PingCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;

class PingCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:ping';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Dummy command to test Sentry monitoring';

/**
* Execute the console command.
*/
public function handle(): int
{
$this->info('Pong!');

return static::SUCCESS;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace App\Jobs;
namespace App\Console\Commands;

use App\Enum\UserRole;
use App\Models\Organisation;
Expand All @@ -11,36 +11,62 @@
use App\Notifications\ExpiringProtocol;
use App\Notifications\SummaryExpiredProtocols;
use App\Notifications\SummaryExpiringProtocols;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
use Illuminate\Support\Collection;

class ProcessProtocolsJob implements ShouldQueue
class ProcessProtocolsCommand extends Command implements Isolatable
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:protocols';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Process protocols that are about to expire';

public Collection $admins;

public function __construct()
public Collection $organisations;

/**
* Execute the console command.
*/
public function handle(): int
{
$this->loadPlatformAdmins();
$this->loadActiveOrganisations();

logger()->info(sprintf(
'ProcessProtocols: starting check on %d active organisations...',
$this->organisations->count()
));

$this->handleExpiringProtocols();
$this->handleExpiredProtocols();

logger()->info('ProcessProtocols: done!');

return static::SUCCESS;
}

private function loadPlatformAdmins(): void
{
$this->admins = User::query()
->withoutGlobalScopes()
->role(UserRole::PLATFORM_ADMIN)
->get();
}

/**
* Execute the job.
*/
public function handle(): void
private function loadActiveOrganisations(): void
{
$organisations = Organisation::query()
$this->organisations = Organisation::query()
->whereActive()
->select(['id', 'name', 'email', 'contact_person'])
->withOnly([
Expand All @@ -51,32 +77,29 @@ public function handle(): void
])
->withLastProtocolExpiresAt()
->get();

logger()->info(sprintf('ProcessProtocolsJob: starting check on %d organisations...', $organisations->count()));

$this->handleExpiringProtocols($organisations);
$this->handleExpiredProtocols($organisations);

logger()->info('ProcessProtocolsJob: done!');
}

private function handleExpiringProtocols(Collection $organisations): void
private function handleExpiringProtocols(): void
{
$checkDate = today()->addDays(30);

logger()->info(sprintf(
'ProcessProtocolsJob: checking for protocols expiring in 30 days (%s)...',
'ProcessProtocols: checking for protocols expiring in 30 days (%s)...',
$checkDate->format('Y-m-d')
));

$organisations
->filter(fn (Organisation $organisation) => $checkDate->isSameDay($organisation->last_protocol_expires_at))
$this->organisations
->filter(
fn (Organisation $organisation) => $organisation
->last_protocol_expires_at
?->isSameDay($checkDate) ?? true
)
->each(function (Organisation $organisation) {
$this->sendNotification(ExpiringProtocol::class, $organisation);
})
->tap(function (Collection $organisations) {
logger()->info(sprintf(
'ProcessProtocolsJob: found %d organisations with expiring protocols: %s',
'ProcessProtocols: found %d organisations with expiring protocols: %s',
$organisations->count(),
$organisations->pluck('id')->join(', ')
));
Expand All @@ -85,25 +108,29 @@ private function handleExpiringProtocols(Collection $organisations): void
});
}

private function handleExpiredProtocols(Collection $organisations): void
private function handleExpiredProtocols(): void
{
$checkDate = today();

logger()->info(sprintf(
'ProcessProtocolsJob: checking for protocols expiring today (%s)...',
'ProcessProtocols: checking for protocols expiring today (%s)...',
$checkDate->format('Y-m-d')
));

$organisations
->filter(fn (Organisation $organisation) => $checkDate->isSameDay($organisation->last_protocol_expires_at))
$this->organisations
->filter(
fn (Organisation $organisation) => $organisation
->last_protocol_expires_at
?->lte($checkDate) ?? true
)
->each(function (Organisation $organisation) {
$organisation->setInactive();

$this->sendNotification(ExpiredProtocol::class, $organisation);
})
->tap(function (Collection $organisations) {
logger()->info(sprintf(
'ProcessProtocolsJob: found %d organisations with expired protocols: %s',
'ProcessProtocols: found %d organisations with expired protocols: %s',
$organisations->count(),
$organisations->pluck('id')->join(', ')
));
Expand Down
12 changes: 9 additions & 3 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

namespace App\Console;

use App\Jobs\ProcessProtocolsJob;
use App\Console\Commands\PingCommand;
use App\Console\Commands\ProcessProtocolsCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

Expand All @@ -18,12 +19,17 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
$schedule->job(new ProcessProtocolsJob)
$schedule->command(ProcessProtocolsCommand::class)
->daily()
->at('06:00')
->timezone('Europe/Bucharest')
->withoutOverlapping()
->sentryMonitor('process-protocols-job');
->sentryMonitor('process-protocols');

$schedule->command(PingCommand::class)
->everyTenMinutes()
->withoutOverlapping()
->sentryMonitor('ping');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
],
"test": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --colors=always"
"test": "@php artisan test"
},
"extra": {
"laravel": {
Expand Down
2 changes: 2 additions & 0 deletions database/factories/DocumentFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Database\Factories;

use App\Enum\DocumentType;
use App\Models\Organisation;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Factories\Factory;

Expand All @@ -23,6 +24,7 @@ public function definition()
return [
'name' => fake()->sentence(),
'type' => DocumentType::other,
'organisation_id' => Organisation::factory(),
];
}

Expand Down
Loading