setName('appmall:license-notify') ->setDescription('扫描即将到期/即将结束试用的插件授权并发送提醒邮件') ->addOption('days', null, Option::VALUE_OPTIONAL, '提醒窗口天数', 7) ->addOption('dry-run', null, Option::VALUE_NONE, '只列出不发邮件') ->addOption('no-mail', null, Option::VALUE_NONE, '不发送邮件,仅输出与记日志'); } protected function execute(Input $input, Output $output): int { // 先自愈表结构(新增的 trial_end / period / max_major 等列在老库可能还没有) \app\appmall\library\AppmallSchema::ensure(); $days = (int) $input->getOption('days'); $days = $days > 0 ? $days : 7; $rows = LicensePolicy::expiring($days); if (empty($rows)) { $output->info(sprintf('未来 %d 天内没有到期的授权或试用。', $days)); return 0; } $dry = (bool) $input->getOption('dry-run'); $noMail = (bool) $input->getOption('no-mail'); $sent = 0; foreach ($rows as $r) { $isTrial = ($r['kind'] ?? '') === 'trial'; $line = sprintf( '%-6s %-22s %-10s %s %s(剩 %d 天)', $isTrial ? '试用到期' : '授权到期', (string) ($r['name'] ?? ''), (string) ($r['version'] ?? ''), date('Y-m-d', (int) ($r['end_time'] ?? 0)), (string) ($r['title'] ?? ''), (int) ($r['left_days'] ?? 0) ); $output->writeln(($r['expired'] ? '[已过期] ' : ' ') . $line); if ($dry || $noMail) { continue; } if ($this->notify((int) ($r['uid'] ?? 0), $r)) { $sent++; } } Log::info('appmall.license.notify', [ 'days' => $days, 'matched' => count($rows), 'sent' => $sent, 'dry' => $dry, ]); $output->info(sprintf( '扫描完成:%d 条待提醒%s', count($rows), $dry ? '(dry-run,未发信)' : sprintf(',已发送 %d 封', $sent) )); return 0; } /** * 给会员发一封到期/试用结束提醒 * * @param array $row LicensePolicy::expiring() 的一行 */ private function notify(int $uid, array $row): bool { if ($uid <= 0) { return false; } $email = $this->userEmail($uid); if ($email === '') { return false; } $isTrial = ($row['kind'] ?? '') === 'trial'; $end = date('Y-m-d', (int) ($row['end_time'] ?? 0)); $subject = $isTrial ? sprintf('【试用即将结束】%s 将于 %s 到期', (string) ($row['title'] ?? '插件'), $end) : sprintf('【授权即将到期】%s 将于 %s 到期', (string) ($row['title'] ?? '插件'), $end); $tip = $isTrial ? '试用结束后该插件将无法继续使用,请在应用市场购买后继续。' : '到期后将无法安装/升级该插件,续费后立即恢复。'; $body = sprintf( "您好:\n\n您在应用市场的插件「%s」(%s)%s于 %s %s。\n%s\n\n—— %s", (string) ($row['title'] ?? ''), (string) ($row['name'] ?? ''), (int) ($row['left_days'] ?? 0) > 0 ? '将' : '已', $end, $isTrial ? '结束试用' : '到期', $tip, (string) config('app.name', 'YwxApp 应用市场') ); try { Mailer::send($email, $subject, nl2br($body)); return true; } catch (\Throwable $e) { Log::warning('到期提醒邮件发送失败:' . $e->getMessage()); return false; } } /** * 取会员邮箱(用户表在不同部署下名字可能是 user/users/member,逐一探测;都取不到就跳过) */ private function userEmail(int $uid): string { foreach (['user', 'users', 'member'] as $table) { try { $row = Db::name($table)->where('id', $uid)->find(); } catch (\Throwable $e) { continue; } if (!empty($row['email'])) { return (string) $row['email']; } } return ''; } }