Browse Source

feat: add new rules for development workflow, Java templates, project overview, template structure, and Velocity templates

PIG AI 1 month ago
parent
commit
de2c121a36

+ 111 - 0
.cursor/rules/development-workflow.mdc

@@ -0,0 +1,111 @@
+---
+description: 
+globs: 
+alwaysApply: false
+---
+# Development Workflow
+
+## Using CGTM Templates
+
+### 1. Template Selection
+
+Choose the appropriate template group based on your needs:
+- **单表增删改查** - For simple CRUD operations on a single table
+- **主子表增删改查** - For parent-child relationships (e.g., Order-OrderItems)
+- **vform** - For visual form designer integration
+
+### 2. Configuration Setup
+
+Before generating code, ensure these variables are configured:
+
+**Basic Information:**
+- `author` - Developer name
+- `package` - Base package (e.g., com.pigx.app)
+- `moduleName` - Module identifier (e.g., system, business)
+- `functionName` - Feature name (e.g., user, product)
+
+**Database Configuration:**
+- `tableName` - Database table name
+- `tableComment` - Table description
+- `fieldList` - Field definitions from database
+
+**Path Configuration:**
+- `backendPath` - Backend project root path
+- `frontendPath` - Frontend project root path
+
+### 3. Code Generation Process
+
+1. **Analyze Database Schema**
+   - Primary keys are marked with `primaryPk = '1'`
+   - Auto-fill fields configured (INSERT, UPDATE, INSERT_UPDATE)
+   - Logical deletion field is `del_flag`
+
+2. **Generate Backend Code**
+   - Entity with proper annotations
+   - Mapper interface and XML
+   - Service interface and implementation
+   - Controller with REST endpoints
+
+3. **Generate Frontend Code**
+   - API client in TypeScript
+   - Table component for data display
+   - Form component for data entry
+   - i18n translations if needed
+
+4. **Generate SQL Scripts**
+   - Permission entries
+   - Menu configuration
+
+### 4. Post-Generation Tasks
+
+After code generation:
+
+1. **Review Generated Code**
+   - Check import statements
+   - Verify field mappings
+   - Ensure proper annotations
+
+2. **Customize Business Logic**
+   - Add validation rules
+   - Implement custom queries
+   - Add business-specific methods
+
+3. **Configure Permissions**
+   - Run generated SQL scripts
+   - Assign roles and permissions
+   - Test access control
+
+4. **Frontend Integration**
+   - Add routes
+   - Configure menu items
+   - Test CRUD operations
+
+### 5. Master-Detail Specifics
+
+For parent-child relationships:
+
+1. **Define Relationships**
+   - `mainField` - Parent table foreign key field
+   - `childField` - Child table reference field
+   - Configure cascade operations
+
+2. **Transaction Management**
+   - All operations wrapped in transactions
+   - Proper rollback on errors
+   - Batch operations for children
+
+3. **UI Considerations**
+   - Nested forms for data entry
+   - Inline editing for child records
+   - Proper validation across levels
+
+### 6. Best Practices
+
+- Always use logical deletion (`del_flag`) instead of physical deletion
+- Implement proper validation at both frontend and backend
+- Use dictionaries for standardized dropdowns
+- Follow RESTful conventions for APIs
+- Maintain consistent naming conventions
+- Add comprehensive API documentation with `@Schema` annotations
+- Use permission annotations for security
+- Implement audit logging with `@SysLog`

+ 100 - 0
.cursor/rules/java-templates.mdc

