FormService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. <?php
  2. namespace App\JsonRpc;
  3. use Hyperf\RpcServer\Annotation\RpcService;
  4. use App\Tools\Result;
  5. use App\Model\GlobalTable;
  6. use Hyperf\DbConnection\Db;
  7. use App\Model\GlobalTableField;
  8. use App\Model\GlobalTableFieldType;
  9. use App\Model\GlobalTableFieldValue;
  10. use App\Model\Website;
  11. use Hyperf\Di\Annotation\Inject;
  12. use Hyperf\Redis\Redis;
  13. #[RpcService(name: "FormService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  14. class FormService implements FormServiceInterface
  15. {
  16. #[Inject]
  17. protected Redis $redis;
  18. /**
  19. * 添加全局表单
  20. * @param array $data
  21. * @return array|mixed
  22. */
  23. public function addGlobalTable(array $data): array
  24. {
  25. // 过滤掉空值
  26. $data = array_filter($data, function($value) {
  27. return !empty($value);
  28. });
  29. // 检查是否已存在相同名称的记录
  30. $globalTable = GlobalTable::on('global')->where(['table'=> $data['table']])->first();
  31. if (empty($globalTable)) {
  32. $id = GlobalTable::on('global')->insertGetId($data);
  33. //给global库创建表 表名为$data['table'] 的值,并初始化一个字段id,类型为int,自增,主键,再初始化一个字段title,类型为varchar,长度为255
  34. Db::connection('global')->statement("CREATE TABLE IF NOT EXISTS `{$data['table']}` (
  35. `id` int(11) NOT NULL AUTO_INCREMENT,
  36. `title` varchar(255) DEFAULT NULL,
  37. `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
  38. `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  39. PRIMARY KEY (`id`)
  40. )");
  41. //给GlobalTableField表初始化数据
  42. GlobalTableField::on('global')->insert([
  43. [
  44. 'table_id' => $id,
  45. 'field_name' => 'id',
  46. 'title' => '编号',
  47. 'field_type' => '1',
  48. 'length' => 255,
  49. 'sort' => 0,
  50. 'is_check' => 1,
  51. 'admin_display' => 1,
  52. 'home_display' => 1,
  53. 'disable_del' => 1,
  54. ],
  55. [
  56. 'table_id' => $id,
  57. 'field_name' => 'title',
  58. 'title' => '标题',
  59. 'field_type' => '1',
  60. 'length' => 255,
  61. 'sort' => 0,
  62. 'is_check' => 1,
  63. 'admin_display' => 1,
  64. 'home_display' => 1,
  65. 'disable_del' => 1,
  66. ],
  67. [
  68. 'table_id' => $id,
  69. 'field_name' => 'updated_at',
  70. 'title' => '更新时间',
  71. 'field_type' => '1',
  72. 'length' => 255,
  73. 'sort' => 999,
  74. 'is_check' => 1,
  75. 'admin_display' => 1,
  76. 'home_display' => 0,
  77. 'disable_del' => 1,
  78. ],
  79. [
  80. 'table_id' => $id,
  81. 'field_name' => 'created_at',
  82. 'title' => '创建时间',
  83. 'field_type' => '1',
  84. 'length' => 255,
  85. 'sort' => 1000,
  86. 'is_check' => 1,
  87. 'admin_display' => 0,
  88. 'home_display' => 0,
  89. 'disable_del' => 1,
  90. ],
  91. ]);
  92. return Result::success('添加成功');
  93. }
  94. return Result::error('表单已存在');
  95. }
  96. /**
  97. * 获取全局表单列表
  98. * @param array $data
  99. * @return array
  100. */
  101. public function getGlobalTableList(array $data): array
  102. {
  103. try {
  104. // 构建查询
  105. $query = GlobalTable::query()
  106. ->when(!empty($data['website_id']), function($q) use ($data) {
  107. return $q->where('website_id', $data['website_id']);
  108. })
  109. ->when(!empty($data['name']), function($q) use ($data) {
  110. return $q->where('name', 'like', '%' . $data['name'] . '%');
  111. });
  112. // 分页参数
  113. $page = (int)($data['page'] ?? 1);
  114. $pageSize = (int)($data['pageSize'] ?? 10);
  115. // 先获取总数
  116. $total = $query->count();
  117. // 获取数据
  118. $list = $query->orderBy('updated_at', 'desc')
  119. ->offset(($page - 1) * $pageSize)
  120. ->limit($pageSize)
  121. ->get();
  122. // 如果没有数据,直接返回空结果
  123. if ($list->isEmpty()) {
  124. return Result::success([
  125. 'list' => [],
  126. 'total' => $total,
  127. 'page' => $page,
  128. 'pageSize' => $pageSize
  129. ]);
  130. }
  131. // 获取并合并 website 数据
  132. $websites = Db::connection('secondary')
  133. ->table('website')
  134. ->whereIn('id', $list->pluck('website_id'))
  135. ->pluck('website_name', 'id');
  136. // 合并数据并返回
  137. return Result::success([
  138. 'list' => $list->map(function($item) use ($websites) {
  139. $item->website_name = $websites[$item->website_id] ?? '';
  140. return $item;
  141. }),
  142. 'total' => $total,
  143. 'page' => $page,
  144. 'pageSize' => $pageSize
  145. ]);
  146. } catch (\Throwable $e) {
  147. return Result::error('查询失败:' . $e->getMessage());
  148. }
  149. }
  150. /**
  151. * 获取全局表单
  152. * @param array $data
  153. * @return array
  154. */
  155. public function getGlobalTable(array $data): array
  156. {
  157. $globalTable = GlobalTable::where('id',$data['id'])->first();
  158. return Result::success($globalTable);
  159. }
  160. /**
  161. * 修改全局表单
  162. * @param array $data
  163. * @return array
  164. */
  165. public function upGlobalTable(array $data): array
  166. {
  167. $globalTable = GlobalTable::where('id',$data['id'])->first();
  168. if(empty($globalTable)){
  169. return Result::error('表单不存在');
  170. }
  171. $data = array_filter($data,function($value){
  172. return $value !== null;
  173. });
  174. GlobalTable::where(['id'=>$data['id']])->update($data);
  175. return Result::success('修改成功');
  176. }
  177. /**
  178. * 删除全局表单
  179. * @param array $data
  180. * @return array
  181. */
  182. public function delGlobalTable(array $data): array
  183. {
  184. $globalTable = GlobalTable::where('id', $data['id'])->first();
  185. if(empty($globalTable)){
  186. return Result::error('表单不存在');
  187. }
  188. //删除global库的表
  189. Db::connection('global')->statement("DROP TABLE IF EXISTS `{$globalTable->table}`");
  190. //删除GlobalTableField表中table_id为$data['id']的数据
  191. GlobalTableField::where('table_id', $data['id'])->delete();
  192. GlobalTable::where('id', $data['id'])->delete();
  193. return Result::success('删除成功');
  194. }
  195. /**
  196. * 获取表单字段列表
  197. * @param array $data
  198. * @return array
  199. */
  200. public function getGlobalTableFieldList(array $data): array
  201. {
  202. $fields = GlobalTableField::from('global_table_field as a')
  203. ->join('global_table_field_type as b', 'a.field_type', '=', 'b.id')
  204. ->where('a.table_id', $data['id'])
  205. ->whereNotIn('a.field_name',['id','created_at','updated_at'])
  206. ->orderBy('a.sort', 'asc')
  207. ->select(
  208. // global_table_field 所有字段
  209. 'a.*',
  210. // global_table_field_type 字段
  211. 'b.type_name',
  212. 'b.type_name_alias',
  213. 'b.field_type as type_definition'
  214. )
  215. ->get();
  216. return Result::success($fields);
  217. }
  218. /**
  219. * 获取表单字段
  220. * @param array $data
  221. * @return array
  222. */
  223. public function getGlobalTableField(array $data): array
  224. {
  225. $globalTableField = GlobalTableField::where('id',$data['id'])->first();
  226. return Result::success($globalTableField);
  227. }
  228. /**
  229. * 添加表单字段
  230. * @param array $data
  231. * @return array
  232. * @throws \Throwable
  233. */
  234. public function addGlobalTableField(array $data): array
  235. {
  236. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  237. if(empty($globalTable)){
  238. return Result::error('表单不存在');
  239. }
  240. //检查是否已存在相同名称的记录
  241. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id'],'field_name'=>$data['field_name']])->first();
  242. if(!empty($globalTableField)){
  243. return Result::error('字段已存在');
  244. }
  245. // 检查表中是否已存在该列
  246. try {
  247. $columns = Db::connection('global')->select("SHOW COLUMNS FROM `{$globalTable->table}`");
  248. $columnNames = array_column($columns, 'Field');
  249. if (in_array($data['field_name'], $columnNames)) {
  250. return Result::error('字段名已存在于数据表中');
  251. }
  252. } catch (\Throwable $e) {
  253. return Result::error('检查字段是否存在时出错:' . $e->getMessage());
  254. }
  255. $globalTableFieldTypeInfo = GlobalTableFieldType::where('id',$data['field_type'])->first();
  256. //给global库的表添加字段
  257. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` ADD COLUMN `{$data['field_name']}` {$globalTableFieldTypeInfo['field_type']}({$data['length']}) COMMENT '{$data['title']}'");
  258. //给GlobalTableField表添加数据
  259. GlobalTableField::create($data);
  260. return Result::success('添加成功');
  261. }
  262. /**
  263. * 修改表单字段
  264. * @param array $data
  265. * @return array
  266. * @throws \Throwable
  267. */
  268. public function upGlobalTableField(array $data): array
  269. {
  270. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  271. if(empty($globalTable)){
  272. return Result::error('表单不存在');
  273. }
  274. //检查是否已存在相同名称的记录
  275. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id'],'field_name'=>$data['field_name']])->first();
  276. if(!empty($globalTableField) && $globalTableField->id != $data['id']){
  277. return Result::error('字段已存在');
  278. }
  279. $globalTableFieldTypeInfo = GlobalTableFieldType::where('id',$data['field_type'])->first();
  280. //给global库的表修改字段
  281. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` CHANGE COLUMN `{$data['field_name']}` `{$data['field_name']}` {$globalTableFieldTypeInfo['field_type']}({$data['length']}) COMMENT '{$data['title']}'");
  282. //给GlobalTableField表修改数据
  283. GlobalTableField::where('id',$data['id'])->update($data);
  284. return Result::success('修改成功');
  285. }
  286. /**
  287. * 删除表单字段
  288. * @param array $data
  289. * @return array
  290. * @throws \Throwable
  291. */
  292. public function delGlobalTableField(array $data): array
  293. {
  294. $tableFieldInfo = GlobalTableField::where('id',$data['id'])->first();
  295. if(empty($tableFieldInfo)){
  296. return Result::error('字段不存在');
  297. }
  298. $globalTable = GlobalTable::where('id',$tableFieldInfo['table_id'])->first();
  299. if(empty($globalTable)){
  300. return Result::error('表单不存在');
  301. }
  302. //给global库的表删除字段
  303. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` DROP COLUMN `{$tableFieldInfo['field_name']}`");
  304. //给GlobalTableField表删除数据
  305. GlobalTableField::where('id',$data['id'])->delete();
  306. return Result::success('删除成功');
  307. }
  308. /**
  309. * 获取自定义生成表里面的数据
  310. */
  311. public function getGlobalTableData(array $data): array
  312. {
  313. try {
  314. //查询global库的表GlobalTableField模型中table_id为$data['id']的数据条件为admin_display=1的数据
  315. $globalTableFields = GlobalTableField::where(['table_id'=>$data['id'],'admin_display'=>1])->orderBy('sort','asc')->get();
  316. $globalTableFields->transform(function ($field) {
  317. $optionValue = [];
  318. $optionStr = trim((string) $field->option);
  319. if (!empty($optionStr)) {
  320. $options = explode("\n", $optionStr);
  321. foreach ($options as $option) {
  322. $parts = explode('|', $option);
  323. if (count($parts) === 2) {
  324. $optionValue[$parts[1]] = $parts[0];
  325. }
  326. }
  327. }
  328. $field->option_value = $optionValue;
  329. return $field;
  330. });
  331. //查询global库的表GlobalTable模型中id为$data['id']的数据
  332. $globalTable = GlobalTable::where('id',$data['id'])->first();
  333. if(empty($globalTable)){
  334. return Result::error('表单不存在');
  335. }
  336. // 构建查询
  337. $query = Db::connection('global')->table($globalTable->table);
  338. // 添加title模糊搜索
  339. if (!empty($data['title'])) {
  340. $query->where('title', 'like', '%' . $data['title'] . '%');
  341. }
  342. // 分页参数
  343. $page = (int)($data['page'] ?? 1);
  344. $pageSize = (int)($data['pageSize'] ?? 10);
  345. // 先获取总数
  346. $total = $query->count();
  347. // 获取分页数据
  348. $list = $query->select($globalTableFields->pluck('field_name')->toArray())
  349. ->orderBy('id', 'desc')
  350. ->offset(($page - 1) * $pageSize)
  351. ->limit($pageSize)
  352. ->get();
  353. // 转换字符串数组为实际数组
  354. $list->transform(function ($item) use ($globalTableFields) {
  355. foreach ($globalTableFields as $field) {
  356. $fieldName = $field->field_name;
  357. if (isset($item->$fieldName) && is_string($item->$fieldName)) {
  358. // 尝试解析JSON格式的字符串
  359. $decoded = json_decode($item->$fieldName, true);
  360. if (json_last_error() === JSON_ERROR_NONE) {
  361. $item->$fieldName = $decoded;
  362. }
  363. // 如果是简单的逗号分隔字符串,也可以转换为数组
  364. elseif (strpos($item->$fieldName, ',') !== false) {
  365. $item->$fieldName = array_map('trim', explode(',', $item->$fieldName));
  366. }
  367. }
  368. }
  369. return $item;
  370. });
  371. return Result::success([
  372. 'tableFields' => $globalTableFields,
  373. 'list' => $list,
  374. 'total' => $total,
  375. 'page' => $page,
  376. 'pageSize' => $pageSize
  377. ]);
  378. } catch (\Throwable $e) {
  379. return Result::error('查询失败:' . $e->getMessage());
  380. }
  381. }
  382. /**
  383. * 获取字段类型列表
  384. */
  385. public function getGlobalTableFieldTypeList(array $data): array
  386. {
  387. try {
  388. $list = Db::connection('global')->table("global_table_field_type")->get();
  389. return Result::success($list);
  390. }catch (\Throwable $e){
  391. return Result::error('查询失败:' . $e->getMessage());
  392. }
  393. }
  394. /**
  395. * 删除自定义表里面的某一条数据
  396. */
  397. public function delGlobalTableData(array $data): array
  398. {
  399. try {
  400. //查询global库的表GlobalTable模型中id为$data['id']的数据
  401. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  402. if(empty($globalTable)){
  403. return Result::error('表单不存在');
  404. }
  405. // 构建查询
  406. $query = Db::connection('global')->table($globalTable->table);
  407. $query->where('id',$data['id']);
  408. $query->delete();
  409. return Result::success('删除成功');
  410. }catch (\Throwable $e){
  411. return Result::error('删除失败:' . $e->getMessage());
  412. }
  413. }
  414. /**
  415. * 修改自定义表里面的某一条数据
  416. */
  417. public function updateGlobalTableData(array $data): array
  418. {
  419. try {
  420. $globalTable = GlobalTable::where('id', $data['table_id'])->first();
  421. if (empty($globalTable)) {
  422. return Result::error('表单不存在');
  423. }
  424. unset($data['table_id']);
  425. // 转换数组字段为字符串
  426. $data = array_map(function ($value) {
  427. if (is_array($value)) {
  428. return json_encode($value, JSON_UNESCAPED_UNICODE);
  429. }
  430. return $value;
  431. }, $data);
  432. $query = Db::connection('global')->table($globalTable->table);
  433. $query->where('id', $data['id'])->update($data);
  434. return Result::success('修改成功');
  435. } catch (\Throwable $e) {
  436. return Result::error('修改失败:' . $e->getMessage());
  437. }
  438. }
  439. /**
  440. * 查看自定义表里面的某条数据
  441. */
  442. public function getGlobalTableDataById(array $data): array
  443. {
  444. try {
  445. //查询
  446. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  447. if(empty($globalTable)){
  448. return Result::error('表单不存在');
  449. }
  450. $query = Db::connection('global')->table($globalTable->table);
  451. $query->where('id',$data['id']);
  452. $dataInfo = $query->first();
  453. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id']])->get();
  454. $globalTableField->transform(function ($field) {
  455. $optionValue = [];
  456. $optionStr = trim((string) $field->option);
  457. if (!empty($optionStr)) {
  458. $options = explode("\n", $optionStr);
  459. foreach ($options as $option) {
  460. $parts = explode('|', $option);
  461. if (count($parts) === 2) {
  462. $optionValue[$parts[1]] = $parts[0];
  463. }
  464. }
  465. }
  466. $field->option_value = $optionValue;
  467. return $field;
  468. });
  469. $return = [
  470. 'data'=>$dataInfo,
  471. 'tableFields'=>$globalTableField->toArray(),
  472. ];
  473. return Result::success($return);
  474. }catch (\Throwable $e){
  475. return Result::error('查询失败:' . $e->getMessage());
  476. }
  477. }
  478. /**
  479. * 查询网站下表单自定义字段
  480. */
  481. public function getWebGlobalTableFieldList(array $data): array
  482. {
  483. try {
  484. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  485. $websiteInfo = Website::where('id',$globalTable['website_id'])->first();
  486. if(empty($websiteInfo)){
  487. return Result::error('网站不存在');
  488. }else{
  489. $globalTable['website_name'] = $websiteInfo['website_name'];
  490. $globalTable['suffix'] = $websiteInfo['suffix'];
  491. }
  492. $fields = GlobalTableField::from('global_table_field as a')
  493. ->join('global_table_field_type as b', 'a.field_type', '=', 'b.id')
  494. ->where('a.table_id', $data['table_id'])
  495. ->where('a.field_name',"<>",'id')
  496. ->where('a.home_display', 1)
  497. ->orderBy('a.sort', 'asc')
  498. ->select(
  499. // global_table_field 所有字段
  500. 'a.*',
  501. // global_table_field_type 字段
  502. 'b.type_name',
  503. 'b.type_name_alias',
  504. 'b.field_type as type_definition'
  505. )
  506. ->get();
  507. $fields->transform(function ($field) {
  508. $optionValue = [];
  509. $optionStr = trim((string) $field->option);
  510. if (!empty($optionStr)) {
  511. $options = explode("\n", $optionStr);
  512. foreach ($options as $option) {
  513. $parts = explode('|', $option);
  514. if (count($parts) === 2) {
  515. $optionValue[$parts[1]] = $parts[0];
  516. }
  517. }
  518. }
  519. $field->option_value = $optionValue;
  520. return $field;
  521. });
  522. $config = new \EasySwoole\VerifyCode\Config();
  523. $code = new \EasySwoole\VerifyCode\VerifyCode($config);
  524. $img_code = '';
  525. $characters = '0123456789';
  526. $charLength = strlen($characters);
  527. for ($i = 0; $i < 4; $i++) {
  528. $img_code .= $characters[rand(0, $charLength - 1)];
  529. }
  530. //重写验证码
  531. $result = $code->DrawCode((string)$img_code);
  532. $img_code = $result->getImageCode();
  533. var_dump("验证码:",$img_code);
  534. $code_uniqid = uniqid("code");
  535. //写入缓存 用于其他方法验证 并且设置过期时间
  536. $this->redis->set($code_uniqid,$img_code,60000);
  537. $rep = [
  538. 'fields' => $fields,
  539. 'table'=>$globalTable,
  540. ];
  541. if($globalTable->is_code){
  542. $rep['code']['code_uniqid'] = $code_uniqid;
  543. $rep['code']['img'] = $result->getImageBase64();
  544. }
  545. return Result::success($rep);
  546. }catch (\Throwable $e){
  547. return Result::error('查询失败:' . $e->getMessage());
  548. }
  549. }
  550. /**
  551. * web端创建数据
  552. * @param array $data
  553. * @return array
  554. */
  555. public function addWebGlobalTableData(array $data): array
  556. {
  557. try {
  558. $globalTable = GlobalTable::where('id',$data['otherData']['table_id'])->first();
  559. if($globalTable->is_code){
  560. if(empty($data['otherData']['code'])){
  561. return Result::error('请输入验证码');
  562. }
  563. $code = $this->redis->get($data['otherData']['code_uniqid']);
  564. if(empty($code)){
  565. return Result::error('验证码已过期');
  566. }
  567. if($data['otherData']['code'] != $code){
  568. return Result::error('验证码错误');
  569. }
  570. }
  571. if(empty($globalTable)){
  572. return Result::error('表单不存在');
  573. }
  574. $query = Db::connection('global')->table($globalTable->table);
  575. $data['data'] = array_map(function ($value) {
  576. if (is_array($value)) {
  577. return json_encode($value, JSON_UNESCAPED_UNICODE);
  578. }
  579. return $value;
  580. }, $data['data']);
  581. $query->insert($data['data']);
  582. return Result::success([]);
  583. }catch (\Throwable $e){
  584. return Result::error('添加失败:' . $e->getMessage());
  585. }
  586. }
  587. }