diff --git a/app/Console/Commands/NotifyUtilityFeeStatus.php b/app/Console/Commands/NotifyUtilityFeeStatus.php index 97ed9e2..2a29faf 100644 --- a/app/Console/Commands/NotifyUtilityFeeStatus.php +++ b/app/Console/Commands/NotifyUtilityFeeStatus.php @@ -33,20 +33,42 @@ class NotifyUtilityFeeStatus extends Command ->where('due_date', '<', now()->startOfDay()) ->update(['payment_status' => \App\Modules\Finance\Models\UtilityFee::STATUS_OVERDUE]); - // 2. 獲取需要處理的單據 (pending 或 overdue) - $unpaidFees = \App\Modules\Finance\Models\UtilityFee::whereIn('payment_status', [ + // 2. 獲取可能需要處理的單據 (pending 或 overdue) + $feesToCheck = \App\Modules\Finance\Models\UtilityFee::whereIn('payment_status', [ \App\Modules\Finance\Models\UtilityFee::STATUS_PENDING, \App\Modules\Finance\Models\UtilityFee::STATUS_OVERDUE ]) + ->whereNotNull('due_date') ->orderBy('due_date', 'asc') ->get(); - if ($unpaidFees->isEmpty()) { - $this->info("目前沒有需要繳納的公共事業費。"); + if ($feesToCheck->isEmpty()) { + $this->info("目前沒有未繳納的公共事業費。"); return 0; } - // 3. 讀取系統設定 + // 3. 根據業務規則過濾出今天「真正」需要發信的單據 + $today = now()->startOfDay(); + $unpaidFees = $feesToCheck->filter(function ($fee) use ($today) { + $dueDate = \Illuminate\Support\Carbon::parse($fee->due_date)->startOfDay(); + $diffInDays = $today->diffInDays($dueDate, false); + + // 如果已經逾期 (overdue),每天都要發信 + if ($fee->payment_status === \App\Modules\Finance\Models\UtilityFee::STATUS_OVERDUE) { + return true; + } + + // 如果是待繳納 (pending),僅在特定天數發信 + // 規則:到期前 7 天、3 天、當天 (0 天) + return in_array($diffInDays, [7, 3, 0]); + }); + + if ($unpaidFees->isEmpty()) { + $this->info("今日無符合發信條件的公共事業費提醒。"); + return 0; + } + + // 4. 讀取系統設定 $senderEmail = \App\Modules\Core\Models\SystemSetting::getVal('notification.utility_fee_sender_email'); $senderPassword = \App\Modules\Core\Models\SystemSetting::getVal('notification.utility_fee_sender_password'); $recipientEmailsStr = \App\Modules\Core\Models\SystemSetting::getVal('notification.utility_fee_recipient_emails');