SystemCrud.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace app\adminapi\controller\v1\setting;
  14. use app\adminapi\controller\AuthController;
  15. use app\Request;
  16. use app\services\system\log\SystemFileServices;
  17. use app\services\system\SystemCrudServices;
  18. use app\services\system\SystemMenusServices;
  19. use crmeb\services\CacheService;
  20. use crmeb\services\crud\Make;
  21. use crmeb\services\FileService;
  22. use crmeb\utils\Terminal;
  23. use think\facade\App;
  24. use think\helper\Str;
  25. use think\Response;
  26. /**
  27. * Class SystemCrud
  28. * @author 等风来
  29. * @email 136327134@qq.com
  30. * @date 2023/4/6
  31. * @package app\adminapi\controller\v1\setting
  32. */
  33. class SystemCrud extends AuthController
  34. {
  35. /**
  36. * SystemCrud constructor.
  37. * @param App $app
  38. * @param SystemCrudServices $services
  39. */
  40. public function __construct(App $app, SystemCrudServices $services)
  41. {
  42. parent::__construct($app);
  43. $this->services = $services;
  44. }
  45. /**
  46. * @return \think\Response
  47. * @author 等风来
  48. * @email 136327134@qq.com
  49. * @date 2023/4/11
  50. */
  51. public function index()
  52. {
  53. return app('json')->success($this->services->getList());
  54. }
  55. /**
  56. * @return \think\Response
  57. * @author 等风来
  58. * @email 136327134@qq.com
  59. * @date 2023/4/11
  60. */
  61. public function save($id = 0)
  62. {
  63. $data = $this->request->postMore([
  64. ['pid', 0],//上级菜单id
  65. ['menuName', ''],//菜单名
  66. ['tableName', ''],//表名
  67. ['modelName', ''],//模块名称
  68. ['tableComment', ''],//表备注
  69. ['tableField', []],//表字段
  70. ['tableIndex', []],//索引
  71. ['filePath', []],//生成文件位置
  72. ['isTable', 0],//是否生成表
  73. ['deleteField', []],//删除的表字段
  74. ]);
  75. $fromField = $columnField = [];
  76. foreach ($data['tableField'] as $item) {
  77. //判断字段长度
  78. if (in_array($item['field_type'], ['datetime', 'timestamp', 'time', 'date', 'year']) && $item['limit'] > 6) {
  79. return app('json')->fail('字段' . $item['field'] . '长度不能大于6');
  80. }
  81. //收集列表展示数据
  82. if ($item['is_table'] && !in_array($item['field_type'], ['primaryKey', 'addSoftDelete', 'addSoftDelete'])) {
  83. if (isset($item['primaryKey']) && !$item['primaryKey']) {
  84. $columnField[] = [
  85. 'field' => $item['field'],
  86. 'name' => $item['table_name'],
  87. 'type' => $item['from_type'],
  88. ];
  89. }
  90. }
  91. //收集表单展示数据
  92. if ($item['from_type']) {
  93. $name = $item['table_name'] ?: $item['comment'];
  94. $option = $item['options'] ?? [];
  95. if (!$name) {
  96. return app('json')->fail(500048, [], ['field' => $item['field']]);
  97. }
  98. if (!$option && in_array($item['from_type'], ['radio', 'select'])) {
  99. return app('json')->fail('表单类型为radio或select时,options字段不能为空');
  100. }
  101. $fromField[] = [
  102. 'field' => $item['field'],
  103. 'type' => $item['from_type'],
  104. 'name' => $name,
  105. 'required' => $item['required'],
  106. 'option' => $option,
  107. ];
  108. }
  109. }
  110. if (!$fromField) {
  111. return app('json')->fail(500046);
  112. }
  113. if (!$columnField) {
  114. return app('json')->fail(500047);
  115. }
  116. $data['fromField'] = $fromField;
  117. $data['columnField'] = $columnField;
  118. if (!$data['tableName']) {
  119. return app('json')->fail(500042);
  120. }
  121. $this->services->createCrud($id, $data);
  122. return app('json')->success(500043);
  123. }
  124. /**
  125. * 获取创建文件的目录存放位置
  126. * @return \think\Response
  127. * @author 等风来
  128. * @email 136327134@qq.com
  129. * @date 2023/4/11
  130. */
  131. public function getFilePath()
  132. {
  133. [$tableName] = $this->request->postMore([
  134. ['tableName', ''],
  135. ], true);
  136. if (!$tableName) {
  137. return app('json')->fail(500042);
  138. }
  139. if (in_array($tableName, SystemCrudServices::NOT_CRUD_TABANAME)) {
  140. return app('json')->fail(500041);
  141. }
  142. $routeName = 'crud/' . Str::snake($tableName);
  143. $key = 'id';
  144. $tableField = [];
  145. $field = $this->services->getColumnNamesList($tableName);
  146. foreach ($field as $item) {
  147. if ($item['primaryKey']) {
  148. $key = $item['name'];
  149. }
  150. $tableField[] = [
  151. 'field' => $item['name'],
  152. 'field_type' => $item['type'],
  153. 'primaryKey' => (bool)$item['primaryKey'],
  154. 'default' => $item['default'],
  155. 'limit' => $item['limit'],
  156. 'comment' => $item['comment'],
  157. 'required' => false,
  158. 'is_table' => false,
  159. 'table_name' => '',
  160. 'from_type' => '',
  161. ];
  162. }
  163. $make = $this->services->makeFile($tableName, $routeName, false, [
  164. 'menuName' => '',
  165. 'key' => $key,
  166. 'fromField' => [],
  167. 'columnField' => [],
  168. ]);
  169. $makePath = [];
  170. foreach ($make as $k => $item) {
  171. $makePath[$k] = $item['path'];
  172. }
  173. return app('json')->success(compact('makePath', 'tableField'));
  174. }
  175. /**
  176. * @param $id
  177. * @return \think\Response
  178. * @author 等风来
  179. * @email 136327134@qq.com
  180. * @date 2023/4/12
  181. */
  182. public function read($id)
  183. {
  184. if (!$id) {
  185. return app('json')->fail(500035);
  186. }
  187. $info = $this->services->get($id);
  188. if (!$info) {
  189. return app('json')->fail(100026);
  190. }
  191. $routeName = 'crud/' . Str::snake($info->table_name);
  192. $column = $this->services->getColumnNamesList($info->table_name);
  193. $key = 'id';
  194. foreach ($column as $value) {
  195. if ($value['primaryKey']) {
  196. $key = $value['name'];
  197. break;
  198. }
  199. }
  200. $softDelete = false;
  201. foreach ((array)$info->field['tableField'] as $item) {
  202. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  203. $softDelete = true;
  204. break;
  205. }
  206. }
  207. $make = $this->services->makeFile($info->table_name, $routeName, false, [
  208. 'menuName' => $info->name,
  209. 'modelName' => $info->model_name,
  210. 'key' => $key,
  211. 'softDelete' => $softDelete,
  212. 'fromField' => $info->field['fromField'] ?? [],
  213. 'columnField' => $info->field['columnField'] ?? [],
  214. ]);
  215. $data = [];
  216. foreach ($make as $key => $item) {
  217. if (in_array($key, ['pages', 'router', 'api'])) {
  218. $path = Make::adminTemplatePath() . $item['path'];
  219. } else {
  220. $path = app()->getRootPath() . $item['path'];
  221. }
  222. $item['name'] = $item['path'];
  223. try {
  224. $item['content'] = file_get_contents($path, LOCK_EX);
  225. $data[$key] = $item;
  226. } catch (\Throwable $e) {
  227. }
  228. }
  229. //调整排序
  230. $makeData = [];
  231. $names = [
  232. 'controller' => '控制器',
  233. 'validate' => '验证器',
  234. 'service' => '逻辑层',
  235. 'dao' => '数据库操作',
  236. 'model' => '模型层',
  237. 'route' => '后端路由',
  238. 'router' => '前端路由',
  239. 'api' => '前端接口',
  240. 'pages' => '前端页面'
  241. ];
  242. foreach ($names as $name => $value) {
  243. if (isset($data[$name])) {
  244. $data[$name]['file_name'] = $value;
  245. $makeData[] = $data[$name];
  246. }
  247. }
  248. $data = $makeData;
  249. $info = $info->toArray();
  250. //记录没有修改之前的数据
  251. foreach ((array)$info['field']['tableField'] as $key => $item) {
  252. $item['default_field'] = $item['field'];
  253. $item['default_limit'] = $item['limit'];
  254. $item['default_field_type'] = $item['field_type'];
  255. $item['default_comment'] = $item['comment'];
  256. $item['default_default'] = $item['default'];
  257. $item['is_table'] = !!$item['is_table'];
  258. $item['required'] = !!$item['required'];
  259. $item['primaryKey'] = isset($item['primaryKey']) ? (int)$item['primaryKey'] : 0;
  260. $info['field']['tableField'][$key] = $item;
  261. }
  262. //对比数据库,是否有新增字段
  263. $newColumn = [];
  264. $fieldAll = array_column($info['field']['tableField'], 'field');
  265. foreach ($column as $value) {
  266. if (!in_array($value['name'], $fieldAll)) {
  267. $newColumn[] = [
  268. 'field' => $value['name'],
  269. 'field_type' => $value['type'],
  270. 'primaryKey' => $value['primaryKey'] ? 1 : 0,
  271. 'default' => $value['default'],
  272. 'limit' => $value['limit'],
  273. 'comment' => $value['comment'],
  274. 'required' => '',
  275. 'is_table' => '',
  276. 'table_name' => '',
  277. 'from_type' => '',
  278. 'default_field' => $value['name'],
  279. 'default_limit' => $value['limit'],
  280. 'default_field_type' => $value['type'],
  281. 'default_comment' => $value['comment'],
  282. 'default_default' => $value['default'],
  283. ];
  284. }
  285. }
  286. if ($newColumn) {
  287. $info['field']['tableField'] = array_merge($newColumn, $info['field']['tableField']);
  288. }
  289. $keyInfo = $deleteInfo = $createInfo = $updateInfo = [];
  290. $tableField = [];
  291. foreach ($info['field']['tableField'] as $item) {
  292. if ($item['primaryKey']) {
  293. $keyInfo = $item;
  294. continue;
  295. }
  296. if ($item['field_type'] == 'timestamp' && $item['field'] === 'delete_time') {
  297. $deleteInfo = $item;
  298. continue;
  299. }
  300. if ($item['field_type'] == 'timestamp' && $item['field'] === 'create_time') {
  301. $createInfo = $item;
  302. continue;
  303. }
  304. if ($item['field_type'] == 'timestamp' && $item['field'] === 'update_time') {
  305. $updateInfo = $item;
  306. continue;
  307. }
  308. $tableField[] = $item;
  309. }
  310. if ($keyInfo) {
  311. array_unshift($tableField, $keyInfo);
  312. }
  313. if ($createInfo) {
  314. array_push($tableField, $createInfo);
  315. }
  316. if ($updateInfo) {
  317. array_push($tableField, $updateInfo);
  318. }
  319. if ($deleteInfo) {
  320. array_push($tableField, $deleteInfo);
  321. }
  322. $info['field']['tableField'] = $tableField;
  323. $info['field']['pid'] = (int)$info['field']['pid'];
  324. return app('json')->success(['file' => $data, 'crudInfo' => $info]);
  325. }
  326. /**
  327. * @param Request $request
  328. * @param SystemFileServices $service
  329. * @param $id
  330. * @return Response
  331. * @author 等风来
  332. * @email 136327134@qq.com
  333. * @date 2023/4/24
  334. */
  335. public function savefile(Request $request, SystemFileServices $service, $id)
  336. {
  337. $comment = $request->param('comment');
  338. $filepath = $request->param('filepath');
  339. $pwd = $request->param('pwd');
  340. if ($pwd == '') {
  341. return app('json')->fail('请输入文件管理密码');
  342. }
  343. if (config('filesystem.password') != $pwd) {
  344. return app('json')->fail('文件管理密码错误');
  345. }
  346. if (empty($filepath) || !$id) {
  347. return app('json')->fail(410087);
  348. }
  349. $crudInfo = $this->services->get($id, ['make_path']);
  350. if (!$crudInfo) {
  351. return app('json')->fail('修改的CRUD文件不存在');
  352. }
  353. $makeFilepath = '';
  354. foreach ($crudInfo->make_path as $key => $item) {
  355. $path = $item;
  356. if (in_array($key, ['pages', 'router', 'api'])) {
  357. $item = Make::adminTemplatePath() . $item;
  358. } else {
  359. $item = app()->getRootPath() . $item;
  360. }
  361. if ($filepath == $path) {
  362. $makeFilepath = $item;
  363. break;
  364. }
  365. }
  366. if (!$makeFilepath || !in_array($filepath, $crudInfo->make_path)) {
  367. return app('json')->fail('您没有权限修改此文件');
  368. }
  369. $res = $service->savefile($makeFilepath, $comment);
  370. if ($res) {
  371. return app('json')->success(100000);
  372. } else {
  373. return app('json')->fail(100006);
  374. }
  375. }
  376. /**
  377. * 获取tree菜单
  378. * @return \think\Response
  379. * @author 等风来
  380. * @email 136327134@qq.com
  381. * @date 2023/4/11
  382. */
  383. public function getMenus()
  384. {
  385. return app('json')->success(app()->make(SystemMenusServices::class)
  386. ->getList(['auth_type' => 1, 'is_show' => 1], ['auth_type', 'pid', 'id', 'menu_name as label', 'id as value']));
  387. }
  388. /**
  389. * 获取创建表数据类型
  390. * @return \think\Response
  391. * @author 等风来
  392. * @email 136327134@qq.com
  393. * @date 2023/4/11
  394. */
  395. public function columnType()
  396. {
  397. return app('json')->success($this->services->getTabelRule());
  398. }
  399. /**
  400. * @param SystemMenusServices $services
  401. * @param $id
  402. * @return \think\Response
  403. * @author 等风来
  404. * @email 136327134@qq.com
  405. * @date 2023/4/11
  406. */
  407. public function delete(SystemMenusServices $services, $id)
  408. {
  409. if (!$id) {
  410. return app('json')->fail(500035);
  411. }
  412. $info = $this->services->get($id);
  413. if (!$info) {
  414. return app('json')->fail(100026);
  415. }
  416. $services->transaction(function () use ($services, $info) {
  417. if ($info->menu_ids) {
  418. $services->deleteMenus($info->menu_ids);
  419. }
  420. $info->delete();
  421. });
  422. if ($info->make_path) {
  423. $errorFile = [];
  424. foreach ($info->make_path as $key => $item) {
  425. if (in_array($key, ['pages', 'router', 'api'])) {
  426. $item = Make::adminTemplatePath() . $item;
  427. } else {
  428. $item = app()->getRootPath() . $item;
  429. }
  430. try {
  431. unlink($item);
  432. } catch (\Throwable $e) {
  433. $errorFile[] = $item;
  434. }
  435. }
  436. if ($errorFile) {
  437. return app('json')->success(500040, [], [
  438. 'message' => '文件:' . implode("\n", $errorFile) . ';无法被删除!'
  439. ]);
  440. }
  441. }
  442. return app('json')->success(100002);
  443. }
  444. /**
  445. * 下载文件
  446. * @param $id
  447. * @return Response
  448. * @author 等风来
  449. * @email 136327134@qq.com
  450. * @date 2023/4/15
  451. */
  452. public function download($id)
  453. {
  454. if (!$id) {
  455. return app('json')->fail(500035);
  456. }
  457. $info = $this->services->get($id);
  458. if (!$info) {
  459. return app('json')->fail(100026);
  460. }
  461. $zipPath = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name);
  462. $zipName = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name) . '.zip';
  463. if (is_file($zipName)) {
  464. unlink($zipName);
  465. }
  466. $makePath = $info->make_path ?? [];
  467. foreach ($makePath as $key => $item) {
  468. if (in_array($key, ['pages', 'router', 'api'])) {
  469. $item = $zipPath . str_replace(dirname(app()->getRootPath()), '', Make::adminTemplatePath()) . $item;
  470. } else {
  471. $item = $zipPath . DS . $item;
  472. }
  473. $makePath[$key] = $item;
  474. }
  475. $routeName = 'crud/' . Str::snake($info->table_name);
  476. $column = $this->services->getColumnNamesList($info->table_name);
  477. $key = 'id';
  478. foreach ($column as $value) {
  479. if ($value['primaryKey']) {
  480. $key = $value['name'];
  481. break;
  482. }
  483. }
  484. $softDelete = false;
  485. foreach ((array)$info->field['tableField'] as $item) {
  486. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  487. $softDelete = true;
  488. break;
  489. }
  490. }
  491. $this->services->makeFile($info->table_name, $routeName, true, [
  492. 'menuName' => $info->name,
  493. 'key' => $key,
  494. 'softDelete' => $softDelete,
  495. 'fromField' => $info->field['fromField'] ?? [],
  496. 'columnField' => $info->field['columnField'] ?? [],
  497. ], $makePath, $zipPath);
  498. if (!extension_loaded('zip')) {
  499. return app('json')->fail(500039);
  500. }
  501. $fileService = new FileService();
  502. $fileService->addZip($zipPath, $zipName, app()->getRootPath() . 'backup');
  503. $key = md5($zipName);
  504. CacheService::set($key, [
  505. 'path' => $zipName,
  506. 'fileName' => Str::camel($info->table_name) . '.zip',
  507. ], 300);
  508. return app('json')->success(['download_url' => sys_config('site_url') . '/adminapi/download/' . $key]);
  509. }
  510. /**
  511. * 获取权限路由
  512. * @param $tableName
  513. * @return Response
  514. * @author 等风来
  515. * @email 136327134@qq.com
  516. * @date 2023/4/20
  517. */
  518. public function getRouteList($tableName)
  519. {
  520. $info = $this->services->get(['table_name' => $tableName]);
  521. if (!$info) {
  522. return app('json')->fail('crud详情查询失败');
  523. }
  524. $routeList = app()->make(SystemMenusServices::class)->getColumn([
  525. ['id', 'in', $info->menu_ids],
  526. ['auth_type', '=', 2]
  527. ], 'methods,api_url');
  528. $newRoute = [];
  529. foreach ($routeList as $item) {
  530. if ($item['methods'] == 'GET') {
  531. if (strstr($item['api_url'], 'create')) {
  532. $newRoute['create'] = $item['api_url'];
  533. } else if (strstr($item['api_url'], 'edit')) {
  534. $newRoute['edit'] = $item['api_url'];
  535. } else {
  536. $newRoute['index'] = $item['api_url'];
  537. }
  538. } else if ($item['methods'] == 'DELETE') {
  539. $newRoute['delete'] = $item['api_url'];
  540. }
  541. }
  542. $column = $this->services->getColumnNamesList($info->table_name);
  543. $key = 'id';
  544. foreach ($column as $value) {
  545. if ($value['primaryKey']) {
  546. $key = $value['name'];
  547. break;
  548. }
  549. }
  550. $columns = [
  551. [
  552. 'title' => 'ID',
  553. 'key' => $key,
  554. 'from_type' => '',
  555. ]
  556. ];
  557. foreach ((array)$info->field['tableField'] as $item) {
  558. if (isset($item['primaryKey']) && $item['primaryKey']) {
  559. continue;
  560. }
  561. if (isset($item['is_table']) && $item['is_table']) {
  562. if (in_array($item['from_type'], ['frameImageOne', 'frameImages'])) {
  563. $keyName = 'slot';
  564. } else {
  565. $keyName = 'key';
  566. }
  567. $columns[] = [
  568. 'title' => $item['table_name'] ?: $item['comment'],
  569. $keyName => $item['field'],
  570. 'from_type' => $item['from_type'],
  571. ];
  572. }
  573. }
  574. $route = $newRoute;
  575. return app('json')->success(compact('key', 'route', 'columns'));
  576. }
  577. /**
  578. * @return string
  579. * @author 等风来
  580. * @email 136327134@qq.com
  581. * @date 2023/4/14
  582. */
  583. public function npm()
  584. {
  585. $terminal = new Terminal();
  586. $adminPath = $terminal->adminTemplatePath();
  587. $adminPath = dirname($adminPath);
  588. try {
  589. $dir = $adminPath . DS . 'node_modules';
  590. if (!is_dir($dir)) {
  591. // $terminal->run('npm-install');
  592. }
  593. // $res = $terminal->run('npm-build');
  594. } catch (\Throwable $e) {
  595. $terminal->echoOutputFlag($e->getMessage());
  596. }
  597. if (!is_dir($adminPath . DS . 'dist')) {
  598. echo Response::create([
  599. 'message' => '打包失败',
  600. ], 'json')->getContent();
  601. }
  602. $build = public_path() . config('app.admin_prefix');
  603. // $this->app->make(FileService::class)->copyDir($adminPath . DS . 'dist', $build);
  604. // echo $res;
  605. }
  606. }