代码下载接口

This commit is contained in:
2025-05-13 13:16:59 +08:00
parent 636fc411d2
commit a764794a5f
8 changed files with 206 additions and 183 deletions

View File

@@ -86,4 +86,18 @@ class AdminController extends BaseController
'获取成功' '获取成功'
); );
} }
/**
* 获取菜单列表
* @Method GET
* @return JsonResponse
* @throws Exception
*/
public function codes(): JsonResponse
{
return jok(
[],
'获取成功'
);
}
} }

View File

@@ -19,23 +19,31 @@ class CodeGenerationController extends BaseController
public function generation() public function generation()
{ {
// $this->insertField = [ $this->insertField = [
// 'class_name', 'class_name',
// 'class_comment', 'class_comment',
// 'sort', 'sort',
// 'icon', 'icon',
// 'pid', 'pid',
// 'field', 'field',
// ]; ];
//
// $params = $this->checkRequiredFields(request()->post());
$params = json_decode('{"class_name":"testTemplate","class_comment":"测试代码生成","sort":"9999999","icon":"ant-design:api-outlined","pid":14,"field":[{"name":"name","type":"VARCHAR","type_number":"32","default":null,"comment":"测试名称","null":true,"formShow":true,"tableShow":true,"search":true,"searchValue":"like","formType":"VbenInput"},{"name":"test_name_1","type":"VARCHAR","type_number":"32","default":null,"comment":"测试名称","null":true,"formShow":true,"tableShow":true,"search":true,"searchValue":"like","formType":"VbenInput"}]}', true); $params = $this->checkRequiredFields(request()->post());
// ds($params);
return $this->service->generate($params); return jok(
// return jok( $this->service->generate($params),
// $this->service->generate([]) '生成成功!'
// ); );
}
public function download()
{
// $id = request()->post('id');
$id = request()->get('id');
if (!$id) {
return jerr('参数错误!');
}
return $this->service->download($id);
} }
} }

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasOne;
class CodeGenerationModel extends BaseModel
{
protected $table = 'code_generation';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

View File

@@ -2,7 +2,9 @@
namespace App\Service\core; namespace App\Service\core;
use App\Models\CodeGenerationModel;
use App\Service\common\UtilsService; use App\Service\common\UtilsService;
use App\Service\MenuService;
use Exception; use Exception;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -75,10 +77,20 @@ class CodeGenerationService
return self::$_instance[$name]; return self::$_instance[$name];
} }
public function download($id)
{
$model = CodeGenerationModel::find($id);
if (!$model) {
$this->utils->errorThrow('文件不存在');
}
// 返回下载 $path 文件流
return response()->download($model['path'], $model['file_name'], ['Content-Type' => 'application/zip']);
}
/** /**
* 创建临时文件夹,复制模板文件,压缩并返回文件流 * 创建临时文件夹,复制模板文件,压缩并返回文件流
*/ */
public function download(): BinaryFileResponse|JsonResponse public function downloadUrl()
{ {
try { try {
// 将后端模板文件内容写入临时目录中 // 将后端模板文件内容写入临时目录中
@@ -98,8 +110,15 @@ class CodeGenerationService
// 执行文件压缩 // 执行文件压缩
$zip->zip($zipFile, $path); $zip->zip($zipFile, $path);
// 返回下载 $path 文件流 CodeGenerationModel::create([
return response()->download($zipFile, "{$this->classComment}-{$this->uniqid}.zip", ['Content-Type' => 'application/zip']); 'title' => $this->classComment,
'file_name' => "{$this->classComment}-{$this->uniqid}.zip",
'path' => $zipFile,
'params' => json_encode($this->param),
'created_at' => time(),
'updated_at' => time(),
]);
return $zipFile;
} catch (\Exception $e) { } catch (\Exception $e) {
return response()->json([ return response()->json([
'error' => '生成模板文件失败', 'error' => '生成模板文件失败',
@@ -134,9 +153,10 @@ class CodeGenerationService
* 代码生成主逻辑 * 代码生成主逻辑
* *
* @param $params * @param $params
* @return mixed
* @throws Exception * @throws Exception
*/ */
public function generate($params) public function generate($params): mixed
{ {
$this->param = $params; $this->param = $params;
DB::beginTransaction(); DB::beginTransaction();
@@ -157,24 +177,19 @@ class CodeGenerationService
$this->querySql(); $this->querySql();
// 生成视图 // 生成视图
$this->genViews(); $this->genViews();
// // 生成菜单 // 生成菜单
// $this->genMenu(); $this->genMenu();
return $this->download();
// // 生成导出层
// $this->genExport();
// // 生成导入层
// $this->genImport();
} catch (Exception $e) { } catch (Exception $e) {
DB::rollBack(); DB::rollBack();
ds([ // ds([
'error' => '生成代码失败', // 'error' => '生成代码失败',
'message' => $e->getMessage(), // 'message' => $e->getMessage(),
'line' => $e->getLine(), // 'line' => $e->getLine(),
'file' => $e->getFile(), // 'file' => $e->getFile(),
]); // ]);
$this->utils->errorThrow($e->getMessage()); $this->utils->errorThrow($e->getMessage());
} }
return $this->download(); return $this->downloadUrl();
} }
@@ -240,7 +255,7 @@ class CodeGenerationService
$apiPath = app_path('../routes/api.php'); $apiPath = app_path('../routes/api.php');
$apiFile = file_get_contents($apiPath, 'y'); $apiFile = file_get_contents($apiPath, 'y');
$newApi = $newApi =
"'{$this->dashCase}' => \App\Http\Controllers\Api\CodeGeneration\\{$this->upperCamelCase}Controller::class, // {$this->classComment}} \r\n // 需要登录的路由生成地址"; "'{$this->dashCase}' => \App\Http\Controllers\Api\CodeGeneration\\{$this->upperCamelCase}Controller::class, // {$this->classComment} \r\n // 需要登录的路由生成地址";
$updateNewFile = str_replace('// 需要登录的路由生成地址', $newApi, $apiFile); $updateNewFile = str_replace('// 需要登录的路由生成地址', $newApi, $apiFile);
@@ -289,35 +304,7 @@ class CodeGenerationService
'model' 'model'
); );
} }
//
// /**
// * 生成导出层文件
// * @return void
// */
// private function genExport(): void
// {
// $this->strReplaceTmp(
// $this->basePath . $this->tmpPath['server']['export'],
// $this->basePath . $this->newPath['server']['export'],
// 'server',
// 'export'
// );
// }
//
// /**
// * 生成导入层文件
// * @return void
// */
// private function genImport(): void
// {
// $this->strReplaceTmp(
// $this->basePath . $this->tmpPath['server']['import'],
// $this->basePath . $this->newPath['server']['import'],
// 'server',
// 'import'
// );
// }
//
/** /**
* 生成前端部分文件 * 生成前端部分文件
* @return void * @return void
@@ -343,16 +330,24 @@ class CodeGenerationService
} }
} }
// /** /**
// * 生成菜单/授权 * 生成菜单/授权
// * *
// * @return void * @return void
// * @throws Exception * @throws Exception
// */ */
// private function genMenu(): void private function genMenu(): void
// { {
// RoleService::getInstance()->createRoleMenuRelation(UsersEnum::ADMIN_ID, MenuService::getInstance()->save($this->menu)); MenuService::getInstance()->create([
// } 'title' => $this->classComment,
'icon' => $this->param['icon']?? '',
'name' => $this->upperCamelCase,
'path' => "/{$this->dashCase}",
'component' => "/my-gen/{$this->dashCase}/index",
'pid' => $this->param['pid'],
'sort' => $this->param['sort'],
]);
}
/** /**
* 模板内容替换 * 模板内容替换
@@ -425,15 +420,15 @@ class CodeGenerationService
} }
// 设置表单字段 // 设置表单字段
if ($item['formShow']) { if ($item['formShow']) {
$isNull = $item['null'] == 1 ? 'required' : ''; $isNull = $item['null'] == 1 ? "'required'" : "''";
$this->insertField .= !empty($this->insertField) ? '","' . $item['name'] : $item['name']; $this->insertField .= !empty($this->insertField) ? '","' . $item['name'] : $item['name'];
$this->updateField .= !empty($this->updateField) ? '","' . $item['name'] : 'id","' . $item['name']; $this->updateField .= !empty($this->updateField) ? '","' . $item['name'] : 'id","' . $item['name'];
$this->viewForm .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n rules: " . $isNull . ",\n },\n "; $this->viewForm .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n rules: " . $isNull . ",\n },\n";
} }
// 设置搜索字段 // 设置搜索字段
if ($item['search']) { if ($item['search']) {
$this->viewSearch .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n },\n "; $this->viewSearch .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n },\n ";
$this->searchField .= !empty($this->searchField) ? ',' . $item['name'] . '\' => \'' . $item['searchValue'] : $item['name'] . '\' => \'' . $item['searchValue']; $this->searchField .= !empty($this->searchField) ? "','" . $item['name'] . '\' => \'' . $item['searchValue'] : $item['name'] . '\' => \'' . $item['searchValue'];
} }
// // 设置导出字段 // // 设置导出字段
// $this->exportField .= !empty($this->exportField) ? ',"' . $item['comment'] . '"' : '"' . $item['comment'] . '"'; // $this->exportField .= !empty($this->exportField) ? ',"' . $item['comment'] . '"' : '"' . $item['comment'] . '"';
@@ -441,7 +436,7 @@ class CodeGenerationService
// // 设置导入字段 // // 设置导入字段
// $this->importField .= "'" . $item['name'] . "' => \$row['" . $item['comment'] . "'],\n "; // $this->importField .= "'" . $item['name'] . "' => \$row['" . $item['comment'] . "'],\n ";
// 设置视图数据字段 // 设置视图数据字段
$this->viewData .= "{ field: '{$item['name']}', title: '{$item['comment']}' },\n "; $this->viewData .= "{ field: '{$item['name']}', title: '{$item['comment']}' },\n ";
} }
/** /**

View File

@@ -2,10 +2,10 @@ import { requestClient } from '#/api/request';
const prefix = 'dashCase/'; const prefix = 'dashCase/';
/** /**
* 分页查询用户列表 * 分页查询模板名称列表
* @param data * @param data
*/ */
export async function getupperCamelCaseList(data: any) { export async function getupperCamelCaseListApi(data: any) {
return requestClient.get<any>(`${prefix}list`, { params: data }); return requestClient.get<any>(`${prefix}list`, { params: data });
} }
@@ -13,7 +13,7 @@ export async function getupperCamelCaseList(data: any) {
* 获取模板名称详情 * 获取模板名称详情
* @param id * @param id
*/ */
export async function getupperCamelCaseInfo(id: number) { export async function getupperCamelCaseInfoApi(id: number) {
return requestClient.get<any>(`${prefix}detail`, { params: { id } }); return requestClient.get<any>(`${prefix}detail`, { params: { id } });
} }
@@ -21,7 +21,7 @@ export async function getupperCamelCaseInfo(id: number) {
* 新增模板名称 * 新增模板名称
* @param data * @param data
*/ */
export async function createupperCamelCase(data: Record<string, any>) { export async function createupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}create`, data); return requestClient.post<any>(`${prefix}create`, data);
} }
@@ -29,7 +29,7 @@ export async function createupperCamelCase(data: Record<string, any>) {
* 编辑模板名称 * 编辑模板名称
* @param data * @param data
*/ */
export async function updateupperCamelCase(data: Record<string, any>) { export async function updateupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}update`, data); return requestClient.post<any>(`${prefix}update`, data);
} }
@@ -37,6 +37,6 @@ export async function updateupperCamelCase(data: Record<string, any>) {
* 删除模板名称 * 删除模板名称
* @param data * @param data
*/ */
export async function deleteupperCamelCase(data: Record<string, any>) { export async function deleteupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}delete`, data); return requestClient.post<any>(`${prefix}delete`, data);
} }

View File

@@ -6,7 +6,7 @@ import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form'; import { useVbenForm } from '#/adapter/form';
import { createupperCamelCase, updateupperCamelCase } from '../api'; import {createupperCamelCaseApi, updateupperCamelCaseApi} from '../api';
import { modalFormProps } from '../config/form'; import { modalFormProps } from '../config/form';
defineOptions({ defineOptions({
@@ -29,7 +29,7 @@ const [Modal, modalApi] = useVbenModal({
if (e.valid) { if (e.valid) {
const values = await formApi.getValues(); const values = await formApi.getValues();
modalApi.setState({ loading: true, confirmLoading: true }); modalApi.setState({ loading: true, confirmLoading: true });
const submitApi = isUpdate.value ? updateupperCamelCase : createupperCamelCase; const submitApi = isUpdate.value ? updateupperCamelCaseApi : createupperCamelCaseApi;
submitApi(values) submitApi(values)
.then(() => { .then(() => {
message.success('保存成功'); message.success('保存成功');

View File

@@ -1,6 +1,6 @@
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { VxeGridProps } from '#/adapter/vxe-table';
import { getupperCamelCaseList } from '../api'; import { getupperCamelCaseListApi } from '../api';
interface RowType { interface RowType {
id: string; id: string;
@@ -35,7 +35,7 @@ export const gridOptions: VxeGridProps<RowType> = {
ajax: { ajax: {
// 请求后端接口方法 // 请求后端接口方法
query: async ({ page }, formValues) => { query: async ({ page }, formValues) => {
return await getupperCamelCaseList({ return await getupperCamelCaseListApi({
page: page.currentPage, page: page.currentPage,
pageSize: page.pageSize, pageSize: page.pageSize,
...formValues, ...formValues,

View File

@@ -1,93 +1,74 @@
<script lang="ts" setup> <script lang="ts" setup>
// 导入 VxeGridListeners 类型用于定义表格事件监听器
import type { VxeGridListeners } from '#/adapter/vxe-table'; import type { VxeGridListeners } from '#/adapter/vxe-table';
// 导入 Vue 的 ref 函数用于创建响应式数据
import { ref } from 'vue'; import { ref } from 'vue';
// 导入 Vben 的公共 UI 组件和 Hook
import { Page, useVbenModal } from '@vben/common-ui'; import { Page, useVbenModal } from '@vben/common-ui';
// 导入 Ant Design Vue 的组件和消息提示函数 import { Button, Image, message } from 'ant-design-vue';
import { Button, message } from 'ant-design-vue';
// 导入自定义的 VxeGrid Hook 和 TableAction 组件
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action'; import { TableAction } from '#/components/table-action';
// 导入删除 API 函数和模态框组件 import { deleteupperCamelCaseApi } from './api';
import { deleteupperCamelCase } from './api'; import FormModalDemo from './components/modal.vue';
import upperCamelCase from './components/modal.vue';
// 导入搜索表单和表格配置
import { formOptions } from './config/search'; import { formOptions } from './config/search';
import { gridOptions } from './config/table'; import { gridOptions } from './config/table';
// 定义是否显示顶部表格下拉操作的响应式数据
const hasTopTableDropDownActions = ref(false); const hasTopTableDropDownActions = ref(false);
// 定义表格事件监听器
const gridEvents: VxeGridListeners<any> = { const gridEvents: VxeGridListeners<any> = {
// 监听表格复选框变化事件 checkboxChange() {
checkboxChange() { const records = gridApi.grid.getCheckboxRecords();
const records = gridApi.grid.getCheckboxRecords(); hasTopTableDropDownActions.value = records.length > 0;
hasTopTableDropDownActions.value = records.length > 0; },
}, checkboxAll() {
// 监听表格全选复选框变化事件 const records = gridApi.grid.getCheckboxRecords();
checkboxAll() { hasTopTableDropDownActions.value = records.length > 0;
const records = gridApi.grid.getCheckboxRecords(); },
hasTopTableDropDownActions.value = records.length > 0;
},
}; };
// 使用自定义的 VxeGrid Hook
const [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
formOptions, formOptions,
gridOptions, gridOptions,
gridEvents, gridEvents,
}); });
// 使用 Vben 的 Modal Hook
const [FormModal, formModalApi] = useVbenModal({ const [FormModal, formModalApi] = useVbenModal({
connectedComponent: upperCamelCase, connectedComponent: FormModalDemo,
}); });
// 定义显示模态框的函数
const showModal = (data = {}, isUpdate = false) => { const showModal = (data = {}, isUpdate = false) => {
formModalApi.setData({ formModalApi.setData({
values: data, // 表单值
update: isUpdate, values: data,
gridApi, update: isUpdate,
}); gridApi,
formModalApi.open(); });
formModalApi.open();
}; };
// 定义删除操作的 API 函数 const hasDelete = (row: any) => {
const deleteApi = (row: any) => { let ids = [];
let ids = []; if (row) {
if (row) { ids.push(row);
ids.push(row); } else {
} else { ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
ids = gridApi.grid.getCheckboxRecords().map((item) => item.id); }
} deleteupperCamelCaseApi({ ids }).then(() => {
deleteupperCamelCase({ ids }).then(() => { message.success('删除成功!');
message.success('删除成功!'); gridApi.reload();
gridApi.reload(); });
});
}; };
</script> </script>
<template> <template>
<!-- 使用 Page 组件包裹整个页面 --> <Page auto-content-height title="模板名称管理">
<Page auto-content-height title="模板名称管理"> <FormModal />
<!-- 渲染表单模态框 --> <Grid>
<FormModal /> <template #toolbar-buttons>
<!-- 渲染表格 --> <TableAction
<Grid> :actions="[
<!-- 定义表格工具栏按钮 -->
<template #toolbar-buttons>
<TableAction
:actions="[
{ {
label: '新增', label: '新增',
type: 'primary', type: 'primary',
@@ -95,49 +76,55 @@ const deleteApi = (row: any) => {
onClick: showModal.bind(null), onClick: showModal.bind(null),
}, },
]" ]"
:drop-down-actions="[ :drop-down-actions="[
{ {
label: '删除', label: '删除',
icon: 'ant-design:delete-outlined', icon: 'ant-design:delete-outlined',
ifShow: hasTopTableDropDownActions, ifShow: hasTopTableDropDownActions,
popConfirm: { popConfirm: {
title: '确定删除吗', title: '确定删除吗',
confirm: deleteApi.bind(null, false), confirm: hasDelete.bind(null, false),
}, },
}, },
]" ]"
> >
<template #more> <template #more>
<Button style="margin-left: 16px"> <Button style="margin-left: 16px">
批量操作 批量操作
</Button> </Button>
</template> </template>
</TableAction> </TableAction>
</template> </template>
<!-- 定义操作列的自定义模板 --> <template #avatar="{ row }">
<template #action="{ row }"> <Image :src="row.avatar" height="30" width="30" />
<TableAction </template>
:actions="[ <template #toolbar-tools></template>
{ <template #action="{ row }">
label: '编辑', <TableAction
type: 'link', :actions="[
icon: 'uil:edit', {
size: 'small', label: '编辑',
onClick: showModal.bind(null, row, true), type: 'link',
}, icon: 'uil:edit',
{ size: 'small',
label: '删除', // auth: ['admin', 'sys:role:detail'],
type: 'link', onClick: showModal.bind(null, row, true),
icon: 'ant-design:delete-outlined', },
size: 'small', {
popConfirm: { label: '删除',
title: '确定删除吗?', type: 'link',
confirm: deleteApi.bind(null, row.id), icon: 'ant-design:delete-outlined',
}, size: 'small',
}, // auth: ['admin', 'sys:role:detail'],
]" popConfirm: {
/> title: '确定删除吗?',
</template> confirm: hasDelete.bind(null, row.id),
</Grid> },
</Page> },
]"
:drop-down-actions="[]"
/>
</template>
</Grid>
</Page>
</template> </template>