| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\DB;
- class SmsMessage extends Model
- {
- protected $fillable = [
- 'subject',
- 'content',
- 'status',
- 'schedule_at',
- 'sent_at',
- 'created_by'
- ];
- protected $casts = [
- 'schedule_at' => 'datetime',
- 'sent_at' => 'datetime',
- ];
- public function recipients()
- {
- return $this->hasMany(SmsMessageRecipient::class);
- }
- public function creator()
- {
- return $this->belongsTo(User::class, 'created_by');
- }
- public function duplicate(bool $withRecipients = false)
- {
- return DB::transaction(function () use ($withRecipients) {
- $copy = $this->replicate(['status', 'schedule_at', 'sent_at']);
- $copy->status = 'draft';
- $copy->schedule_at = null;
- $copy->sent_at = null;
- $copy->save();
- foreach ($this->attachments as $a) {
- $copy->attachments()->create($a->only(['disk', 'path', 'name', 'size']));
- }
- if ($withRecipients) {
- $payload = $this->recipients()
- ->get(['member_id', 'phone'])
- ->map(fn($r) => [
- 'member_id' => $r->member_id,
- 'phone' => $r->phone,
- 'status' => 'pending',
- ])
- ->all();
- if ($payload) {
- $copy->recipients()->createMany($payload);
- }
- }
- return $copy;
- });
- }
- public function isLocked(): bool
- {
- return in_array($this->status, ['processing', 'sent']);
- }
- }
|