Actions.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. /**
  3. * ----------------------------------------------------------------------------
  4. * 行到水穷处,坐看云起时
  5. * 开发软件,找贵阳云起信息科技,官网地址:https://www.56q7.com/
  6. * ----------------------------------------------------------------------------
  7. * Author: 老成
  8. * email:85556713@qq.com
  9. */
  10. declare(strict_types=1);
  11. namespace app\admin\traits;
  12. use app\common\library\Tree;
  13. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  14. use PhpOffice\PhpSpreadsheet\Shared\Date;
  15. use think\annotation\route\Route;
  16. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  17. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  18. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  19. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  20. use think\facade\Db;
  21. use app\common\library\Export;
  22. trait Actions
  23. {
  24. /**
  25. * 增删改查等操作成功后的回调方法
  26. * 请勿在回调函数内使用$this->error()方法,使用ThrowException抛出异常
  27. */
  28. protected $callback;
  29. /**
  30. * 自定义导出数据的控制器及方法
  31. */
  32. protected $downloadController;
  33. protected $downloadAction;
  34. /**
  35. * 添加插入时额外增加的字段
  36. * 支持add,edit
  37. */
  38. protected $postParams = [];
  39. /**
  40. * 回收站显示的字段
  41. */
  42. protected $recyclebinColumns=[
  43. 'id'=>'ID'
  44. ];
  45. /**
  46. * 回收站显示的字段类型,支持text,image,images,date,datetime,tag,tags,默认为text
  47. */
  48. protected $recyclebinColumnsType=[];
  49. /**
  50. * 导入字段
  51. */
  52. protected $importFields=[];
  53. /**
  54. * 关联查询的字段
  55. * @var array
  56. */
  57. protected $relationField=[];
  58. /**
  59. * 修改、删除、更新时验证属性权限
  60. * @var array
  61. */
  62. protected $volidateFields=[];
  63. /**
  64. * 查看
  65. */
  66. #[Route('GET,JSON','index')]
  67. public function index()
  68. {
  69. if (false === $this->request->isAjax()) {
  70. return $this->fetch();
  71. }
  72. if($this->request->post('selectpage')){
  73. return $this->selectpage();
  74. }
  75. [$where, $order, $limit, $with] = $this->buildparams();
  76. $list = $this->model
  77. ->withJoin($with,'left')
  78. //如果没有使用operate filter过滤的情况下,推荐使用with关联,可以提高查询效率
  79. //->with($with)
  80. ->where($where)
  81. ->order($order)
  82. ->paginate($limit);
  83. $result = ['total' => $list->total(), 'rows' => $list->items()];
  84. return json($result);
  85. }
  86. /**
  87. * 添加
  88. */
  89. #[Route('GET,POST','add')]
  90. public function add()
  91. {
  92. if (false === $this->request->isPost()) {
  93. return $this->fetch();
  94. }
  95. $params = array_merge($this->request->post("row/a"),$this->postParams);
  96. if (empty($params)) {
  97. $this->error(__('提交的参数不能为空'));
  98. }
  99. if(!$this->request->checkToken('__token__',['__token__'=>$this->request->post('__token__')])){
  100. $this->error(__('token错误,请刷新页面重试'));
  101. }
  102. foreach ($params as &$value){
  103. if(is_array($value)){
  104. $value=implode(',',$value);
  105. }
  106. if($value===''){
  107. $value=null;
  108. }
  109. }
  110. $result = false;
  111. Db::startTrans();
  112. try {
  113. $result = $this->model->save($params);
  114. if($this->callback){
  115. $callback=$this->callback;
  116. $callback($this->model);
  117. }
  118. Db::commit();
  119. } catch (\Exception $e) {
  120. Db::rollback();
  121. $this->error($e->getMessage());
  122. }
  123. if ($result === false) {
  124. $this->error(__('没有新增任何数据'));
  125. }
  126. $this->success();
  127. }
  128. /**
  129. * 编辑
  130. */
  131. #[Route('GET,POST','edit')]
  132. public function edit(mixed $row=null)
  133. {
  134. $ids = $this->request->get('ids');
  135. if(!$row || is_array($row)){
  136. $row = $this->model->find($ids);
  137. }
  138. if (!$row) {
  139. $this->error(__('没有找到记录'));
  140. }
  141. if(count($this->volidateFields)>0){
  142. foreach ($this->volidateFields as $field=>$value){
  143. if($row[$field]!=$value){
  144. $this->error(__('没有操作权限'));
  145. }
  146. }
  147. }
  148. if (false === $this->request->isPost()) {
  149. $this->assign('row', $row);
  150. return $this->fetch();
  151. }
  152. $params = array_merge($this->request->post("row/a"),$this->postParams);
  153. if (empty($params)) {
  154. $this->error(__('提交的参数不能为空'));
  155. }
  156. if(!$this->request->checkToken('__token__',['__token__'=>$this->request->post('__token__')])){
  157. $this->error(__('token错误,请刷新页面重试'));
  158. }
  159. foreach ($params as &$value){
  160. if(is_array($value)){
  161. $value=implode(',',$value);
  162. }
  163. if($value===''){
  164. $value=null;
  165. }
  166. }
  167. $result = false;
  168. Db::startTrans();
  169. try {
  170. $result = $row->save($params);
  171. if($this->callback){
  172. $callback=$this->callback;
  173. $callback($row);
  174. }
  175. Db::commit();
  176. } catch (\Exception $e) {
  177. Db::rollback();
  178. $this->error($e->getMessage());
  179. }
  180. if (false === $result) {
  181. $this->error(__('没有数据被更新'));
  182. }
  183. $this->success();
  184. }
  185. /**
  186. * 删除
  187. */
  188. #[Route('GET,POST','del')]
  189. public function del()
  190. {
  191. $ids = $this->request->param("ids");
  192. if (empty($ids)) {
  193. $this->error(__('参数%s不能为空', ['s'=>'ids']));
  194. }
  195. $pk = $this->model->getPk();
  196. $list = $this->model->where($pk, 'in', $ids)->select();
  197. $count = 0;
  198. Db::startTrans();
  199. try {
  200. foreach ($list as $item) {
  201. if(count($this->volidateFields)>0){
  202. foreach ($this->volidateFields as $field=>$value){
  203. if($item[$field]!=$value){
  204. $this->error(__('没有操作权限'));
  205. }
  206. }
  207. }
  208. $count += $item->delete();
  209. }
  210. if($this->callback){
  211. $callback=$this->callback;
  212. $callback($ids);
  213. }
  214. Db::commit();
  215. } catch (\Exception $e) {
  216. Db::rollback();
  217. $this->error($e->getMessage());
  218. }
  219. if ($count) {
  220. $this->success();
  221. }
  222. $this->error(__('没有记录被删除'));
  223. }
  224. /**
  225. * 批量更新一个字段
  226. */
  227. #[Route('POST,GET','multi')]
  228. public function multi()
  229. {
  230. $ids = $this->request->param('ids');
  231. $field = $this->request->param('field');
  232. $value = $this->request->param('value');
  233. if(!$ids){
  234. $this->error(__('没有需要更新的行'));
  235. }
  236. if(!$field){
  237. $this->error(__('没有需要更新的列'));
  238. }
  239. $ids=is_string($ids)?explode(',',$ids):$ids;
  240. $pk=$this->model->getPk();
  241. $count = 0;
  242. Db::startTrans();
  243. try {
  244. foreach ($ids as $id) {
  245. $id=intval($id);
  246. $where=[
  247. $pk=>$id
  248. ];
  249. if(count($this->volidateFields)>0){
  250. foreach ($this->volidateFields as $sk=>$sv){
  251. $where[$sk]=$sv;
  252. }
  253. }
  254. $r = $this->model->where($where)->update([$field=>$value]);
  255. if($r){
  256. $count++;
  257. }
  258. }
  259. if($this->callback){
  260. $callback=$this->callback;
  261. $callback($ids,$field,$value);
  262. }
  263. Db::commit();
  264. } catch (\Exception $e) {
  265. Db::rollback();
  266. $this->error($e->getMessage());
  267. }
  268. if ($count) {
  269. $this->success();
  270. }
  271. $this->error(__('没有数据被更新'));
  272. }
  273. /**
  274. * 导入
  275. */
  276. #[Route('GET,POST','import')]
  277. protected function import()
  278. {
  279. $file = $this->request->request('file');
  280. if (!$file) {
  281. $this->error(__('参数%s不能为空', ['s'=>'file']));
  282. }
  283. $filePath = root_path() . DS . $file;
  284. if (!is_file($filePath)) {
  285. $this->error(__('上传文件不存在'));
  286. }
  287. //实例化reader
  288. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  289. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  290. $this->error(__('文件格式不正确'));
  291. }
  292. if ($ext === 'csv') {
  293. $file = fopen($filePath, 'r');
  294. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  295. $fp = fopen($filePath, 'w');
  296. $n = 0;
  297. while ($line = fgets($file)) {
  298. $line = rtrim($line, "\n\r\0");
  299. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  300. if ($encoding !== 'utf-8') {
  301. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  302. }
  303. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  304. fwrite($fp, $line . "\n");
  305. } else {
  306. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  307. }
  308. $n++;
  309. }
  310. fclose($file) || fclose($fp);
  311. $reader = new Csv();
  312. } elseif ($ext === 'xls') {
  313. $reader = new Xls();
  314. } else {
  315. $reader = new Xlsx();
  316. }
  317. $fieldArr = array_flip($this->importFields);
  318. if(empty($fieldArr)){
  319. $this->error(__('导入字段不能为空'));
  320. }
  321. //加载文件
  322. $insert = [];
  323. try {
  324. if (!$PHPExcel = $reader->load($filePath)) {
  325. $this->error(__('未知文件格式'));
  326. }
  327. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  328. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  329. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  330. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  331. $fields = [];
  332. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  333. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  334. $columnName = Coordinate::stringFromColumnIndex($currentColumn);
  335. $val = $currentSheet->getCell($columnName.$currentRow)->getCalculatedValue();
  336. $fields[] = is_null($val) ? '' : $val;
  337. }
  338. }
  339. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  340. $values = [];
  341. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  342. $columnName = Coordinate::stringFromColumnIndex($currentColumn);
  343. $cell = $currentSheet->getCell($columnName.$currentRow);
  344. $dataType=$cell->getDataType();
  345. $val = $cell->getCalculatedValue();
  346. if($dataType==DataType::TYPE_ISO_DATE){
  347. }
  348. $values[] = is_null($val) ? '' : $val;
  349. }
  350. $row = [];
  351. $temp = array_combine($fields, $values);
  352. foreach ($temp as $k => $v) {
  353. if(isset($fieldArr[$k])){
  354. $row[$fieldArr[$k]]=$v;
  355. }
  356. }
  357. if ($row) {
  358. $insert[] = $row;
  359. }
  360. }
  361. } catch (Exception $exception) {
  362. $this->error($exception->getMessage());
  363. }
  364. if (!$insert) {
  365. $this->error(__('一行都未导入'));
  366. }
  367. $success=0;
  368. $fail=[];
  369. try {
  370. if($this->callback){
  371. $rinsert=[];
  372. $callback = $this->callback;
  373. foreach ($insert as $vf){
  374. $ss=$callback($vf,$success,$fail);
  375. if($ss){
  376. $rinsert[]=$ss;
  377. $success++;
  378. }
  379. }
  380. if(!empty($rinsert)){
  381. $this->model->saveAll($rinsert);
  382. }
  383. }else{
  384. $this->model->saveAll($insert);
  385. }
  386. } catch (PDOException $exception) {
  387. $msg = $exception->getMessage();
  388. $this->error($msg);
  389. } catch (Exception $e) {
  390. $this->error($e->getMessage());
  391. }
  392. $this->success('',compact('success','fail'));
  393. }
  394. /**
  395. * 回收站
  396. */
  397. #[Route('GET,POST,JSON','recyclebin')]
  398. public function recyclebin($action='list')
  399. {
  400. switch ($action){
  401. case 'list':
  402. if (false === $this->request->isAjax()) {
  403. $search=[];
  404. $this->assign('search', implode(',',$search));
  405. $this->assign('columns', $this->recyclebinColumns);
  406. $this->assign('columnsType', $this->recyclebinColumnsType);
  407. return $this->fetch('common/recyclebin');
  408. }
  409. [$where, $order, $limit, $with] = $this->buildparams();
  410. $list = $this->model
  411. ->withJoin($with,'left')
  412. ->onlyTrashed()
  413. ->where($where)
  414. ->order($order)
  415. ->paginate($limit);
  416. $result = ['total' => $list->total(), 'rows' => $list->items()];
  417. return json($result);
  418. case 'restore':
  419. $ids=$this->request->param('ids');
  420. foreach ($ids as $id){
  421. $row=$this->model->onlyTrashed()->find($id);
  422. if($row){
  423. $row->restore();
  424. }
  425. }
  426. $this->success();
  427. case 'destroy':
  428. $ids=$this->request->param('ids');
  429. foreach ($ids as $id){
  430. $row=$this->model->onlyTrashed()->find($id);
  431. if($row){
  432. $row->force()->delete();
  433. }
  434. }
  435. $this->success();
  436. case 'restoreall':
  437. $this->model->onlyTrashed()->where('deletetime','<>',null)->update(['deletetime'=>null]);
  438. $this->success();
  439. case 'clear':
  440. Db::execute('delete from '.$this->model->getTable().' where deletetime is not null');
  441. $this->success();
  442. }
  443. }
  444. /**
  445. * 下载
  446. */
  447. #[Route('GET,JSON','download')]
  448. public function download()
  449. {
  450. if($this->request->isAjax()){
  451. $postdata=$this->request->post();
  452. if (!$this->downloadController){
  453. //获取table的列
  454. $listAction=explode('/',str_replace('.','/',$postdata['listAction']));
  455. $controller='\\app\\admin\\controller';
  456. for($i=0;$i<count($listAction)-1;$i++){
  457. if($i==count($listAction)-2){
  458. $listAction[$i]=ucfirst($listAction[$i]);
  459. }
  460. $controller.='\\'.$listAction[$i];
  461. }
  462. $this->downloadController=$controller;
  463. }
  464. if (!$this->downloadAction){
  465. $listAction=explode('/',str_replace('.','/',$postdata['listAction']));
  466. $action=$listAction[count($listAction)-1];
  467. if(strpos($action,'?')){
  468. $action=substr($action,0,strpos($action,'?'));
  469. }
  470. if(strpos($action,'-')!==false){
  471. $arrs=explode('-',$action);
  472. $action='';
  473. foreach ($arrs as $k=>$v){
  474. if($k>0){
  475. $action.=ucfirst($v);
  476. }else{
  477. $action.=$v;
  478. }
  479. }
  480. }
  481. $this->downloadAction=$action;
  482. }
  483. $obj=new ($this->downloadController)($this->request);
  484. $result=call_user_func_array([$obj,$this->downloadAction],[]);
  485. $list=$result->getData()['rows'];
  486. if($postdata['isTree']){
  487. $list=Tree::instance()->getTreeList($list);
  488. }
  489. if($this->callback){
  490. $callback=$this->callback;
  491. foreach ($list as $k=>$v){
  492. $list[$k]=$callback($v);
  493. }
  494. }
  495. //格式化
  496. $fields=[];
  497. foreach ($postdata['field'] as $v){
  498. $fields[$v['field']]=$v['title'];
  499. }
  500. //导出到excel
  501. $export=new Export();
  502. $export->setColumn($fields);
  503. $export->setData($list,$postdata['searchList']);
  504. $export->write();
  505. $file=date('YmdHis',time()).'.xlsx';
  506. $export->save(root_path().'runtime'.DS,$file);
  507. $this->success('',$file);
  508. }else{
  509. $file=$this->request->get('file');
  510. $filepath=root_path().'runtime'.DS.$file;
  511. if(!file_exists($filepath)){
  512. $this->error('没有找到文件');
  513. }
  514. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  515. header('Content-Disposition: attachment;filename="'.$file);
  516. header('Cache-Control: max-age=1');
  517. echo file_get_contents($filepath);
  518. unlink($filepath);
  519. exit;
  520. }
  521. }
  522. }