EmailMessage.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\DB;
  5. class EmailMessage extends Model
  6. {
  7. protected $fillable = [
  8. 'subject',
  9. 'content_html',
  10. 'status',
  11. 'schedule_at',
  12. 'sent_at',
  13. 'created_by'
  14. ];
  15. protected $casts = [
  16. 'schedule_at' => 'datetime',
  17. 'sent_at' => 'datetime',
  18. ];
  19. public function recipients()
  20. {
  21. return $this->hasMany(EmailMessageRecipient::class);
  22. }
  23. public function attachments()
  24. {
  25. return $this->hasMany(EmailMessageAttachment::class);
  26. }
  27. public function creator()
  28. {
  29. return $this->belongsTo(User::class, 'created_by');
  30. }
  31. public function duplicate(bool $withRecipients = false)
  32. {
  33. return DB::transaction(function () use ($withRecipients) {
  34. $copy = $this->replicate(['status', 'schedule_at', 'sent_at']);
  35. $copy->status = 'draft';
  36. $copy->schedule_at = null;
  37. $copy->sent_at = null;
  38. $copy->save();
  39. foreach ($this->attachments as $a) {
  40. $copy->attachments()->create($a->only(['disk', 'path', 'name', 'size']));
  41. }
  42. if ($withRecipients) {
  43. $payload = $this->recipients()
  44. ->get(['member_id', 'email_address'])
  45. ->map(fn($r) => [
  46. 'member_id' => $r->member_id,
  47. 'email_address' => $r->email_address,
  48. 'status' => 'pending',
  49. ])
  50. ->all();
  51. if ($payload) {
  52. $copy->recipients()->createMany($payload);
  53. }
  54. }
  55. return $copy;
  56. });
  57. }
  58. public function isLocked(): bool
  59. {
  60. return in_array($this->status, ['processing', 'sent']);
  61. }
  62. }