Purchasecontent.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use think\Db;
  5. use think\exception\PDOException;
  6. use think\exception\ValidateException;
  7. use Exception;
  8. /**
  9. * 协助采购 — 通知公告
  10. *
  11. * @icon fa fa-bullhorn
  12. */
  13. class Purchasecontent extends Backend
  14. {
  15. /** @var \app\admin\model\Purchasecontent */
  16. protected $model = null;
  17. protected $searchFields = 'subject,content';
  18. protected $noNeedRight = ['adminselect', 'install'];
  19. public function _initialize()
  20. {
  21. parent::_initialize();
  22. $this->model = new \app\admin\model\Purchasecontent;
  23. $this->ensurePurchaseContentTables();
  24. }
  25. protected function ensurePurchaseContentTables(): void
  26. {
  27. try {
  28. Db::query('SELECT 1 FROM `purchase_content` LIMIT 1');
  29. Db::query('SELECT 1 FROM `purchase_content_recipient` LIMIT 1');
  30. } catch (\Throwable $e) {
  31. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_content_install.sql';
  32. if (is_file($sqlFile)) {
  33. $sql = file_get_contents($sqlFile);
  34. if (is_string($sql) && $sql !== '') {
  35. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  36. $stmt = trim($stmt);
  37. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  38. continue;
  39. }
  40. try {
  41. Db::execute($stmt);
  42. } catch (\Throwable $ignore) {
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }
  49. /**
  50. * 选择后台用户(发送人 / 接收人)
  51. */
  52. public function adminselect()
  53. {
  54. $this->model = model('Admin');
  55. $this->selectpageFields = 'id,username,nickname';
  56. $this->searchFields = 'id,username,nickname';
  57. $this->model->where('status', 'normal');
  58. return $this->selectpage();
  59. }
  60. public function index()
  61. {
  62. $this->relationSearch = false;
  63. $this->request->filter(['strip_tags', 'trim']);
  64. if (!$this->request->isAjax()) {
  65. return $this->view->fetch();
  66. }
  67. $adminId = (int)$this->auth->id;
  68. $isSuper = $this->auth->isSuperAdmin();
  69. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  70. $query = $this->model->where($where);
  71. if (!$isSuper) {
  72. $recvIds = Db::table('purchase_content_recipient')
  73. ->where('admin_id', $adminId)
  74. ->column('content_id');
  75. $recvIds = is_array($recvIds) ? array_values(array_unique(array_filter(array_map('intval', $recvIds)))) : [];
  76. $query->where(function ($q) use ($adminId, $recvIds) {
  77. $q->where('creator_id', $adminId);
  78. if ($recvIds !== []) {
  79. $q->whereOr('id', 'in', $recvIds);
  80. }
  81. });
  82. }
  83. $list = $query->order($sort, $order)->paginate($limit);
  84. $rows = $list->items();
  85. $this->enrichContentRows($rows, $adminId);
  86. return json(['total' => $list->total(), 'rows' => $rows]);
  87. }
  88. public function add()
  89. {
  90. if (!$this->request->isPost()) {
  91. $admin = $this->auth->getUserinfo();
  92. $this->view->assign('admin', [
  93. 'id' => (int)($admin['id'] ?? $this->auth->id),
  94. 'nickname' => (string)($admin['nickname'] ?? $admin['username'] ?? ''),
  95. ]);
  96. $this->view->assign('adminList', $this->loadNormalAdminList());
  97. return $this->view->fetch();
  98. }
  99. $params = $this->request->post('row/a');
  100. if (empty($params)) {
  101. $this->error(__('Parameter %s can not be empty', ''));
  102. }
  103. $subject = trim((string)($params['subject'] ?? ''));
  104. $content = trim((string)($params['content'] ?? ''));
  105. if ($subject === '') {
  106. $this->error('请填写主题');
  107. }
  108. if ($content === '') {
  109. $this->error('请填写内容');
  110. }
  111. $senderId = (int)$this->auth->id;
  112. if ($senderId <= 0 || !$this->adminExists($senderId)) {
  113. $this->error('当前登录用户无效');
  114. }
  115. $recipientIds = $this->parseIdList($params['recipient_ids'] ?? '');
  116. if ($recipientIds === []) {
  117. $this->error('请选择投递接收人');
  118. }
  119. $creatorId = (int)$this->auth->id;
  120. $now = time();
  121. Db::startTrans();
  122. try {
  123. $contentId = (int)Db::table('purchase_content')->insertGetId([
  124. 'creator_id' => $creatorId,
  125. 'sender_id' => $senderId,
  126. 'subject' => $subject,
  127. 'content' => $content,
  128. 'createtime' => $now,
  129. 'updatetime' => $now,
  130. ]);
  131. if ($contentId <= 0) {
  132. throw new Exception('保存公告失败');
  133. }
  134. $recvRows = [];
  135. foreach ($recipientIds as $aid) {
  136. $recvRows[] = [
  137. 'content_id' => $contentId,
  138. 'admin_id' => $aid,
  139. 'createtime' => $now,
  140. ];
  141. }
  142. Db::table('purchase_content_recipient')->insertAll($recvRows);
  143. Db::commit();
  144. } catch (ValidateException|PDOException|Exception $e) {
  145. Db::rollback();
  146. $this->error($e->getMessage());
  147. }
  148. $this->success();
  149. }
  150. public function detail($ids = null)
  151. {
  152. $row = $this->getContentRowForAdmin((int)$ids);
  153. if (!$row) {
  154. $this->error(__('No Results were found'));
  155. }
  156. $adminId = (int)$this->auth->id;
  157. if (!$this->auth->isSuperAdmin() && (int)$row['creator_id'] !== $adminId) {
  158. $isRecv = Db::table('purchase_content_recipient')
  159. ->where('content_id', (int)$row['id'])
  160. ->where('admin_id', $adminId)
  161. ->count();
  162. if (!$isRecv) {
  163. $this->error('无权查看该通知');
  164. }
  165. $recvRow = Db::table('purchase_content_recipient')
  166. ->where('content_id', (int)$row['id'])
  167. ->where('admin_id', $adminId)
  168. ->find();
  169. if ($recvRow && empty($recvRow['read_time'])) {
  170. Db::table('purchase_content_recipient')
  171. ->where('id', (int)$recvRow['id'])
  172. ->update(['read_time' => time()]);
  173. }
  174. }
  175. $items = [$row];
  176. $this->enrichContentRows($items, $adminId);
  177. $row = $items[0];
  178. $this->view->assign('row', $row);
  179. return $this->view->fetch();
  180. }
  181. public function del($ids = null)
  182. {
  183. if (!$this->request->isPost()) {
  184. $this->error(__('Invalid parameters'));
  185. }
  186. $ids = $ids ?: $this->request->post('ids');
  187. $idList = $this->parseIdList($ids);
  188. if ($idList === []) {
  189. $this->error(__('Parameter %s can not be empty', 'ids'));
  190. }
  191. $adminId = (int)$this->auth->id;
  192. $isSuper = $this->auth->isSuperAdmin();
  193. Db::startTrans();
  194. try {
  195. foreach ($idList as $cid) {
  196. $row = $this->model->get($cid);
  197. if (!$row) {
  198. continue;
  199. }
  200. if (!$isSuper && (int)$row['creator_id'] !== $adminId) {
  201. throw new Exception('仅创建人或超级管理员可删除');
  202. }
  203. Db::table('purchase_content_recipient')->where('content_id', $cid)->delete();
  204. $row->delete();
  205. }
  206. Db::commit();
  207. } catch (PDOException|Exception $e) {
  208. Db::rollback();
  209. $this->error($e->getMessage());
  210. }
  211. $this->success();
  212. }
  213. /**
  214. * 安装菜单(超级管理员执行一次)
  215. */
  216. public function install()
  217. {
  218. if (!$this->auth->isSuperAdmin()) {
  219. $this->error('仅超级管理员可执行');
  220. }
  221. $t = time();
  222. $pid = 0;
  223. $parent = Db::name('auth_rule')->where('name', 'procuremenroot')->find();
  224. if ($parent) {
  225. $pid = (int)$parent['id'];
  226. } else {
  227. $pick = Db::name('auth_rule')->where('name', 'procuremen/pick')->find();
  228. if ($pick) {
  229. $pid = (int)($pick['pid'] ?? 0);
  230. }
  231. }
  232. if ($pid <= 0) {
  233. $this->error('未找到协助采购父菜单,请先在权限规则中配置 procuremenroot 或 procuremen/pick');
  234. }
  235. $added = 0;
  236. $menuName = 'purchasecontent/index';
  237. $menuRule = Db::name('auth_rule')->where('name', $menuName)->find();
  238. if ($menuRule) {
  239. $menuId = (int)$menuRule['id'];
  240. } else {
  241. $menuId = Db::name('auth_rule')->insertGetId([
  242. 'type' => 'file',
  243. 'pid' => $pid,
  244. 'name' => $menuName,
  245. 'title' => '通知公告',
  246. 'icon' => 'fa fa-bullhorn',
  247. 'url' => '',
  248. 'ismenu' => 1,
  249. 'menutype' => 'addtabs',
  250. 'weigh' => 84,
  251. 'status' => 'normal',
  252. 'createtime' => $t,
  253. 'updatetime' => $t,
  254. ]);
  255. $added++;
  256. }
  257. foreach (['purchasecontent/add' => '新增', 'purchasecontent/detail' => '查看', 'purchasecontent/del' => '删除', 'purchasecontent/adminselect' => '选择用户'] as $name => $title) {
  258. if (Db::name('auth_rule')->where('name', $name)->find()) {
  259. continue;
  260. }
  261. Db::name('auth_rule')->insert([
  262. 'type' => 'file',
  263. 'pid' => $menuId,
  264. 'name' => $name,
  265. 'title' => $title,
  266. 'icon' => 'fa fa-circle-o',
  267. 'ismenu' => 0,
  268. 'status' => 'normal',
  269. 'createtime' => $t,
  270. 'updatetime' => $t,
  271. ]);
  272. $added++;
  273. }
  274. \think\Cache::rm('__menu__');
  275. $this->success('通知公告菜单安装完成,新增节点 ' . $added . ' 个。请刷新后台并为角色勾选权限。');
  276. }
  277. /**
  278. * @param array<int, mixed> $rows
  279. */
  280. protected function enrichContentRows(array &$rows, int $currentAdminId): void
  281. {
  282. if ($rows === []) {
  283. return;
  284. }
  285. $contentIds = [];
  286. $adminIds = [];
  287. foreach ($rows as $r) {
  288. if (!is_array($r) && !is_object($r)) {
  289. continue;
  290. }
  291. $arr = is_array($r) ? $r : $r->toArray();
  292. $cid = (int)($arr['id'] ?? 0);
  293. if ($cid > 0) {
  294. $contentIds[$cid] = true;
  295. }
  296. foreach (['creator_id', 'sender_id'] as $fk) {
  297. $aid = (int)($arr[$fk] ?? 0);
  298. if ($aid > 0) {
  299. $adminIds[$aid] = true;
  300. }
  301. }
  302. }
  303. $nameMap = $this->loadAdminNicknameMap(array_keys($adminIds));
  304. $recvMap = $this->loadRecipientMap(array_keys($contentIds));
  305. foreach ($rows as &$row) {
  306. if (is_object($row) && method_exists($row, 'getData')) {
  307. $data = $row->getData();
  308. } elseif (is_object($row) && method_exists($row, 'toArray')) {
  309. $data = $row->toArray();
  310. } else {
  311. $data = (array)$row;
  312. }
  313. $cid = (int)($data['id'] ?? 0);
  314. $creatorId = (int)($data['creator_id'] ?? 0);
  315. $senderId = (int)($data['sender_id'] ?? 0);
  316. $recv = $recvMap[$cid] ?? ['names' => [], 'count' => 0, 'is_receiver' => false, 'read_time' => null];
  317. $extra = [
  318. 'creator_name' => $nameMap[$creatorId] ?? '',
  319. 'sender_name' => $nameMap[$senderId] ?? '',
  320. 'recipient_names' => implode('、', $recv['names']),
  321. 'recipient_count' => $recv['count'],
  322. 'is_receiver' => $recv['is_receiver'] ? 1 : 0,
  323. 'read_time' => $recv['read_time'],
  324. 'can_delete' => ($this->auth->isSuperAdmin() || $creatorId === $currentAdminId) ? 1 : 0,
  325. ];
  326. if (is_object($row)) {
  327. foreach ($extra as $k => $v) {
  328. $row->$k = $v;
  329. }
  330. } else {
  331. $row = array_merge($data, $extra);
  332. }
  333. }
  334. unset($row);
  335. }
  336. /**
  337. * @param int[] $adminIds
  338. * @return array<int, string>
  339. */
  340. protected function loadAdminNicknameMap(array $adminIds): array
  341. {
  342. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  343. if ($adminIds === []) {
  344. return [];
  345. }
  346. $rows = Db::name('admin')
  347. ->where('id', 'in', $adminIds)
  348. ->field('id,nickname,username')
  349. ->select();
  350. if (!is_array($rows)) {
  351. return [];
  352. }
  353. $out = [];
  354. foreach ($rows as $r) {
  355. if (!is_array($r)) {
  356. continue;
  357. }
  358. $id = (int)($r['id'] ?? 0);
  359. $nick = trim((string)($r['nickname'] ?? ''));
  360. if ($nick === '') {
  361. $nick = trim((string)($r['username'] ?? ''));
  362. }
  363. $out[$id] = $nick !== '' ? $nick : ('#' . $id);
  364. }
  365. return $out;
  366. }
  367. /**
  368. * @param int[] $contentIds
  369. * @return array<int, array{names: string[], count: int, is_receiver: bool, read_time: int|null}>
  370. */
  371. protected function loadRecipientMap(array $contentIds): array
  372. {
  373. $contentIds = array_values(array_unique(array_filter(array_map('intval', $contentIds))));
  374. $out = [];
  375. if ($contentIds === []) {
  376. return $out;
  377. }
  378. $recvRows = Db::table('purchase_content_recipient')
  379. ->where('content_id', 'in', $contentIds)
  380. ->field('content_id,admin_id,read_time')
  381. ->select();
  382. if (!is_array($recvRows)) {
  383. return $out;
  384. }
  385. $adminIds = [];
  386. foreach ($recvRows as $r) {
  387. if (!is_array($r)) {
  388. continue;
  389. }
  390. $aid = (int)($r['admin_id'] ?? 0);
  391. if ($aid > 0) {
  392. $adminIds[$aid] = true;
  393. }
  394. }
  395. $nameMap = $this->loadAdminNicknameMap(array_keys($adminIds));
  396. $currentAdminId = (int)$this->auth->id;
  397. foreach ($recvRows as $r) {
  398. if (!is_array($r)) {
  399. continue;
  400. }
  401. $cid = (int)($r['content_id'] ?? 0);
  402. $aid = (int)($r['admin_id'] ?? 0);
  403. if ($cid <= 0) {
  404. continue;
  405. }
  406. if (!isset($out[$cid])) {
  407. $out[$cid] = ['names' => [], 'count' => 0, 'is_receiver' => false, 'read_time' => null];
  408. }
  409. $nm = $nameMap[$aid] ?? ('#' . $aid);
  410. if ($nm !== '' && !in_array($nm, $out[$cid]['names'], true)) {
  411. $out[$cid]['names'][] = $nm;
  412. }
  413. if ($aid === $currentAdminId) {
  414. $out[$cid]['is_receiver'] = true;
  415. $rt = (int)($r['read_time'] ?? 0);
  416. if ($rt > 0) {
  417. $out[$cid]['read_time'] = $rt;
  418. }
  419. }
  420. }
  421. foreach ($out as $cid => &$item) {
  422. sort($item['names'], SORT_STRING);
  423. $item['count'] = count($item['names']);
  424. }
  425. unset($item);
  426. return $out;
  427. }
  428. protected function getContentRowForAdmin(int $id): ?array
  429. {
  430. if ($id <= 0) {
  431. return null;
  432. }
  433. $row = $this->model->get($id);
  434. return $row ? $row->toArray() : null;
  435. }
  436. protected function adminExists(int $adminId): bool
  437. {
  438. if ($adminId <= 0) {
  439. return false;
  440. }
  441. return (bool)Db::name('admin')->where('id', $adminId)->where('status', 'normal')->count();
  442. }
  443. /**
  444. * 新增公告:可选接收人列表
  445. *
  446. * @return array<int, array{id:int, username:string, nickname:string, label:string}>
  447. */
  448. protected function loadNormalAdminList(): array
  449. {
  450. try {
  451. $rows = Db::name('admin')
  452. ->where('status', 'normal')
  453. ->field('id,username,nickname')
  454. ->order('id', 'asc')
  455. ->select();
  456. } catch (\Throwable $e) {
  457. $rows = [];
  458. }
  459. if (!is_array($rows)) {
  460. return [];
  461. }
  462. $out = [];
  463. foreach ($rows as $r) {
  464. if (!is_array($r)) {
  465. continue;
  466. }
  467. $id = (int)($r['id'] ?? 0);
  468. if ($id <= 0) {
  469. continue;
  470. }
  471. $username = trim((string)($r['username'] ?? ''));
  472. $nickname = trim((string)($r['nickname'] ?? ''));
  473. if ($nickname === '') {
  474. $nickname = $username;
  475. }
  476. $label = $nickname;
  477. if ($username !== '' && $username !== $nickname) {
  478. $label .= '(' . $username . ')';
  479. }
  480. $out[] = [
  481. 'id' => $id,
  482. 'username' => $username,
  483. 'nickname' => $nickname,
  484. 'label' => $label,
  485. ];
  486. }
  487. return $out;
  488. }
  489. /**
  490. * @param mixed $raw
  491. * @return int[]
  492. */
  493. protected function parseIdList($raw): array
  494. {
  495. if (is_array($raw)) {
  496. $parts = $raw;
  497. } else {
  498. $parts = preg_split('/\s*,\s*/', trim((string)$raw), -1, PREG_SPLIT_NO_EMPTY);
  499. }
  500. if (!is_array($parts)) {
  501. return [];
  502. }
  503. $out = [];
  504. foreach ($parts as $p) {
  505. $id = (int)$p;
  506. if ($id > 0 && $this->adminExists($id)) {
  507. $out[$id] = $id;
  508. }
  509. }
  510. return array_values($out);
  511. }
  512. }