Skip to content

Commit

Permalink
refactor: process protocols
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiio committed Jan 19, 2024
1 parent affa9f3 commit c66d1ab
Show file tree
Hide file tree
Showing 7 changed files with 349 additions and 63 deletions.
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] }}
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
6 changes: 3 additions & 3 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace App\Console;

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

Expand All @@ -18,12 +18,12 @@ 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');
}

/**
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
4 changes: 2 additions & 2 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="DB_CONNECTION" value="mysql"/>
<server name="DB_DATABASE" value="tests"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
Expand Down
23 changes: 0 additions & 23 deletions tests/Feature/ExampleTest.php

This file was deleted.

Loading

0 comments on commit c66d1ab

Please sign in to comment.