clrghouz/app/Models/Echoarea.php
2022-01-15 14:58:41 +11:00

79 lines
1.7 KiB
PHP

<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use App\Traits\ScopeActive;
class Echoarea extends Model
{
use SoftDeletes,ScopeActive;
private const CACHE_TIME = 3600;
/* RELATIONS */
public function addresses()
{
return $this->belongsToMany(Address::class);
}
public function domain()
{
return $this->belongsTo(Domain::class);
}
public function echomail()
{
return $this->hasMany(Echomail::class)
->orderBy('datetime','ASC');
}
/* ATTRIBUTES */
public function getLastMessageAttribute(): ?Carbon
{
return $this->echomail?->last()->datetime;
}
/* METHODS */
public function messages_count(int $period): int
{
$key = sprintf('%s_%d_%d','echo_messages_count',$this->id,$period);
return Cache::remember($key,self::CACHE_TIME,function() use ($period) {
switch ($period) {
case 1: // day
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subDay())->count();
case 7: // week
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subWeek())->count();
case 30: // month
return $this->echomail()->where('datetime','>=',Carbon::now()->startOfday()->subMonth())->count();
default:
return 0;
}
});
}
/**
* Number of messages waiting for address
*
* @param Address $ao
* @return Collection
*/
public function waiting(Address $ao): Collection
{
return $this->echomail()
->join('echomail_seenby',['echomail_seenby.echomail_id'=>'echomails.id'])
->whereNull('sent_at')
->whereNotNull('export_at')
->where('address_id',$ao->id)
->get();
}
}