@@ -0,0 +1,100 @@
+---
+description: 
+globs: 
+alwaysApply: false
+---
+# Java Backend Template Patterns
+
+## Entity Template Pattern
+
+Entities follow the MyBatis-Plus active record pattern:
+
+```java
+@Data
+@TableName("${tableName}")
+@EqualsAndHashCode(callSuper = true)
+public class ${ClassName}Entity extends Model<${ClassName}Entity> {
+    // Fields with annotations
+}
+```
+
+Key annotations used:
+- `@TableId(type = IdType.ASSIGN_ID)` - For primary keys
+- `@TableField(fill = FieldFill.INSERT)` - Auto-fill on insert
+- `@TableLogic` - Logical deletion flag
+- `@Schema` - OpenAPI documentation
+
+## Controller Template Pattern
+
+Controllers follow RESTful conventions with Spring Boot:
+
+```java
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/${functionName}")
+@Tag(description = "${tableComment}", name = "${tableComment}管理")
+public class ${ClassName}Controller {
+    // CRUD endpoints
+}
+```
+
+Standard endpoints:
+- `GET /{id}` - Get by ID
+- `GET /page` - Paginated list
+- `POST` - Create new
+- `PUT` - Update existing
+- `DELETE` - Delete (logical or physical)
+
+## Service Layer Pattern
+
+Service interface:
+```java
+public interface ${ClassName}Service extends IService<${ClassName}Entity> {
+    // Custom business methods
+}
+```
+
+Implementation extends ServiceImpl:
+```java
+@Service
+@RequiredArgsConstructor
+public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper, ${ClassName}Entity> 
+    implements ${ClassName}Service {
+    // Business logic implementation
+}
+```
+
+## Mapper Pattern
+
+MyBatis mapper interface:
+```java
+@Mapper
+public interface ${ClassName}Mapper extends BaseMapper<${ClassName}Entity> {
+    // Custom SQL methods
+}
+```
+
+## Multi-Tenant Support
+
+When `isTenant` is true:
+- Entity includes `@TenantTable` annotation
+- Automatic tenant filtering in queries
+- Tenant ID auto-fill on insert
+
+## Transaction Handling
+
+Master-detail operations use:
+```java
+@Transactional(rollbackFor = Exception.class)
+public Boolean save${ClassName}(${ClassName}Entity entity) {
+    // Parent save
+    // Children save/update/delete
+}
+```
+
+## Security Annotations
+
+Common security patterns:
+- `@PreAuthorize("@pms.hasPermission('${functionName}_add')")` - Permission check
+- `@SysLog("新增${tableComment}")` - Audit logging
+- `@Inner(false)` - Internal service access control

+ 52 - 0
.cursor/rules/project-overview.mdc

@@ -0,0 +1,52 @@
+---
+description: 
+globs: 
+alwaysApply: true
+---
+# CGTM Project Overview
+
+## What is CGTM?
+
+CGTM (Code Generation Template Market - 代码生成模板市场) is an online platform that provides various code generation templates to enhance developer experience. It's designed to work with the PIGX framework for rapid application development.
+
+## Project Purpose
+
+- Provide rich and diverse code generation templates
+- Enable easy template updates through "online update" functionality
+- Support community contributions via GitHub pull requests
+- Accelerate development workflow with pre-built templates
+
+## Core Technologies
+
+- **Template Engine**: Apache Velocity
+- **Backend**: Java with Spring Boot
+- **Frontend**: Vue.js with TypeScript
+- **Database Support**: Multiple database types through dynamic configuration
+- **Architecture**: Microservices with modular design
+
+## Template Categories
+
+1. **Single Table CRUD** (单表增删改查)
+   - Complete CRUD operations for single entities
+   - Includes Controller, Service, Mapper, Entity, and Vue components
+
+2. **Master-Detail CRUD** (主子表增删改查)
+   - Parent-child relationship management
+   - Complex form handling with nested data
+
+3. **VForm Templates**
+   - Visual form designer integration
+   - JSON-based form configuration
+
+## Key Features
+
+- Multi-tenant support (`isTenant` flag)
+- Internationalization (i18n) ready
+- Auto-fill fields support
+- Logical deletion support
+- Dynamic permission and menu generation
+- Modern UI with best UX practices
+
+## License
+
+AGPL 3.0 - Free for PIGX users only

+ 79 - 0
.cursor/rules/template-structure.mdc

@@ -0,0 +1,79 @@
+---
+description: 
+globs: 
+alwaysApply: true
+---
+# Template Structure Guide
+
+## Directory Organization
+
+```
+CGTM/
+├── single/              # Single table CRUD templates
+├── multiple/            # Master-detail table templates
+├── common/              # Shared templates across modules
+├── vform/               # Visual form designer templates
+└── config.json          # Template configuration mapping
+```
+
+## Template Configuration
+
+The [config.json](mdc:config.json) file defines template groups and their mappings:
+
+```json
+{
+  "单表增删改查": [...],     // Single table templates
+  "主子表增删改查": [...],   // Master-detail templates
+  "vform": [...]           // VForm templates
+}
+```
+
+Each template entry contains:
+- `templateName`: Display name of the template
+- `generatorPath`: Output path with variable substitution
+- `templateFile`: Source template file location
+
+## Single Table Templates
+
+Located in the [single/](mdc:single) directory:
+
+- [Controller.java](mdc:single/Controller.java) - REST API endpoints
+- [Service.java](mdc:single/Service.java) - Business logic interface
+- [ServiceImpl.java](mdc:single/ServiceImpl.java) - Service implementation
+- [实体.java](mdc:single/实体.java) - JPA/MyBatis entity
+- [Mapper.java](mdc:single/Mapper.java) - MyBatis mapper interface
+- [Mapper.xml](mdc:single/Mapper.xml) - SQL mappings
+- [表格.vue](mdc:single/表格.vue) - Data table component
+- [表单.vue](mdc:single/表单.vue) - Form component
+
+## Master-Detail Templates
+
+Located in the [multiple/](mdc:multiple) directory:
+
+- [主子Contoller.java](mdc:multiple/主子Contoller.java) - Parent-child REST APIs
+- [主子Service.java](mdc:multiple/主子Service.java) - Complex business logic
+- [主子ServiceImpl.java](mdc:multiple/主子ServiceImpl.java) - Implementation with transactions
+- [主实体.java](mdc:multiple/主实体.java) - Parent entity
+- [子实体.java](mdc:multiple/子实体.java) - Child entity
+- [子Mapper.java](mdc:multiple/子Mapper.java) - Child table mapper
+- [主子表格.vue](mdc:multiple/主子表格.vue) - Parent-child data display
+- [主子表单.vue](mdc:multiple/主子表单.vue) - Nested form handling
+
+## Common Templates
+
+Located in the [common/](mdc:common) directory:
+
+- [api.ts](mdc:common/api.ts) - TypeScript API client
+- [权限菜单.sql](mdc:common/权限菜单.sql) - Permission and menu SQL
+- [i18n中文模板.ts](mdc:common/i18n中文模板.ts) - Chinese translations
+- [i18n英文模板.ts](mdc:common/i18n英文模板.ts) - English translations
+
+## Path Variables
+
+Template paths support these variables:
+- `${backendPath}` - Backend project root
+- `${frontendPath}` - Frontend project root
+- `${packagePath}` - Java package path (com/example/app)
+- `${moduleName}` - Module name
+- `${ClassName}` - Entity class name
+- `${functionName}` - Function/feature name

