Emailbroadcast.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. namespace app\admin\controller;
  3. use app\admin\model\general\Lang as LangModel;
  4. use app\common\controller\Backend;
  5. use app\common\model\EmailBroadcast as EmailBroadcastModel;
  6. use app\common\model\EmailBroadcastItem as EmailBroadcastItemModel;
  7. use app\common\model\EmailSubscribe as EmailSubscribeModel;
  8. use app\common\model\EmailSubscribeLog as EmailSubscribeLogModel;
  9. use app\common\model\EmailTemplate as EmailTemplateModel;
  10. use think\facade\Db;
  11. use think\facade\Validate;
  12. class Emailbroadcast extends Backend
  13. {
  14. protected $modelClass = null;
  15. protected $modelValidate = false;
  16. protected function initialize()
  17. {
  18. parent::initialize();
  19. $this->modelClass = new EmailBroadcastModel();
  20. $this->assign('statusList', $this->modelClass->getStatusList());
  21. $this->assign('itemStatusList', (new EmailBroadcastItemModel())->getStatusList());
  22. $this->assign('langList', LangModel::getEnabledList());
  23. $this->assign('defaultLang', LangModel::getDefaultMark());
  24. $this->assign('templateList', EmailTemplateModel::where(['type' => 'marketing_broadcast', 'status' => 1])
  25. ->order('listorder', 'asc')
  26. ->order('id', 'asc')
  27. ->select());
  28. if (in_array(strtolower($this->request->action()), ['add', 'edit', 'items'], true)) {
  29. $config = $this->view->config ?: [];
  30. $config['jsname'] = 'backend/emailbroadcast/' . strtolower($this->request->action());
  31. $this->view->config = $config;
  32. $this->assign('config', $config);
  33. }
  34. }
  35. public function index()
  36. {
  37. if ($this->request->isAjax()) {
  38. $page = (int)$this->request->param('page/d', 1);
  39. $limit = (int)$this->request->param('limit/d', 20);
  40. $sort = (string)$this->request->param('sort/s', 'id');
  41. $order = (string)$this->request->param('order/s', 'desc');
  42. $name = trim((string)$this->request->param('name/s', ''));
  43. $lang = trim((string)$this->request->param('lang/s', ''));
  44. $status = $this->request->param('status/s', '');
  45. $templateId = (int)$this->request->param('template_id/d', 0);
  46. $query = $this->modelClass;
  47. if ($name !== '') {
  48. $query = $query->whereLike('name|subject', '%' . $name . '%');
  49. }
  50. if ($lang !== '') {
  51. $query = $query->where('lang', strtolower($lang));
  52. }
  53. if ($status !== '') {
  54. $query = $query->where('status', (int)$status);
  55. }
  56. if ($templateId > 0) {
  57. $query = $query->where('template_id', $templateId);
  58. }
  59. $count = $query->count();
  60. $data = $query->order($sort, $order)->page($page, $limit)->select();
  61. foreach ($data as $row) {
  62. $row->status_text = $this->modelClass->getStatusList()[(int)$row->status] ?? $row->status;
  63. }
  64. return json(['code' => 0, 'count' => $count, 'data' => $data]);
  65. }
  66. return $this->fetch();
  67. }
  68. public function add()
  69. {
  70. if ($this->request->isPost()) {
  71. $this->token();
  72. $params = $this->buildBroadcastParams();
  73. $recipientRows = $this->getSubscribersForBroadcast($params);
  74. if (empty($recipientRows)) {
  75. $this->error('未筛选到可发送的订阅用户');
  76. }
  77. Db::startTrans();
  78. try {
  79. $now = time();
  80. $params['recipient_count'] = count($recipientRows);
  81. $params['success_count'] = 0;
  82. $params['fail_count'] = 0;
  83. $params['status'] = 0;
  84. $params['createtime'] = $now;
  85. $params['updatetime'] = $now;
  86. $this->modelClass->save($params);
  87. $items = [];
  88. foreach ($recipientRows as $recipient) {
  89. $items[] = [
  90. 'broadcast_id' => $this->modelClass->id,
  91. 'subscribe_id' => (int)$recipient['id'],
  92. 'email' => (string)$recipient['email'],
  93. 'lang' => (string)$recipient['lang'],
  94. 'status' => 0,
  95. 'response_code' => '',
  96. 'response_msg' => '待发送',
  97. 'retry_count' => 0,
  98. 'send_time' => 0,
  99. 'createtime' => $now,
  100. 'updatetime' => $now,
  101. ];
  102. }
  103. (new EmailBroadcastItemModel())->saveAll($items);
  104. Db::commit();
  105. } catch (\Throwable $e) {
  106. Db::rollback();
  107. $this->error('创建群发任务失败:' . $e->getMessage());
  108. }
  109. $this->success('群发任务创建成功', url('Emailbroadcast/index'));
  110. }
  111. return $this->fetch();
  112. }
  113. public function edit()
  114. {
  115. $id = (int)$this->request->param('id/d', 0);
  116. $row = $this->modelClass->find($id);
  117. if (!$row) {
  118. $this->error('群发任务不存在');
  119. }
  120. if ($this->request->isPost()) {
  121. $this->token();
  122. if ((int)$row->status !== 0) {
  123. $this->error('仅待发送任务支持编辑');
  124. }
  125. $params = $this->buildBroadcastParams();
  126. $recipientRows = $this->getSubscribersForBroadcast($params);
  127. if (empty($recipientRows)) {
  128. $this->error('未筛选到可发送的订阅用户');
  129. }
  130. Db::startTrans();
  131. try {
  132. $now = time();
  133. $params['recipient_count'] = count($recipientRows);
  134. $params['success_count'] = 0;
  135. $params['fail_count'] = 0;
  136. $params['status'] = 0;
  137. $params['updatetime'] = $now;
  138. $row->save($params);
  139. Db::name('email_broadcast_item')->where('broadcast_id', $row->id)->delete();
  140. $items = [];
  141. foreach ($recipientRows as $recipient) {
  142. $items[] = [
  143. 'broadcast_id' => $row->id,
  144. 'subscribe_id' => (int)$recipient['id'],
  145. 'email' => (string)$recipient['email'],
  146. 'lang' => (string)$recipient['lang'],
  147. 'status' => 0,
  148. 'response_code' => '',
  149. 'response_msg' => '待发送',
  150. 'retry_count' => 0,
  151. 'send_time' => 0,
  152. 'createtime' => $now,
  153. 'updatetime' => $now,
  154. ];
  155. }
  156. (new EmailBroadcastItemModel())->saveAll($items);
  157. Db::commit();
  158. } catch (\Throwable $e) {
  159. Db::rollback();
  160. $this->error('编辑群发任务失败:' . $e->getMessage());
  161. }
  162. $this->success('群发任务更新成功', url('Emailbroadcast/index'));
  163. }
  164. $this->assign('data', $row);
  165. return $this->fetch();
  166. }
  167. public function items()
  168. {
  169. $id = (int)$this->request->param('id/d', 0);
  170. $broadcast = $this->modelClass->find($id);
  171. if (!$broadcast) {
  172. $this->error('群发任务不存在');
  173. }
  174. if ($this->request->isAjax()) {
  175. $page = (int)$this->request->param('page/d', 1);
  176. $limit = (int)$this->request->param('limit/d', 20);
  177. $sort = (string)$this->request->param('sort/s', 'id');
  178. $order = (string)$this->request->param('order/s', 'desc');
  179. $email = trim((string)$this->request->param('email/s', ''));
  180. $status = $this->request->param('status/s', '');
  181. $query = new EmailBroadcastItemModel();
  182. $query = $query->where('broadcast_id', $id);
  183. if ($email !== '') {
  184. $query = $query->where('email', 'like', '%' . $email . '%');
  185. }
  186. if ($status !== '') {
  187. $query = $query->where('status', (int)$status);
  188. }
  189. $count = $query->count();
  190. $data = $query->order($sort, $order)->page($page, $limit)->select();
  191. return json(['code' => 0, 'count' => $count, 'data' => $data]);
  192. }
  193. $this->assign('broadcast', $broadcast);
  194. return $this->fetch();
  195. }
  196. public function send()
  197. {
  198. if (!$this->request->isPost()) {
  199. $this->error('请求方式错误');
  200. }
  201. $id = (int)$this->request->post('id/d', 0);
  202. $batchSize = (int)$this->request->post('batch_size/d', 0);
  203. $batchSize = $batchSize > 0 ? min($batchSize, 500) : 100;
  204. $row = $this->modelClass->find($id);
  205. if (!$row) {
  206. $this->error('群发任务不存在');
  207. }
  208. if (!in_array((int)$row->status, [0, 3, 4], true)) {
  209. $this->error('当前状态不允许发送');
  210. }
  211. $template = EmailTemplateModel::where('id', (int)$row->template_id)->find();
  212. if (!$template || (int)$template->status !== 1) {
  213. $this->error('关联模板不存在或已禁用');
  214. }
  215. $now = time();
  216. $row->status = 1;
  217. if ((int)$row->start_time <= 0) {
  218. $row->start_time = $now;
  219. }
  220. $row->updatetime = $now;
  221. $row->save();
  222. $items = EmailBroadcastItemModel::where('broadcast_id', $row->id)
  223. ->where('status', 'in', [0, 2])
  224. ->order('id', 'asc')
  225. ->limit($batchSize)
  226. ->select();
  227. if ($items->isEmpty()) {
  228. $this->error('没有可发送的明细记录');
  229. }
  230. $success = 0;
  231. $fail = 0;
  232. $processed = 0;
  233. foreach ($items as $item) {
  234. $subscribe = EmailSubscribeModel::where('id', (int)$item->subscribe_id)->find();
  235. $context = $this->buildMailContext([
  236. 'email' => (string)$item->email,
  237. 'lang' => (string)$item->lang,
  238. 'broadcast_name' => (string)$row->name,
  239. 'broadcast_id' => (string)$row->id,
  240. 'template_name' => (string)$template->name,
  241. 'unsubscribe_url' => $subscribe && (string)$subscribe->unsubscribe_token !== ''
  242. ? url('index/emailsubscribe/unsubscribe', ['token' => (string)$subscribe->unsubscribe_token], true, true)
  243. : '',
  244. ]);
  245. $subject = $this->renderTemplateContent((string)$template->subject, $context);
  246. $content = $this->renderTemplateContent((string)$template->content, $context);
  247. [$sendResult, $responseCode, $responseMsg] = $this->sendEmail((string)$item->email, $subject, $content);
  248. $sendTime = $sendResult ? time() : 0;
  249. $item->status = $sendResult ? 1 : 2;
  250. $item->response_code = $responseCode;
  251. $item->response_msg = $responseMsg ?: ($sendResult ? '发送成功' : '发送失败');
  252. $item->retry_count = (int)$item->retry_count + ($sendResult ? 0 : 1);
  253. $item->send_time = $sendTime;
  254. $item->updatetime = time();
  255. $item->save();
  256. if ($subscribe) {
  257. $subscribe->last_send_status = $sendResult ? 1 : 2;
  258. if ($sendResult) {
  259. $subscribe->last_send_time = $sendTime;
  260. }
  261. $subscribe->updatetime = time();
  262. $subscribe->save();
  263. }
  264. EmailSubscribeLogModel::create([
  265. 'subscribe_id' => (int)$item->subscribe_id,
  266. 'email' => (string)$item->email,
  267. 'mail_type' => 'marketing_broadcast',
  268. 'subject' => $subject,
  269. 'content' => $content,
  270. 'status' => $sendResult ? 1 : 2,
  271. 'response_code' => $responseCode,
  272. 'response_msg' => $responseMsg ?: ($sendResult ? '营销群发发送成功' : '营销群发发送失败'),
  273. 'retry_count' => $sendResult ? 0 : 1,
  274. 'send_time' => $sendTime,
  275. 'createtime' => time(),
  276. 'updatetime' => time(),
  277. ]);
  278. $sendResult ? $success++ : $fail++;
  279. $processed++;
  280. }
  281. $row->success_count = (int)$row->success_count + $success;
  282. $row->fail_count = (int)$row->fail_count + $fail;
  283. $pendingCount = EmailBroadcastItemModel::where('broadcast_id', $row->id)
  284. ->where('status', 0)
  285. ->count();
  286. $failedCount = EmailBroadcastItemModel::where('broadcast_id', $row->id)
  287. ->where('status', 2)
  288. ->count();
  289. if ($pendingCount > 0) {
  290. $row->status = $row->fail_count > 0 ? 3 : 1;
  291. $row->finish_time = 0;
  292. $message = '本次发送 ' . $processed . ' 条,任务未完成,仍有 ' . $pendingCount . ' 条待发送';
  293. } else {
  294. $row->status = $failedCount > 0 ? ($row->success_count > 0 ? 3 : 4) : 2;
  295. $row->finish_time = time();
  296. $message = $failedCount > 0 ? '群发执行完成,存在失败记录' : '群发执行完成';
  297. }
  298. $row->updatetime = time();
  299. $row->save();
  300. $this->success($message, null, [
  301. 'processed' => $processed,
  302. 'success' => $success,
  303. 'fail' => $fail,
  304. 'pending' => $pendingCount,
  305. 'batch_size' => $batchSize,
  306. ]);
  307. }
  308. public function del()
  309. {
  310. if (!$this->request->isPost()) {
  311. $this->error('请求方式错误');
  312. }
  313. $ids = $this->request->post('ids/a', []);
  314. if (!$ids) {
  315. $this->error('请先选择群发任务');
  316. }
  317. Db::startTrans();
  318. try {
  319. Db::name('email_broadcast_item')->where('broadcast_id', 'in', $ids)->delete();
  320. $this->modelClass->where('id', 'in', $ids)->delete();
  321. Db::commit();
  322. } catch (\Throwable $e) {
  323. Db::rollback();
  324. $this->error('删除失败:' . $e->getMessage());
  325. }
  326. $this->success('删除成功');
  327. }
  328. protected function buildBroadcastParams(): array
  329. {
  330. $row = $this->request->post('row/a', [], 'trim');
  331. $lang = strtolower((string)($row['lang'] ?? LangModel::getDefaultMark()));
  332. $templateId = (int)($row['template_id'] ?? 0);
  333. $template = EmailTemplateModel::where('id', $templateId)->find();
  334. if (!$template) {
  335. $this->error('请选择有效的邮件模板');
  336. }
  337. if ((string)$template->type !== 'marketing_broadcast') {
  338. $this->error('仅支持选择营销群发邮件模板');
  339. }
  340. if ((int)$template->status !== 1) {
  341. $this->error('所选模板已禁用');
  342. }
  343. $statusFilter = array_values(array_unique(array_map('intval', (array)($row['status_filter'] ?? [1]))));
  344. $statusFilter = array_values(array_intersect($statusFilter, [0, 1, 9]));
  345. $allowUserUnsubscribed = !empty($row['allow_user_unsubscribed']);
  346. if (!$allowUserUnsubscribed) {
  347. $statusFilter = array_values(array_diff($statusFilter, [9]));
  348. }
  349. if (empty($statusFilter)) {
  350. $statusFilter = [1];
  351. }
  352. $confirmFilter = array_values(array_unique(array_map('intval', (array)($row['confirm_status_filter'] ?? [0, 1]))));
  353. $confirmFilter = array_values(array_intersect($confirmFilter, [0, 1]));
  354. if (empty($confirmFilter)) {
  355. $confirmFilter = [0, 1];
  356. }
  357. $lastSendFilter = array_values(array_unique(array_map('intval', (array)($row['last_send_status_filter'] ?? [0, 1, 2]))));
  358. $lastSendFilter = array_values(array_intersect($lastSendFilter, [0, 1, 2]));
  359. if (empty($lastSendFilter)) {
  360. $lastSendFilter = [0, 1, 2];
  361. }
  362. return [
  363. 'name' => (string)($row['name'] ?? ''),
  364. 'template_id' => $templateId,
  365. 'template_name' => (string)$template->name,
  366. 'lang' => $lang,
  367. 'subject' => (string)$template->subject,
  368. 'content' => (string)$template->content,
  369. 'remark' => (string)($row['remark'] ?? ''),
  370. 'source_key' => (string)($row['source_key'] ?? ''),
  371. 'status_filter' => implode(',', $statusFilter),
  372. 'confirm_status_filter' => implode(',', $confirmFilter),
  373. 'last_send_status_filter' => implode(',', $lastSendFilter),
  374. 'exclude_sent' => empty($row['exclude_sent']) ? 0 : 1,
  375. 'allow_user_unsubscribed' => $allowUserUnsubscribed ? 1 : 0,
  376. ];
  377. }
  378. protected function getSubscribersForBroadcast(array $params): array
  379. {
  380. $query = EmailSubscribeModel::where('lang', $params['lang'])
  381. ->whereIn('status', explode(',', $params['status_filter']))
  382. ->whereIn('confirm_status', explode(',', $params['confirm_status_filter']))
  383. ->whereIn('last_send_status', explode(',', $params['last_send_status_filter']));
  384. if ($params['source_key'] !== '') {
  385. $query = $query->where('source_key', $params['source_key']);
  386. }
  387. if (!empty($params['exclude_sent'])) {
  388. $query = $query->whereNotIn('id', function ($subQuery) {
  389. $subQuery->name('email_subscribe_log')->where('mail_type', 'marketing_broadcast')->field('subscribe_id');
  390. });
  391. }
  392. return $query->order('id', 'asc')->select()->toArray();
  393. }
  394. protected function sendEmail(string $email, string $subject, string $content): array
  395. {
  396. try {
  397. $config = get_addon_config('phpmailer');
  398. if (!$config) {
  399. return [false, 'NO_CONFIG', '未找到 phpmailer 插件配置'];
  400. }
  401. $mailer = new \addons\phpmailer\library\Mailer($config);
  402. $result = $mailer->to($email)->subject($subject)->message($content, true)->send();
  403. if ($result) {
  404. return [true, 'SUCCESS', '邮件发送成功'];
  405. }
  406. return [false, 'FAIL', $mailer->getError() ?: '邮件发送失败'];
  407. } catch (\Throwable $e) {
  408. return [false, 'EXCEPTION', $e->getMessage()];
  409. }
  410. }
  411. protected function buildMailContext(array $data): array
  412. {
  413. $context = [];
  414. foreach ($data as $key => $value) {
  415. $context[$key] = is_scalar($value) || $value === null ? (string)$value : json_encode($value, JSON_UNESCAPED_UNICODE);
  416. }
  417. return $context;
  418. }
  419. protected function renderTemplateContent(string $content, array $context): string
  420. {
  421. $replace = [];
  422. foreach ($context as $key => $value) {
  423. $replace['{{' . $key . '}}'] = (string)$value;
  424. $replace['{{ ' . $key . ' }}'] = (string)$value;
  425. }
  426. return strtr($content, $replace);
  427. }
  428. }