SystemCrud.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. $columnField[] = [
  84. 'field' => $item['field'],
  85. 'name' => $item['table_name'],
  86. 'type' => $item['from_type'],
  87. ];
  88. }
  89. //收集表单展示数据
  90. if ($item['from_type']) {
  91. $name = $item['table_name'] ?: $item['comment'];
  92. $option = $item['options'] ?? [];
  93. if (!$name) {
  94. return app('json')->fail(500056, [], ['field' => $item['field']]);
  95. }
  96. if (!$option && in_array($item['from_type'], ['radio', 'select'])) {
  97. return app('json')->fail('表单类型为radio或select时,options字段不能为空');
  98. }
  99. $fromField[] = [
  100. 'field' => $item['field'],
  101. 'type' => $item['from_type'],
  102. 'name' => $name,
  103. 'required' => $item['required'],
  104. 'option' => $option,
  105. ];
  106. }
  107. }
  108. if (!$fromField) {
  109. return app('json')->fail(500054);
  110. }
  111. if (!$columnField) {
  112. return app('json')->fail(500055);
  113. }
  114. $data['fromField'] = $fromField;
  115. $data['columnField'] = $columnField;
  116. if (!$data['tableName']) {
  117. return app('json')->fail(500045);
  118. }
  119. $this->services->createCrud($id, $data);
  120. return app('json')->success(500046);
  121. }
  122. /**
  123. * 获取创建文件的目录存放位置
  124. * @return \think\Response
  125. * @author 等风来
  126. * @email 136327134@qq.com
  127. * @date 2023/4/11
  128. */
  129. public function getFilePath()
  130. {
  131. [$tableName] = $this->request->postMore([
  132. ['tableName', ''],
  133. ], true);
  134. if (!$tableName) {
  135. return app('json')->fail(500045);
  136. }
  137. if (in_array($tableName, SystemCrudServices::NOT_CRUD_TABANAME)) {
  138. return app('json')->fail(500044);
  139. }
  140. $routeName = 'crud/' . Str::snake($tableName);
  141. $key = 'id';
  142. $tableField = [];
  143. $field = $this->services->getColumnNamesList($tableName);
  144. foreach ($field as $item) {
  145. if ($item['primaryKey']) {
  146. $key = $item['name'];
  147. }
  148. $tableField[] = [
  149. 'field' => $item['name'],
  150. 'field_type' => $item['type'],
  151. 'primaryKey' => (bool)$item['primaryKey'],
  152. 'default' => $item['default'],
  153. 'limit' => $item['limit'],
  154. 'comment' => $item['comment'],
  155. 'required' => false,
  156. 'is_table' => false,
  157. 'table_name' => '',
  158. 'from_type' => '',
  159. ];
  160. }
  161. $make = $this->services->makeFile($tableName, $routeName, false, [
  162. 'menuName' => '',
  163. 'key' => $key,
  164. 'fromField' => [],
  165. 'columnField' => [],
  166. ]);
  167. $makePath = [];
  168. foreach ($make as $k => $item) {
  169. $makePath[$k] = $item['path'];
  170. }
  171. return app('json')->success(compact('makePath', 'tableField'));
  172. }
  173. /**
  174. * @param $id
  175. * @return \think\Response
  176. * @author 等风来
  177. * @email 136327134@qq.com
  178. * @date 2023/4/12
  179. */
  180. public function read($id)
  181. {
  182. if (!$id) {
  183. return app('json')->fail(500035);
  184. }
  185. $info = $this->services->get($id);
  186. if (!$info) {
  187. return app('json')->fail(500043);
  188. }
  189. $routeName = 'crud/' . Str::snake($info->table_name);
  190. $column = $this->services->getColumnNamesList($info->table_name);
  191. $key = 'id';
  192. foreach ($column as $value) {
  193. if ($value['primaryKey']) {
  194. $key = $value['name'];
  195. break;
  196. }
  197. }
  198. $softDelete = false;
  199. foreach ((array)$info->field['tableField'] as $item) {
  200. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  201. $softDelete = true;
  202. break;
  203. }
  204. }
  205. $make = $this->services->makeFile($info->table_name, $routeName, false, [
  206. 'menuName' => $info->name,
  207. 'modelName' => $info->model_name,
  208. 'key' => $key,
  209. 'softDelete' => $softDelete,
  210. 'fromField' => $info->field['fromField'] ?? [],
  211. 'columnField' => $info->field['columnField'] ?? [],
  212. ]);
  213. $data = [];
  214. foreach ($make as $key => $item) {
  215. if (in_array($key, ['pages', 'router', 'api'])) {
  216. $path = Make::adminTemplatePath() . $item['path'];
  217. } else {
  218. $path = app()->getRootPath() . $item['path'];
  219. }
  220. $item['name'] = $item['path'];
  221. try {
  222. $item['content'] = file_get_contents($path, LOCK_EX);
  223. $data[$key] = $item;
  224. } catch (\Throwable $e) {
  225. }
  226. }
  227. //调整排序
  228. $makeData = [];
  229. $names = ['model', 'dao', 'service', 'controller', 'validate', 'router', 'api', 'pages'];
  230. foreach ($names as $name) {
  231. if (isset($data[$name])) {
  232. $makeData[] = $data[$name];
  233. }
  234. }
  235. $data = $makeData;
  236. $info = $info->toArray();
  237. //记录没有修改之前的数据
  238. foreach ((array)$info['field']['tableField'] as $key => $item) {
  239. $item['default_field'] = $item['field'];
  240. $item['default_limit'] = $item['limit'];
  241. $item['default_field_type'] = $item['field_type'];
  242. $item['default_comment'] = $item['comment'];
  243. $item['default_default'] = $item['default'];
  244. $item['is_table'] = !!$item['is_table'];
  245. $item['primaryKey'] = isset($item['primaryKey']) ? (int)$item['primaryKey'] : 0;
  246. $info['field']['tableField'][$key] = $item;
  247. }
  248. //对比数据库,是否有新增字段
  249. $newColumn = [];
  250. $fieldAll = array_column($info['field']['tableField'], 'field');
  251. foreach ($column as $value) {
  252. if (!in_array($value['name'], $fieldAll)) {
  253. $newColumn[] = [
  254. 'field' => $value['name'],
  255. 'field_type' => $value['type'],
  256. 'primaryKey' => $value['primaryKey'] ? 1 : 0,
  257. 'default' => $value['default'],
  258. 'limit' => $value['limit'],
  259. 'comment' => $value['comment'],
  260. 'required' => '',
  261. 'is_table' => '',
  262. 'table_name' => '',
  263. 'from_type' => '',
  264. 'default_field' => $value['name'],
  265. 'default_limit' => $value['limit'],
  266. 'default_field_type' => $value['type'],
  267. 'default_comment' => $value['comment'],
  268. 'default_default' => $value['default'],
  269. ];
  270. }
  271. }
  272. if ($newColumn) {
  273. $info['field']['tableField'] = array_merge($newColumn, $info['field']['tableField']);
  274. }
  275. $keyInfo = [];
  276. $deleteInfo = [];
  277. foreach ($info['field']['tableField'] as $key => $item) {
  278. if ($item['primaryKey']) {
  279. $keyInfo = $item;
  280. unset($info['field']['tableField'][$key]);
  281. }
  282. if ($item['field_type'] == 'addSoftDelete') {
  283. $deleteInfo = $item;
  284. unset($info['field']['tableField'][$key]);
  285. }
  286. }
  287. if ($keyInfo) {
  288. array_unshift($info['field']['tableField'], $keyInfo);
  289. }
  290. if ($deleteInfo) {
  291. array_push($info['field']['tableField'], $deleteInfo);
  292. }
  293. $info['field']['pid'] = (int)$info['field']['pid'];
  294. return app('json')->success(['file' => $data, 'crudInfo' => $info]);
  295. }
  296. /**
  297. * @param Request $request
  298. * @param SystemFileServices $service
  299. * @param $id
  300. * @return Response
  301. * @author 等风来
  302. * @email 136327134@qq.com
  303. * @date 2023/4/24
  304. */
  305. public function savefile(Request $request, SystemFileServices $service, $id)
  306. {
  307. $comment = $request->param('comment');
  308. $filepath = $request->param('filepath');
  309. if (empty($filepath) || !$id) {
  310. return app('json')->fail(410087);
  311. }
  312. $crudInfo = $this->services->get($id, ['make_path']);
  313. if (!$crudInfo) {
  314. return app('json')->fail('修改的CRUD文件不存在');
  315. }
  316. $makeFilepath = '';
  317. foreach ($crudInfo->make_path as $key => $item) {
  318. $path = $item;
  319. if (in_array($key, ['pages', 'router', 'api'])) {
  320. $item = Make::adminTemplatePath() . $item;
  321. } else {
  322. $item = app()->getRootPath() . $item;
  323. }
  324. if ($filepath == $path) {
  325. $makeFilepath = $item;
  326. break;
  327. }
  328. }
  329. if (!$makeFilepath || !in_array($filepath, $crudInfo->make_path)) {
  330. return app('json')->fail('您没有权限修改此文件');
  331. }
  332. $res = $service->savefile($makeFilepath, $comment);
  333. if ($res) {
  334. return app('json')->success(100000);
  335. } else {
  336. return app('json')->fail(100006);
  337. }
  338. }
  339. /**
  340. * 获取tree菜单
  341. * @return \think\Response
  342. * @author 等风来
  343. * @email 136327134@qq.com
  344. * @date 2023/4/11
  345. */
  346. public function getMenus()
  347. {
  348. return app('json')->success(app()->make(SystemMenusServices::class)
  349. ->getList(['auth_type' => 1, 'is_show' => 1], ['auth_type', 'pid', 'id', 'menu_name as label', 'id as value']));
  350. }
  351. /**
  352. * 获取创建表数据类型
  353. * @return \think\Response
  354. * @author 等风来
  355. * @email 136327134@qq.com
  356. * @date 2023/4/11
  357. */
  358. public function columnType()
  359. {
  360. return app('json')->success($this->services->getTabelRule());
  361. }
  362. /**
  363. * @param SystemMenusServices $services
  364. * @param $id
  365. * @return \think\Response
  366. * @author 等风来
  367. * @email 136327134@qq.com
  368. * @date 2023/4/11
  369. */
  370. public function delete(SystemMenusServices $services, $id)
  371. {
  372. if (!$id) {
  373. return app('json')->fail(500035);
  374. }
  375. $info = $this->services->get($id);
  376. if (!$info) {
  377. return app('json')->fail(500042);
  378. }
  379. $services->transaction(function () use ($services, $info) {
  380. if ($info->menu_ids) {
  381. $services->deleteMenus($info->menu_ids);
  382. }
  383. $info->delete();
  384. });
  385. if ($info->make_path) {
  386. try {
  387. foreach ($info->make_path as $key => $item) {
  388. if (in_array($key, ['pages', 'router', 'api'])) {
  389. $item = Make::adminTemplatePath() . $item;
  390. } else {
  391. $item = app()->getRootPath() . $item;
  392. }
  393. unlink($item);
  394. }
  395. } catch (\Throwable $e) {
  396. return app('json')->success(500041, [], ['message' => $e->getMessage()]);
  397. }
  398. }
  399. return app('json')->success(100002);
  400. }
  401. /**
  402. * 下载文件
  403. * @param $id
  404. * @return Response
  405. * @author 等风来
  406. * @email 136327134@qq.com
  407. * @date 2023/4/15
  408. */
  409. public function download($id)
  410. {
  411. if (!$id) {
  412. return app('json')->fail(500035);
  413. }
  414. $info = $this->services->get($id);
  415. if (!$info) {
  416. return app('json')->fail(500039);
  417. }
  418. $zipPath = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name);
  419. $zipName = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name) . '.zip';
  420. if (is_file($zipName)) {
  421. unlink($zipName);
  422. }
  423. $makePath = $info->make_path ?? [];
  424. foreach ($makePath as $key => $item) {
  425. if (in_array($key, ['pages', 'router', 'api'])) {
  426. $item = $zipPath . str_replace(dirname(app()->getRootPath()), '', Make::adminTemplatePath()) . $item;
  427. } else {
  428. $item = $zipPath . DS . $item;
  429. }
  430. $makePath[$key] = $item;
  431. }
  432. $routeName = 'crud/' . Str::snake($info->table_name);
  433. $column = $this->services->getColumnNamesList($info->table_name);
  434. $key = 'id';
  435. foreach ($column as $value) {
  436. if ($value['primaryKey']) {
  437. $key = $value['name'];
  438. break;
  439. }
  440. }
  441. $softDelete = false;
  442. foreach ((array)$info->field['tableField'] as $item) {
  443. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  444. $softDelete = true;
  445. break;
  446. }
  447. }
  448. $this->services->makeFile($info->table_name, $routeName, true, [
  449. 'menuName' => $info->name,
  450. 'key' => $key,
  451. 'softDelete' => $softDelete,
  452. 'fromField' => $info->field['fromField'] ?? [],
  453. 'columnField' => $info->field['columnField'] ?? [],
  454. ], $makePath, $zipPath);
  455. if (!extension_loaded('zip')) {
  456. return app('json')->fail(500040);
  457. }
  458. $fileService = new FileService();
  459. $fileService->addZip($zipPath, $zipName, app()->getRootPath() . 'backup');
  460. $key = md5($zipName);
  461. CacheService::set($key, [
  462. 'path' => $zipName,
  463. 'fileName' => Str::camel($info->table_name) . '.zip',
  464. ], 300);
  465. return app('json')->success(['download_url' => sys_config('site_url') . '/adminapi/download/' . $key]);
  466. }
  467. /**
  468. * 获取权限路由
  469. * @param $tableName
  470. * @return Response
  471. * @author 等风来
  472. * @email 136327134@qq.com
  473. * @date 2023/4/20
  474. */
  475. public function getRouteList($tableName)
  476. {
  477. $info = $this->services->get(['table_name' => $tableName]);
  478. if (!$info) {
  479. return app('json')->fail('crud详情查询失败');
  480. }
  481. $routeList = app()->make(SystemMenusServices::class)->getColumn([
  482. ['id', 'in', $info->menu_ids],
  483. ['auth_type', '=', 2]
  484. ], 'methods,api_url');
  485. $newRoute = [];
  486. foreach ($routeList as $item) {
  487. if ($item['methods'] == 'GET') {
  488. if (strstr($item['api_url'], 'create')) {
  489. $newRoute['create'] = $item['api_url'];
  490. } else if (strstr($item['api_url'], 'edit')) {
  491. $newRoute['edit'] = $item['api_url'];
  492. } else {
  493. $newRoute['index'] = $item['api_url'];
  494. }
  495. } else if ($item['methods'] == 'DELETE') {
  496. $newRoute['delete'] = $item['api_url'];
  497. }
  498. }
  499. $column = $this->services->getColumnNamesList($info->table_name);
  500. $key = 'id';
  501. foreach ($column as $value) {
  502. if ($value['primaryKey']) {
  503. $key = $value['name'];
  504. break;
  505. }
  506. }
  507. $columns = [
  508. [
  509. 'title' => 'ID',
  510. 'key' => $key,
  511. 'from_type' => '',
  512. ]
  513. ];
  514. foreach ((array)$info->field['tableField'] as $item) {
  515. if (isset($item['is_table']) && $item['is_table']) {
  516. if (in_array($item['from_type'], ['frameImageOne', 'frameImages'])) {
  517. $keyName = 'slot';
  518. } else {
  519. $keyName = 'key';
  520. }
  521. $columns[] = [
  522. 'title' => $item['table_name'] ?: $item['comment'],
  523. $keyName => $item['field'],
  524. 'from_type' => $item['from_type'],
  525. ];
  526. }
  527. }
  528. $route = $newRoute;
  529. return app('json')->success(compact('key', 'route', 'columns'));
  530. }
  531. /**
  532. * @return string
  533. * @author 等风来
  534. * @email 136327134@qq.com
  535. * @date 2023/4/14
  536. */
  537. public function npm()
  538. {
  539. $terminal = new Terminal();
  540. $adminPath = $terminal->adminTemplatePath();
  541. $adminPath = dirname($adminPath);
  542. try {
  543. $dir = $adminPath . DS . 'node_modules';
  544. if (!is_dir($dir)) {
  545. // $terminal->run('npm-install');
  546. }
  547. // $res = $terminal->run('npm-build');
  548. } catch (\Throwable $e) {
  549. $terminal->echoOutputFlag($e->getMessage());
  550. }
  551. if (!is_dir($adminPath . DS . 'dist')) {
  552. echo Response::create([
  553. 'message' => '打包失败',
  554. ], 'json')->getContent();
  555. }
  556. $build = public_path() . config('app.admin_prefix');
  557. // $this->app->make(FileService::class)->copyDir($adminPath . DS . 'dist', $build);
  558. // echo $res;
  559. }
  560. }