akaunting/app/Console/Commands/ReportCache.php

84 lines
2.0 KiB
PHP
Raw Normal View History

2021-06-15 10:33:36 +03:00
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Models\Common\Report;
use App\Utilities\Reports as Utility;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
2021-06-17 14:36:54 +03:00
class ReportCache extends Command
2021-06-15 10:33:36 +03:00
{
/**
* The name and signature of the console command.
*
* @var string
*/
2021-06-17 14:36:54 +03:00
protected $signature = 'report:cache';
2021-06-15 10:33:36 +03:00
/**
* The console command description.
*
* @var string
*/
2021-06-17 14:36:54 +03:00
protected $description = 'Calculate and cache reports';
2021-06-15 10:33:36 +03:00
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Disable model cache
config(['laravel-model-caching.enabled' => false]);
// Get all companies
$companies = Company::enabled()->withCount('reports')->cursor();
foreach ($companies as $company) {
// Has company reports
if (!$company->reports_count) {
continue;
}
2021-06-17 14:36:54 +03:00
$this->info('Calculating reports for ' . $company->name . ' company.');
2021-06-15 10:33:36 +03:00
// Set company
$company->makeCurrent();
2021-06-17 14:36:54 +03:00
$this->cacheReportsOfCurrentCompany();
2021-06-15 10:33:36 +03:00
}
Company::forgetCurrent();
}
2021-06-17 14:36:54 +03:00
protected function cacheReportsOfCurrentCompany()
2021-06-15 10:33:36 +03:00
{
$reports = Report::orderBy('name')->get();
foreach ($reports as $report) {
2021-06-22 11:31:42 +03:00
try {
$class = Utility::getClassInstance($report, false);
2021-06-15 10:33:36 +03:00
2021-06-22 11:31:42 +03:00
if (empty($class)) {
continue;
}
2021-06-15 10:33:36 +03:00
2021-06-22 11:31:42 +03:00
$ttl = 3600 * 6; // 6 hours
2021-06-15 10:33:36 +03:00
2021-06-22 11:31:42 +03:00
Cache::forget('reports.totals.' . $report->id);
2021-06-15 12:37:13 +03:00
2021-06-22 11:31:42 +03:00
Cache::remember('reports.totals.' . $report->id, $ttl, function () use ($class) {
return $class->getGrandTotal();
});
} catch (\Throwable $e) {
$this->error($e->getMessage());
report($e);
}
2021-06-15 10:33:36 +03:00
}
}
}