SystemCrud.php 19 KB

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