SystemCrud.php 19 KB

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