SystemCrud.php 20 KB

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