SystemCrud.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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(500056, [], ['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(500054);
  112. }
  113. if (!$columnField) {
  114. return app('json')->fail(500055);
  115. }
  116. $data['fromField'] = $fromField;
  117. $data['columnField'] = $columnField;
  118. if (!$data['tableName']) {
  119. return app('json')->fail(500045);
  120. }
  121. $this->services->createCrud($id, $data);
  122. return app('json')->success(500046);
  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(500045);
  138. }
  139. if (in_array($tableName, SystemCrudServices::NOT_CRUD_TABANAME)) {
  140. return app('json')->fail(500044);
  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(500043);
  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 = [];
  290. $deleteInfo = [];
  291. foreach ($info['field']['tableField'] as $key => $item) {
  292. if ($item['primaryKey']) {
  293. $keyInfo = $item;
  294. unset($info['field']['tableField'][$key]);
  295. }
  296. if ($item['field_type'] == 'addSoftDelete') {
  297. $deleteInfo = $item;
  298. unset($info['field']['tableField'][$key]);
  299. }
  300. }
  301. if ($keyInfo) {
  302. array_unshift($info['field']['tableField'], $keyInfo);
  303. }
  304. if ($deleteInfo) {
  305. array_push($info['field']['tableField'], $deleteInfo);
  306. }
  307. $info['field']['pid'] = (int)$info['field']['pid'];
  308. return app('json')->success(['file' => $data, 'crudInfo' => $info]);
  309. }
  310. /**
  311. * @param Request $request
  312. * @param SystemFileServices $service
  313. * @param $id
  314. * @return Response
  315. * @author 等风来
  316. * @email 136327134@qq.com
  317. * @date 2023/4/24
  318. */
  319. public function savefile(Request $request, SystemFileServices $service, $id)
  320. {
  321. $comment = $request->param('comment');
  322. $filepath = $request->param('filepath');
  323. if (empty($filepath) || !$id) {
  324. return app('json')->fail(410087);
  325. }
  326. $crudInfo = $this->services->get($id, ['make_path']);
  327. if (!$crudInfo) {
  328. return app('json')->fail('修改的CRUD文件不存在');
  329. }
  330. $makeFilepath = '';
  331. foreach ($crudInfo->make_path as $key => $item) {
  332. $path = $item;
  333. if (in_array($key, ['pages', 'router', 'api'])) {
  334. $item = Make::adminTemplatePath() . $item;
  335. } else {
  336. $item = app()->getRootPath() . $item;
  337. }
  338. if ($filepath == $path) {
  339. $makeFilepath = $item;
  340. break;
  341. }
  342. }
  343. if (!$makeFilepath || !in_array($filepath, $crudInfo->make_path)) {
  344. return app('json')->fail('您没有权限修改此文件');
  345. }
  346. $res = $service->savefile($makeFilepath, $comment);
  347. if ($res) {
  348. return app('json')->success(100000);
  349. } else {
  350. return app('json')->fail(100006);
  351. }
  352. }
  353. /**
  354. * 获取tree菜单
  355. * @return \think\Response
  356. * @author 等风来
  357. * @email 136327134@qq.com
  358. * @date 2023/4/11
  359. */
  360. public function getMenus()
  361. {
  362. return app('json')->success(app()->make(SystemMenusServices::class)
  363. ->getList(['auth_type' => 1, 'is_show' => 1], ['auth_type', 'pid', 'id', 'menu_name as label', 'id as value']));
  364. }
  365. /**
  366. * 获取创建表数据类型
  367. * @return \think\Response
  368. * @author 等风来
  369. * @email 136327134@qq.com
  370. * @date 2023/4/11
  371. */
  372. public function columnType()
  373. {
  374. return app('json')->success($this->services->getTabelRule());
  375. }
  376. /**
  377. * @param SystemMenusServices $services
  378. * @param $id
  379. * @return \think\Response
  380. * @author 等风来
  381. * @email 136327134@qq.com
  382. * @date 2023/4/11
  383. */
  384. public function delete(SystemMenusServices $services, $id)
  385. {
  386. if (!$id) {
  387. return app('json')->fail(500035);
  388. }
  389. $info = $this->services->get($id);
  390. if (!$info) {
  391. return app('json')->fail(500042);
  392. }
  393. $services->transaction(function () use ($services, $info) {
  394. if ($info->menu_ids) {
  395. $services->deleteMenus($info->menu_ids);
  396. }
  397. $info->delete();
  398. });
  399. if ($info->make_path) {
  400. try {
  401. foreach ($info->make_path as $key => $item) {
  402. if (in_array($key, ['pages', 'router', 'api'])) {
  403. $item = Make::adminTemplatePath() . $item;
  404. } else {
  405. $item = app()->getRootPath() . $item;
  406. }
  407. unlink($item);
  408. }
  409. } catch (\Throwable $e) {
  410. return app('json')->success(500041, [], ['message' => $e->getMessage()]);
  411. }
  412. }
  413. return app('json')->success(100002);
  414. }
  415. /**
  416. * 下载文件
  417. * @param $id
  418. * @return Response
  419. * @author 等风来
  420. * @email 136327134@qq.com
  421. * @date 2023/4/15
  422. */
  423. public function download($id)
  424. {
  425. if (!$id) {
  426. return app('json')->fail(500035);
  427. }
  428. $info = $this->services->get($id);
  429. if (!$info) {
  430. return app('json')->fail(500039);
  431. }
  432. $zipPath = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name);
  433. $zipName = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name) . '.zip';
  434. if (is_file($zipName)) {
  435. unlink($zipName);
  436. }
  437. $makePath = $info->make_path ?? [];
  438. foreach ($makePath as $key => $item) {
  439. if (in_array($key, ['pages', 'router', 'api'])) {
  440. $item = $zipPath . str_replace(dirname(app()->getRootPath()), '', Make::adminTemplatePath()) . $item;
  441. } else {
  442. $item = $zipPath . DS . $item;
  443. }
  444. $makePath[$key] = $item;
  445. }
  446. $routeName = 'crud/' . Str::snake($info->table_name);
  447. $column = $this->services->getColumnNamesList($info->table_name);
  448. $key = 'id';
  449. foreach ($column as $value) {
  450. if ($value['primaryKey']) {
  451. $key = $value['name'];
  452. break;
  453. }
  454. }
  455. $softDelete = false;
  456. foreach ((array)$info->field['tableField'] as $item) {
  457. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  458. $softDelete = true;
  459. break;
  460. }
  461. }
  462. $this->services->makeFile($info->table_name, $routeName, true, [
  463. 'menuName' => $info->name,
  464. 'key' => $key,
  465. 'softDelete' => $softDelete,
  466. 'fromField' => $info->field['fromField'] ?? [],
  467. 'columnField' => $info->field['columnField'] ?? [],
  468. ], $makePath, $zipPath);
  469. if (!extension_loaded('zip')) {
  470. return app('json')->fail(500040);
  471. }
  472. $fileService = new FileService();
  473. $fileService->addZip($zipPath, $zipName, app()->getRootPath() . 'backup');
  474. $key = md5($zipName);
  475. CacheService::set($key, [
  476. 'path' => $zipName,
  477. 'fileName' => Str::camel($info->table_name) . '.zip',
  478. ], 300);
  479. return app('json')->success(['download_url' => sys_config('site_url') . '/adminapi/download/' . $key]);
  480. }
  481. /**
  482. * 获取权限路由
  483. * @param $tableName
  484. * @return Response
  485. * @author 等风来
  486. * @email 136327134@qq.com
  487. * @date 2023/4/20
  488. */
  489. public function getRouteList($tableName)
  490. {
  491. $info = $this->services->get(['table_name' => $tableName]);
  492. if (!$info) {
  493. return app('json')->fail('crud详情查询失败');
  494. }
  495. $routeList = app()->make(SystemMenusServices::class)->getColumn([
  496. ['id', 'in', $info->menu_ids],
  497. ['auth_type', '=', 2]
  498. ], 'methods,api_url');
  499. $newRoute = [];
  500. foreach ($routeList as $item) {
  501. if ($item['methods'] == 'GET') {
  502. if (strstr($item['api_url'], 'create')) {
  503. $newRoute['create'] = $item['api_url'];
  504. } else if (strstr($item['api_url'], 'edit')) {
  505. $newRoute['edit'] = $item['api_url'];
  506. } else {
  507. $newRoute['index'] = $item['api_url'];
  508. }
  509. } else if ($item['methods'] == 'DELETE') {
  510. $newRoute['delete'] = $item['api_url'];
  511. }
  512. }
  513. $column = $this->services->getColumnNamesList($info->table_name);
  514. $key = 'id';
  515. foreach ($column as $value) {
  516. if ($value['primaryKey']) {
  517. $key = $value['name'];
  518. break;
  519. }
  520. }
  521. $columns = [
  522. [
  523. 'title' => 'ID',
  524. 'key' => $key,
  525. 'from_type' => '',
  526. ]
  527. ];
  528. foreach ((array)$info->field['tableField'] as $item) {
  529. if (isset($item['primaryKey']) && $item['primaryKey']) {
  530. continue;
  531. }
  532. if (isset($item['is_table']) && $item['is_table']) {
  533. if (in_array($item['from_type'], ['frameImageOne', 'frameImages'])) {
  534. $keyName = 'slot';
  535. } else {
  536. $keyName = 'key';
  537. }
  538. $columns[] = [
  539. 'title' => $item['table_name'] ?: $item['comment'],
  540. $keyName => $item['field'],
  541. 'from_type' => $item['from_type'],
  542. ];
  543. }
  544. }
  545. $route = $newRoute;
  546. return app('json')->success(compact('key', 'route', 'columns'));
  547. }
  548. /**
  549. * @return string
  550. * @author 等风来
  551. * @email 136327134@qq.com
  552. * @date 2023/4/14
  553. */
  554. public function npm()
  555. {
  556. $terminal = new Terminal();
  557. $adminPath = $terminal->adminTemplatePath();
  558. $adminPath = dirname($adminPath);
  559. try {
  560. $dir = $adminPath . DS . 'node_modules';
  561. if (!is_dir($dir)) {
  562. // $terminal->run('npm-install');
  563. }
  564. // $res = $terminal->run('npm-build');
  565. } catch (\Throwable $e) {
  566. $terminal->echoOutputFlag($e->getMessage());
  567. }
  568. if (!is_dir($adminPath . DS . 'dist')) {
  569. echo Response::create([
  570. 'message' => '打包失败',
  571. ], 'json')->getContent();
  572. }
  573. $build = public_path() . config('app.admin_prefix');
  574. // $this->app->make(FileService::class)->copyDir($adminPath . DS . 'dist', $build);
  575. // echo $res;
  576. }
  577. }