+ 100 - 0
.cursor/rules/velocity.mdc

@@ -0,0 +1,100 @@
+---
+description: 
+globs: 
+alwaysApply: true
+---
+# Velocity Templates in CGTM
+
+This rule explains how Velocity templates are used for code generation in this project.
+
+## Basic Structure
+
+Velocity templates use a simple syntax with variables, directives, and references:
+- Variables start with `$` (e.g., `$ClassName`)
+- Directives start with `#` (e.g., `#foreach`, `#if`, `#end`)
+- Comments use `##`
+
+## Entity Template Example
+
+```java
+public class ${ClassName}Entity extends Model<${ClassName}Entity> {
+
+#foreach ($field in $fieldList)
+#if($field.primaryPk)
+    @TableId(type = IdType.ASSIGN_ID)
+#end
+    @Schema(description="$comment"#if($field.hidden),hidden=$field.hidden#end)
+    private $field.attrType $field.attrName;
+#end
+}
+```
+
+## Available Context Variables
+
+### Template Basic Properties
+| Variable | Description |
+|----------|-------------|
+| dbType | Database type |
+| package | Package name |
+| packagePath | Package path |
+| version | Version |
+| moduleName | Module name |
+| ModuleName | Module name (first letter capitalized) |
+| functionName | Function name |
+| FunctionName | Function name (first letter capitalized) |
+| formLayout | Form layout |
+| style | Style, corresponding template group |
+| author | Author |
+| datetime | Current date and time |
+| date | Current date |
+| importList | Import list |
+| tableName | Database table name |
+| tableComment | Database table comment |
+| className | Class name in lowercase |
+| ClassName | Class name |
+| fieldList | Field list |
+| backendPath | Backend path |
+| frontendPath | Frontend path |
+| childFieldList | Child table field list |
+| childTableName | Child table name |
+| mainField | Main table relation field name |
+| childField | Child table relation field name |
+| ChildClassName | Child class name (first letter capitalized) |
+| childClassName | Child class name in lowercase |
+| primaryList | Primary key field list |
+| formList | Form field list |
+| gridList | Grid field list |
+| queryList | Query field list |
+| pk | Primary key field |
+
+### Template Field Properties
+| Variable | Description |
+|----------|-------------|
+| dsName | Data source name |
+| tableName | Table name |
+| fieldName | SQL field name |
+| fieldType | SQL field type |
+| attrName | Java attribute name |
+| attrType | Java attribute type |
+| fieldComment | Field description |
+| sort | Sort |
+| packageName | Attribute package name |
+| autoFill | Auto fill |
+| primaryPk | Whether it's a primary key |
+| baseField | Whether it's a base class field |
+| formItem | Whether it's a form item |
+| formRequired | Form required |
+| formType | Form type |
+| formValidator | Form validator |
+| gridItem | Whether it's a list item |
+| gridSort | List sorting |
+| queryItem | Whether it's a query item |
+| queryType | Query method |
+| queryFormType | Query form type |
+| fieldDict | Field dictionary type |
+
+### Environment Variables
+| Variable | Description |
+|----------|-------------|
+| isSpringBoot3 | Whether it's SpringBoot 3 |
+| isTenant | Whether multi-tenant is supported |