openstamanager/modules/newsletter/src/Newsletter.php

93 lines
2.1 KiB
PHP
Raw Normal View History

2019-08-27 17:25:52 +02:00
<?php
namespace Modules\Newsletter;
use Common\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Models\User;
use Modules\Anagrafiche\Anagrafica;
2019-08-29 10:25:14 +02:00
use Modules\Emails\Account;
use Modules\Emails\Mail;
use Modules\Emails\Template;
2019-08-28 16:58:47 +02:00
use Traits\RecordTrait;
2019-08-27 17:25:52 +02:00
class Newsletter extends Model
{
use SoftDeletes;
2019-08-28 16:58:47 +02:00
use RecordTrait;
2019-08-27 17:25:52 +02:00
2019-08-29 10:25:14 +02:00
protected $table = 'em_newsletters';
2019-08-27 17:25:52 +02:00
2019-08-29 10:25:14 +02:00
public static function build(User $user, Template $template, $name)
2019-08-27 17:25:52 +02:00
{
$model = parent::build();
$model->user()->associate($user);
$model->template()->associate($template);
$model->name = $name;
$model->subject = $template->subject;
$model->content = $template->body;
$model->state = 'DEV';
$model->save();
return $model;
}
2019-08-28 16:58:47 +02:00
/**
* Restituisce il nome del modulo a cui l'oggetto è collegato.
*
* @return string
*/
public function getModuleAttribute()
{
return 'Newsletter';
}
public function fixStato()
{
$mails = $this->emails;
$completed = true;
foreach ($mails as $mail) {
if (empty($mail->sent_at)) {
$completed = false;
break;
}
}
$this->state = $completed ? 'OK' : $this->state;
$this->completed_at = $completed ? date('Y-m-d H:i:s') : $this->completed_at;
$this->save();
}
2019-08-27 17:25:52 +02:00
// Relazione Eloquent
public function anagrafiche()
{
2019-09-24 10:09:29 +02:00
return $this->belongsToMany(Anagrafica::class, 'em_newsletter_anagrafica', 'id_newsletter', 'id_anagrafica')->withPivot('id_email')->withTrashed();
2019-08-27 17:25:52 +02:00
}
public function emails()
{
2019-08-29 15:09:01 +02:00
return $this->belongsToMany(Mail::class, 'em_newsletter_anagrafica', 'id_newsletter', 'id_email')->withPivot('id_anagrafica');
2019-08-27 17:25:52 +02:00
}
public function account()
{
2019-08-29 10:25:14 +02:00
return $this->belongsTo(Account::class, 'id_account');
2019-08-27 17:25:52 +02:00
}
public function template()
{
2019-08-29 10:25:14 +02:00
return $this->belongsTo(Template::class, 'id_template');
2019-08-27 17:25:52 +02:00
}
public function user()
{
return $this->belongsTo(User::class, 'created_by');
}
}