SmsMessage.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\DB;
  5. class SmsMessage extends Model
  6. {
  7. protected $fillable = [
  8. 'subject',
  9. 'content',
  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(SmsMessageRecipient::class);
  22. }
  23. public function creator()
  24. {
  25. return $this->belongsTo(User::class, 'created_by');
  26. }
  27. public function duplicate(bool $withRecipients = false)
  28. {
  29. return DB::transaction(function () use ($withRecipients) {
  30. $copy = $this->replicate(['status', 'schedule_at', 'sent_at']);
  31. $copy->status = 'draft';
  32. $copy->schedule_at = null;
  33. $copy->sent_at = null;
  34. $copy->save();
  35. foreach ($this->attachments as $a) {
  36. $copy->attachments()->create($a->only(['disk', 'path', 'name', 'size']));
  37. }
  38. if ($withRecipients) {
  39. $payload = $this->recipients()
  40. ->get(['member_id', 'phone'])
  41. ->map(fn($r) => [
  42. 'member_id' => $r->member_id,
  43. 'phone' => $r->phone,
  44. 'status' => 'pending',
  45. ])
  46. ->all();
  47. if ($payload) {
  48. $copy->recipients()->createMany($payload);
  49. }
  50. }
  51. return $copy;
  52. });
  53. }
  54. public function isLocked(): bool
  55. {
  56. return in_array($this->status, ['processing', 'sent']);
  57. }
  58. }