Purchasecontent.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use think\Cache;
  5. use think\Db;
  6. use think\exception\PDOException;
  7. use think\exception\ValidateException;
  8. use Exception;
  9. /**
  10. * 协助采购 — 通知公告
  11. *
  12. * @icon fa fa-bullhorn
  13. */
  14. class Purchasecontent extends Backend
  15. {
  16. /** 投递接收人可选范围:auth_group 根组 id(含其全部子组) */
  17. protected const RECIPIENT_AUTH_GROUP_ROOT_ID = 10;
  18. /** 表结构已就绪缓存键(避免每次请求重复 SHOW COLUMNS / 探表) */
  19. protected const SCHEMA_CACHE_KEY = 'purchase_content_schema_v3';
  20. /** 可选接收人列表缓存秒数 */
  21. protected const RECIPIENT_LIST_CACHE_TTL = 300;
  22. /** @var \app\admin\model\Purchasecontent */
  23. protected $model = null;
  24. protected $searchFields = 'subject,content';
  25. protected $noNeedRight = ['adminselect', 'install'];
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->model = new \app\admin\model\Purchasecontent;
  30. if (!Cache::get(self::SCHEMA_CACHE_KEY)) {
  31. $this->ensurePurchaseContentSchemaOnce();
  32. }
  33. }
  34. /**
  35. * 首次访问时建表/迁移;仅当两表均存在才写缓存,避免建表失败后永久跳过。
  36. */
  37. protected function ensurePurchaseContentSchemaOnce(): void
  38. {
  39. $this->ensurePurchaseContentTables();
  40. if ($this->purchaseContentTablesReady()) {
  41. $this->ensurePurchaseContentDatetimeColumns();
  42. Cache::set(self::SCHEMA_CACHE_KEY, 1, 86400);
  43. }
  44. }
  45. protected function purchaseContentTablesReady(): bool
  46. {
  47. try {
  48. Db::query('SELECT 1 FROM `purchase_content` LIMIT 1');
  49. Db::query('SELECT 1 FROM `purchase_content_recipient` LIMIT 1');
  50. return true;
  51. } catch (\Throwable $e) {
  52. return false;
  53. }
  54. }
  55. protected function ensurePurchaseContentTables(): void
  56. {
  57. if ($this->purchaseContentTablesReady()) {
  58. return;
  59. }
  60. // 内联建表(不依赖 sql 文件拆分),与 ProcuremenSchema 一致
  61. try {
  62. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_content` (
  63. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  64. `creator_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '创建人',
  65. `sender_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '投递人',
  66. `subject` varchar(255) NOT NULL DEFAULT '' COMMENT '主题',
  67. `content` mediumtext COMMENT '内容',
  68. `createtime` datetime DEFAULT NULL COMMENT '投递时间',
  69. `updatetime` datetime DEFAULT NULL COMMENT '更新时间',
  70. PRIMARY KEY (`id`),
  71. KEY `idx_creator` (`creator_id`),
  72. KEY `idx_sender` (`sender_id`),
  73. KEY `idx_ct` (`createtime`)
  74. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购通知公告'");
  75. } catch (\Throwable $e) {
  76. }
  77. try {
  78. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_content_recipient` (
  79. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  80. `content_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '公告ID',
  81. `admin_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '接收人',
  82. `read_time` datetime DEFAULT NULL COMMENT '首次阅读时间',
  83. `createtime` datetime DEFAULT NULL COMMENT '创建时间',
  84. PRIMARY KEY (`id`),
  85. UNIQUE KEY `uk_content_admin` (`content_id`,`admin_id`),
  86. KEY `idx_admin` (`admin_id`)
  87. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='通知公告接收人'");
  88. } catch (\Throwable $e) {
  89. }
  90. }
  91. /** 旧版 int 时间戳列迁移为 datetime */
  92. protected function ensurePurchaseContentDatetimeColumns(): void
  93. {
  94. try {
  95. $this->migrateTableDatetimeColumn('purchase_content', 'createtime', '投递时间');
  96. $this->migrateTableDatetimeColumn('purchase_content', 'updatetime', '更新时间');
  97. $this->migrateTableDatetimeColumn('purchase_content_recipient', 'createtime', '创建时间');
  98. $this->migrateTableDatetimeColumn('purchase_content_recipient', 'read_time', '首次阅读时间');
  99. } catch (\Throwable $e) {
  100. }
  101. }
  102. protected function migrateTableDatetimeColumn(string $table, string $column, string $comment): void
  103. {
  104. $rows = Db::query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
  105. if (!is_array($rows) || !isset($rows[0]['Type'])) {
  106. return;
  107. }
  108. $type = strtolower((string)$rows[0]['Type']);
  109. if (strpos($type, 'int') === false) {
  110. return;
  111. }
  112. $tmp = $column . '_dt';
  113. Db::execute("ALTER TABLE `{$table}` ADD COLUMN `{$tmp}` datetime DEFAULT NULL COMMENT '{$comment}'");
  114. Db::execute("UPDATE `{$table}` SET `{$tmp}` = IF(`{$column}` > 0, FROM_UNIXTIME(`{$column}`), NULL)");
  115. Db::execute("ALTER TABLE `{$table}` DROP COLUMN `{$column}`");
  116. Db::execute("ALTER TABLE `{$table}` CHANGE `{$tmp}` `{$column}` datetime DEFAULT NULL COMMENT '{$comment}'");
  117. }
  118. /**
  119. * 投递/阅读时间展示:YYYY-MM-DD HH:mm:ss
  120. *
  121. * @param mixed $value
  122. */
  123. protected function formatPurchaseContentTime($value): string
  124. {
  125. if ($value === null || $value === '') {
  126. return '';
  127. }
  128. if (is_numeric($value)) {
  129. $ts = (int)$value;
  130. if ($ts > 946684800) {
  131. return date('Y-m-d H:i:s', $ts);
  132. }
  133. return '';
  134. }
  135. $s = trim((string)$value);
  136. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  137. return '';
  138. }
  139. if (preg_match('/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/', $s, $m)) {
  140. return $m[1];
  141. }
  142. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  143. return $m[1] . ' 00:00:00';
  144. }
  145. $ts = strtotime($s);
  146. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $s;
  147. }
  148. /**
  149. * 选择后台用户(发送人 / 接收人)
  150. */
  151. public function adminselect()
  152. {
  153. $this->model = model('Admin');
  154. $this->selectpageFields = 'id,username,nickname';
  155. $this->searchFields = 'id,username,nickname';
  156. $groupIds = $this->loadRecipientAuthGroupIds();
  157. $this->model->where('status', 'normal');
  158. if ($groupIds !== []) {
  159. $this->model->where('id', 'in', function ($query) use ($groupIds) {
  160. $query->name('auth_group_access')->where('group_id', 'in', $groupIds)->field('uid');
  161. });
  162. } else {
  163. $this->model->where('id', 0);
  164. }
  165. return $this->selectpage();
  166. }
  167. public function index()
  168. {
  169. $this->relationSearch = false;
  170. $this->request->filter(['strip_tags', 'trim']);
  171. if (!$this->request->isAjax()) {
  172. return $this->view->fetch();
  173. }
  174. $adminId = (int)$this->auth->id;
  175. $isSuper = $this->auth->isSuperAdmin();
  176. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  177. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  178. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? (string)$sort : 'id';
  179. $query = $this->model->where($where);
  180. if (!$isSuper) {
  181. $recvIds = Db::table('purchase_content_recipient')
  182. ->where('admin_id', $adminId)
  183. ->column('content_id');
  184. $recvIds = is_array($recvIds) ? array_values(array_unique(array_filter(array_map('intval', $recvIds)))) : [];
  185. $query->where(function ($q) use ($adminId, $recvIds) {
  186. $q->where('creator_id', $adminId);
  187. if ($recvIds !== []) {
  188. $q->whereOr('id', 'in', $recvIds);
  189. }
  190. });
  191. }
  192. $this->applyPurchaseContentSort($query, $sortField, $orderDir, $adminId);
  193. $list = $query->paginate($limit);
  194. $rows = $list->items();
  195. $this->enrichContentRows($rows, $adminId);
  196. return json(['total' => $list->total(), 'rows' => $rows]);
  197. }
  198. /**
  199. * 列表排序(支持投递人/投递给/状态等衍生字段)
  200. *
  201. * @param mixed $query
  202. */
  203. protected function applyPurchaseContentSort($query, string $sortField, string $orderDir, int $adminId): void
  204. {
  205. $table = $this->model->getTable();
  206. if ($sortField === 'sender_name') {
  207. $query->orderRaw(
  208. '(SELECT COALESCE(NULLIF(TRIM(sa.nickname), \'\'), sa.username, \'\') '
  209. . 'FROM admin sa WHERE sa.id = `' . $table . '`.sender_id LIMIT 1) ' . $orderDir
  210. )->order($table . '.id', 'DESC');
  211. return;
  212. }
  213. if ($sortField === 'recipient_names') {
  214. $query->orderRaw(
  215. '(SELECT COUNT(*) FROM purchase_content_recipient rcnt WHERE rcnt.content_id = `' . $table . '`.id) ' . $orderDir
  216. )->order($table . '.id', 'DESC');
  217. return;
  218. }
  219. if ($sortField === 'is_read') {
  220. $aid = max(0, $adminId);
  221. $query->orderRaw(
  222. '(SELECT CASE '
  223. . 'WHEN COUNT(*) = 0 THEN 2 '
  224. . 'WHEN SUM(CASE WHEN rr.read_time IS NULL OR rr.read_time = \'\' '
  225. . 'OR CAST(rr.read_time AS CHAR) LIKE \'0000-%\' THEN 1 ELSE 0 END) > 0 THEN 0 '
  226. . 'ELSE 1 END '
  227. . 'FROM purchase_content_recipient rr '
  228. . 'WHERE rr.content_id = `' . $table . '`.id AND rr.admin_id = ' . $aid . ') ' . $orderDir
  229. )->order($table . '.id', 'DESC');
  230. return;
  231. }
  232. $allow = ['id', 'createtime', 'subject', 'content', 'sender_id', 'creator_id', 'updatetime'];
  233. if (!in_array($sortField, $allow, true)) {
  234. $sortField = 'id';
  235. }
  236. $query->order($table . '.' . $sortField, $orderDir);
  237. }
  238. public function add()
  239. {
  240. if (!$this->request->isPost()) {
  241. $admin = $this->auth->getUserinfo();
  242. $this->view->assign('admin', [
  243. 'id' => (int)($admin['id'] ?? $this->auth->id),
  244. 'nickname' => (string)($admin['nickname'] ?? $admin['username'] ?? ''),
  245. ]);
  246. $this->view->assign('adminList', $this->loadNormalAdminList());
  247. return $this->view->fetch();
  248. }
  249. $params = $this->request->post('row/a');
  250. if (empty($params)) {
  251. $this->error(__('Parameter %s can not be empty', ''));
  252. }
  253. $subject = trim((string)($params['subject'] ?? ''));
  254. $content = trim((string)($params['content'] ?? ''));
  255. if ($subject === '') {
  256. $this->error('请填写主题');
  257. }
  258. if ($content === '') {
  259. $this->error('请填写内容');
  260. }
  261. $senderId = (int)$this->auth->id;
  262. if ($senderId <= 0 || !$this->adminExists($senderId)) {
  263. $this->error('当前登录用户无效');
  264. }
  265. $recipientIds = $this->parseRecipientIdList($params['recipient_ids'] ?? '');
  266. if ($recipientIds === []) {
  267. $this->error('请选择投递接收人');
  268. }
  269. $creatorId = (int)$this->auth->id;
  270. $now = date('Y-m-d H:i:s');
  271. Db::startTrans();
  272. try {
  273. $contentId = (int)Db::table('purchase_content')->insertGetId([
  274. 'creator_id' => $creatorId,
  275. 'sender_id' => $senderId,
  276. 'subject' => $subject,
  277. 'content' => $content,
  278. 'createtime' => $now,
  279. 'updatetime' => $now,
  280. ]);
  281. if ($contentId <= 0) {
  282. throw new Exception('保存公告失败');
  283. }
  284. $recvRows = [];
  285. foreach ($recipientIds as $aid) {
  286. $recvRows[] = [
  287. 'content_id' => $contentId,
  288. 'admin_id' => $aid,
  289. 'createtime' => $now,
  290. ];
  291. }
  292. Db::table('purchase_content_recipient')->insertAll($recvRows);
  293. Db::commit();
  294. } catch (ValidateException|PDOException|Exception $e) {
  295. Db::rollback();
  296. $this->error($e->getMessage());
  297. }
  298. $this->success();
  299. }
  300. public function detail($ids = null)
  301. {
  302. $row = $this->getContentRowForAdmin((int)$ids);
  303. if (!$row) {
  304. $this->error(__('No Results were found'));
  305. }
  306. $adminId = (int)$this->auth->id;
  307. $contentId = (int)$row['id'];
  308. $isCreator = (int)($row['creator_id'] ?? 0) === $adminId;
  309. $recvRow = Db::table('purchase_content_recipient')
  310. ->where('content_id', $contentId)
  311. ->where('admin_id', $adminId)
  312. ->find();
  313. $isReceiver = (bool)$recvRow;
  314. if (!$this->auth->isSuperAdmin() && !$isCreator && !$isReceiver) {
  315. $this->error('无权查看该通知');
  316. }
  317. // 当前用户是接收人时,首次查看标记为已读
  318. if ($recvRow) {
  319. $rt = $recvRow['read_time'] ?? null;
  320. $unread = ($rt === null || $rt === '' || stripos((string)$rt, '0000-00-00') === 0);
  321. if ($unread) {
  322. Db::table('purchase_content_recipient')
  323. ->where('id', (int)$recvRow['id'])
  324. ->update(['read_time' => date('Y-m-d H:i:s')]);
  325. }
  326. }
  327. $items = [$row];
  328. $this->enrichContentRows($items, $adminId);
  329. $row = $items[0];
  330. $this->view->assign('row', $row);
  331. return $this->view->fetch();
  332. }
  333. public function del($ids = null)
  334. {
  335. if (!$this->request->isPost()) {
  336. $this->error(__('Invalid parameters'));
  337. }
  338. $ids = $ids ?: $this->request->post('ids');
  339. $idList = $this->parseIdList($ids);
  340. if ($idList === []) {
  341. $this->error(__('Parameter %s can not be empty', 'ids'));
  342. }
  343. $adminId = (int)$this->auth->id;
  344. Db::startTrans();
  345. try {
  346. foreach ($idList as $cid) {
  347. $row = $this->model->get($cid);
  348. if (!$row) {
  349. continue;
  350. }
  351. if ((int)$row['sender_id'] !== $adminId) {
  352. throw new Exception('仅可删除本人投递的公告');
  353. }
  354. Db::table('purchase_content_recipient')->where('content_id', $cid)->delete();
  355. $row->delete();
  356. }
  357. Db::commit();
  358. } catch (PDOException|Exception $e) {
  359. Db::rollback();
  360. $this->error($e->getMessage());
  361. }
  362. $this->success();
  363. }
  364. /**
  365. * 安装菜单(超级管理员执行一次)
  366. */
  367. public function install()
  368. {
  369. if (!$this->auth->isSuperAdmin()) {
  370. $this->error('仅超级管理员可执行');
  371. }
  372. $t = time();
  373. $pid = 0;
  374. $parent = Db::name('auth_rule')->where('name', 'procuremenroot')->find();
  375. if ($parent) {
  376. $pid = (int)$parent['id'];
  377. } else {
  378. $pick = Db::name('auth_rule')->where('name', 'procuremen/pick')->find();
  379. if ($pick) {
  380. $pid = (int)($pick['pid'] ?? 0);
  381. }
  382. }
  383. if ($pid <= 0) {
  384. $this->error('未找到协助采购父菜单,请先在权限规则中配置 procuremenroot 或 procuremen/pick');
  385. }
  386. $added = 0;
  387. $menuName = 'purchasecontent/index';
  388. $menuRule = Db::name('auth_rule')->where('name', $menuName)->find();
  389. if ($menuRule) {
  390. $menuId = (int)$menuRule['id'];
  391. } else {
  392. $menuId = Db::name('auth_rule')->insertGetId([
  393. 'type' => 'file',
  394. 'pid' => $pid,
  395. 'name' => $menuName,
  396. 'title' => '通知公告',
  397. 'icon' => 'fa fa-bullhorn',
  398. 'url' => '',
  399. 'ismenu' => 1,
  400. 'menutype' => 'addtabs',
  401. 'weigh' => 84,
  402. 'status' => 'normal',
  403. 'createtime' => $t,
  404. 'updatetime' => $t,
  405. ]);
  406. $added++;
  407. }
  408. foreach (['purchasecontent/add' => '新增', 'purchasecontent/detail' => '查看', 'purchasecontent/del' => '删除', 'purchasecontent/adminselect' => '选择用户'] as $name => $title) {
  409. if (Db::name('auth_rule')->where('name', $name)->find()) {
  410. continue;
  411. }
  412. Db::name('auth_rule')->insert([
  413. 'type' => 'file',
  414. 'pid' => $menuId,
  415. 'name' => $name,
  416. 'title' => $title,
  417. 'icon' => 'fa fa-circle-o',
  418. 'ismenu' => 0,
  419. 'status' => 'normal',
  420. 'createtime' => $t,
  421. 'updatetime' => $t,
  422. ]);
  423. $added++;
  424. }
  425. \think\Cache::rm('__menu__');
  426. $this->success('通知公告菜单安装完成,新增节点 ' . $added . ' 个。请刷新后台并为角色勾选权限。');
  427. }
  428. /**
  429. * @param array<int, mixed> $rows
  430. */
  431. protected function enrichContentRows(array &$rows, int $currentAdminId): void
  432. {
  433. if ($rows === []) {
  434. return;
  435. }
  436. $contentIds = [];
  437. $adminIds = [];
  438. foreach ($rows as $r) {
  439. if (!is_array($r) && !is_object($r)) {
  440. continue;
  441. }
  442. $arr = is_array($r) ? $r : $r->toArray();
  443. $cid = (int)($arr['id'] ?? 0);
  444. if ($cid > 0) {
  445. $contentIds[$cid] = true;
  446. }
  447. foreach (['creator_id', 'sender_id'] as $fk) {
  448. $aid = (int)($arr[$fk] ?? 0);
  449. if ($aid > 0) {
  450. $adminIds[$aid] = true;
  451. }
  452. }
  453. }
  454. $nameMap = $this->loadAdminNicknameMap(array_keys($adminIds));
  455. $recvMap = $this->loadRecipientMap(array_keys($contentIds));
  456. foreach ($rows as &$row) {
  457. if (is_object($row) && method_exists($row, 'getData')) {
  458. $data = $row->getData();
  459. } elseif (is_object($row) && method_exists($row, 'toArray')) {
  460. $data = $row->toArray();
  461. } else {
  462. $data = (array)$row;
  463. }
  464. $cid = (int)($data['id'] ?? 0);
  465. $creatorId = (int)($data['creator_id'] ?? 0);
  466. $senderId = (int)($data['sender_id'] ?? 0);
  467. $recv = $recvMap[$cid] ?? ['names' => [], 'count' => 0, 'is_receiver' => false, 'read_time' => null];
  468. $isSender = ($senderId === $currentAdminId);
  469. $extra = [
  470. 'creator_name' => $nameMap[$creatorId] ?? '',
  471. 'sender_name' => $nameMap[$senderId] ?? '',
  472. 'sender_id' => $senderId,
  473. 'recipient_names' => implode('、', $recv['names']),
  474. 'recipient_count' => $recv['count'],
  475. 'is_receiver' => $recv['is_receiver'] ? 1 : 0,
  476. 'is_sender' => $isSender ? 1 : 0,
  477. 'is_read' => (!empty($recv['read_time'])) ? 1 : 0,
  478. 'read_time' => $recv['read_time'],
  479. 'send_time_text' => $this->formatPurchaseContentTime($data['createtime'] ?? ''),
  480. 'can_delete' => $isSender ? 1 : 0,
  481. ];
  482. if (is_object($row)) {
  483. foreach ($extra as $k => $v) {
  484. $row->$k = $v;
  485. }
  486. } else {
  487. $row = array_merge($data, $extra);
  488. }
  489. }
  490. unset($row);
  491. }
  492. /**
  493. * @param int[] $adminIds
  494. * @return array<int, string>
  495. */
  496. protected function loadAdminNicknameMap(array $adminIds): array
  497. {
  498. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  499. if ($adminIds === []) {
  500. return [];
  501. }
  502. $rows = Db::name('admin')
  503. ->where('id', 'in', $adminIds)
  504. ->field('id,nickname,username')
  505. ->select();
  506. if (!is_array($rows)) {
  507. return [];
  508. }
  509. $out = [];
  510. foreach ($rows as $r) {
  511. if (!is_array($r)) {
  512. continue;
  513. }
  514. $id = (int)($r['id'] ?? 0);
  515. $nick = trim((string)($r['nickname'] ?? ''));
  516. if ($nick === '') {
  517. $nick = trim((string)($r['username'] ?? ''));
  518. }
  519. $out[$id] = $nick !== '' ? $nick : ('#' . $id);
  520. }
  521. return $out;
  522. }
  523. /**
  524. * @param int[] $contentIds
  525. * @return array<int, array{names: string[], count: int, is_receiver: bool, read_time: int|null}>
  526. */
  527. protected function loadRecipientMap(array $contentIds): array
  528. {
  529. $contentIds = array_values(array_unique(array_filter(array_map('intval', $contentIds))));
  530. $out = [];
  531. if ($contentIds === []) {
  532. return $out;
  533. }
  534. $recvRows = Db::table('purchase_content_recipient')
  535. ->where('content_id', 'in', $contentIds)
  536. ->field('content_id,admin_id,read_time')
  537. ->select();
  538. if (!is_array($recvRows)) {
  539. return $out;
  540. }
  541. $adminIds = [];
  542. foreach ($recvRows as $r) {
  543. if (!is_array($r)) {
  544. continue;
  545. }
  546. $aid = (int)($r['admin_id'] ?? 0);
  547. if ($aid > 0) {
  548. $adminIds[$aid] = true;
  549. }
  550. }
  551. $nameMap = $this->loadAdminNicknameMap(array_keys($adminIds));
  552. $currentAdminId = (int)$this->auth->id;
  553. foreach ($recvRows as $r) {
  554. if (!is_array($r)) {
  555. continue;
  556. }
  557. $cid = (int)($r['content_id'] ?? 0);
  558. $aid = (int)($r['admin_id'] ?? 0);
  559. if ($cid <= 0) {
  560. continue;
  561. }
  562. if (!isset($out[$cid])) {
  563. $out[$cid] = ['names' => [], 'count' => 0, 'is_receiver' => false, 'read_time' => null];
  564. }
  565. $nm = $nameMap[$aid] ?? ('#' . $aid);
  566. if ($nm !== '' && !in_array($nm, $out[$cid]['names'], true)) {
  567. $out[$cid]['names'][] = $nm;
  568. }
  569. if ($aid === $currentAdminId) {
  570. $out[$cid]['is_receiver'] = true;
  571. $rt = $r['read_time'] ?? null;
  572. if ($rt !== null && $rt !== '' && stripos((string)$rt, '0000-00-00') !== 0) {
  573. $out[$cid]['read_time'] = $this->formatPurchaseContentTime($rt);
  574. }
  575. }
  576. }
  577. foreach ($out as $cid => &$item) {
  578. sort($item['names'], SORT_STRING);
  579. $item['count'] = count($item['names']);
  580. }
  581. unset($item);
  582. return $out;
  583. }
  584. protected function getContentRowForAdmin(int $id): ?array
  585. {
  586. if ($id <= 0) {
  587. return null;
  588. }
  589. $row = $this->model->get($id);
  590. return $row ? $row->toArray() : null;
  591. }
  592. protected function adminExists(int $adminId): bool
  593. {
  594. if ($adminId <= 0) {
  595. return false;
  596. }
  597. return (bool)Db::name('admin')->where('id', $adminId)->where('status', 'normal')->count();
  598. }
  599. /**
  600. * 接收人是否属于「供应商证」角色组(id=10)及其子组
  601. */
  602. protected function recipientAdminExists(int $adminId): bool
  603. {
  604. if ($adminId <= 0 || !$this->adminExists($adminId)) {
  605. return false;
  606. }
  607. $groupIds = $this->loadRecipientAuthGroupIds();
  608. if ($groupIds === []) {
  609. return false;
  610. }
  611. return (bool)Db::name('auth_group_access')
  612. ->where('uid', $adminId)
  613. ->where('group_id', 'in', $groupIds)
  614. ->count();
  615. }
  616. /**
  617. * auth_group id=10 及其全部子组 id
  618. *
  619. * @return int[]
  620. */
  621. protected function loadRecipientAuthGroupIds(): array
  622. {
  623. static $memo = null;
  624. if ($memo !== null) {
  625. return $memo;
  626. }
  627. $cacheKey = 'purchase_content_group_ids_' . self::RECIPIENT_AUTH_GROUP_ROOT_ID;
  628. $cached = Cache::get($cacheKey);
  629. if (is_array($cached) && $cached !== []) {
  630. $memo = $cached;
  631. return $memo;
  632. }
  633. $rootId = self::RECIPIENT_AUTH_GROUP_ROOT_ID;
  634. try {
  635. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  636. } catch (\Throwable $e) {
  637. return [$rootId];
  638. }
  639. if (!is_array($groups) || $groups === []) {
  640. return [$rootId];
  641. }
  642. $groupList = [];
  643. foreach ($groups as $g) {
  644. if (is_array($g)) {
  645. $groupList[] = $g;
  646. }
  647. }
  648. if ($groupList === []) {
  649. return [$rootId];
  650. }
  651. $tree = \fast\Tree::instance();
  652. $tree->init($groupList);
  653. $ids = $tree->getChildrenIds($rootId, true);
  654. if (!is_array($ids) || $ids === []) {
  655. $memo = [$rootId];
  656. return $memo;
  657. }
  658. $memo = array_values(array_unique(array_filter(array_map('intval', $ids))));
  659. Cache::set($cacheKey, $memo, self::RECIPIENT_LIST_CACHE_TTL);
  660. return $memo;
  661. }
  662. /**
  663. * 新增公告:可选接收人列表(仅角色组 id=10 及其子组下的用户)
  664. *
  665. * @return array<int, array{id:int, username:string, nickname:string, label:string}>
  666. */
  667. protected function loadNormalAdminList(): array
  668. {
  669. $cacheKey = 'purchase_content_admin_list_v2_' . self::RECIPIENT_AUTH_GROUP_ROOT_ID;
  670. $cached = Cache::get($cacheKey);
  671. if (is_array($cached)) {
  672. return $cached;
  673. }
  674. $groupIds = $this->loadRecipientAuthGroupIds();
  675. if ($groupIds === []) {
  676. return [];
  677. }
  678. try {
  679. $adminIds = Db::name('auth_group_access')
  680. ->where('group_id', 'in', $groupIds)
  681. ->column('uid');
  682. } catch (\Throwable $e) {
  683. $adminIds = [];
  684. }
  685. $adminIds = is_array($adminIds)
  686. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  687. : [];
  688. if ($adminIds === []) {
  689. return [];
  690. }
  691. try {
  692. $rows = Db::name('admin')
  693. ->where('status', 'normal')
  694. ->where('id', 'in', $adminIds)
  695. ->field('id,username,nickname')
  696. ->order('id', 'asc')
  697. ->select();
  698. } catch (\Throwable $e) {
  699. $rows = [];
  700. }
  701. if (!is_array($rows)) {
  702. return [];
  703. }
  704. $out = [];
  705. foreach ($rows as $r) {
  706. if (!is_array($r)) {
  707. continue;
  708. }
  709. $id = (int)($r['id'] ?? 0);
  710. if ($id <= 0) {
  711. continue;
  712. }
  713. $username = trim((string)($r['username'] ?? ''));
  714. $nickname = trim((string)($r['nickname'] ?? ''));
  715. if ($nickname === '') {
  716. $nickname = $username;
  717. }
  718. if ($nickname === '') {
  719. $nickname = '#' . $id;
  720. }
  721. $out[] = [
  722. 'id' => $id,
  723. 'username' => $username,
  724. 'nickname' => $nickname,
  725. 'label' => $nickname,
  726. ];
  727. }
  728. Cache::set($cacheKey, $out, self::RECIPIENT_LIST_CACHE_TTL);
  729. return $out;
  730. }
  731. /**
  732. * @param mixed $raw
  733. * @return int[]
  734. */
  735. protected function parseIdList($raw): array
  736. {
  737. if (is_array($raw)) {
  738. $parts = $raw;
  739. } else {
  740. $parts = preg_split('/\s*,\s*/', trim((string)$raw), -1, PREG_SPLIT_NO_EMPTY);
  741. }
  742. if (!is_array($parts)) {
  743. return [];
  744. }
  745. $out = [];
  746. foreach ($parts as $p) {
  747. $id = (int)$p;
  748. if ($id > 0) {
  749. $out[$id] = $id;
  750. }
  751. }
  752. return array_values($out);
  753. }
  754. /**
  755. * 解析并校验接收人 id(须为角色组 id=10 及其子组下的正常用户)
  756. *
  757. * @param mixed $raw
  758. * @return int[]
  759. */
  760. protected function parseRecipientIdList($raw): array
  761. {
  762. $out = [];
  763. foreach ($this->parseIdList($raw) as $id) {
  764. if ($this->recipientAdminExists($id)) {
  765. $out[$id] = $id;
  766. }
  767. }
  768. return array_values($out);
  769. }
  770. }