mi-assessment/server/MiAssessment/TEMPLATE_README.md
2026-02-03 14:25:01 +08:00

329 lines
10 KiB
Markdown

# Framework Template - Backend
This is a .NET 10 backend framework template extracted from the MiAssessment project. It provides a clean architecture foundation with essential features for building mini-program backends.
## Features
- **Authentication & Authorization**: JWT + Refresh Token mechanism
- **User Management**: Basic user info, login logs
- **WeChat Integration**: Mini-program login, phone number retrieval
- **WeChat Pay**: V3 payment, callback verification, refunds
- **Address Management**: User shipping address CRUD
- **Configuration Management**: System configuration read/write
- **File Upload**: Local storage + Tencent Cloud COS dual mode
- **Admin RBAC**: Complete role-based access control system
- **Dictionary Management**: Static data + dynamic SQL query support
- **Payment Orders**: Generic payment order with reward handler mechanism
- **Redis Cache**: Cache service wrapper
## Project Structure
```
server/MiAssessment/
├── MiAssessment.sln
├── src/
│ ├── MiAssessment.Api/ # Web API Layer
│ │ ├── Controllers/
│ │ │ ├── AuthController.cs # Authentication
│ │ │ ├── UserController.cs # User management
│ │ │ ├── AddressController.cs # Address management
│ │ │ ├── ConfigController.cs # Configuration
│ │ │ ├── PayController.cs # Payment
│ │ │ ├── NotifyController.cs # Payment callbacks
│ │ │ └── HealthController.cs # Health check
│ │ ├── Filters/
│ │ └── Program.cs
│ │
│ ├── MiAssessment.Core/ # Business Logic Layer
│ │ ├── Interfaces/
│ │ ├── Services/
│ │ └── Mappings/
│ │
│ ├── MiAssessment.Infrastructure/ # Infrastructure Layer
│ │ ├── Cache/
│ │ ├── External/
│ │ └── Modules/
│ │
│ ├── MiAssessment.Model/ # Data Model Layer
│ │ ├── Entities/
│ │ ├── Models/
│ │ ├── Data/
│ │ └── Base/
│ │
│ ├── MiAssessment.Admin/ # Admin RBAC
│ │ ├── Controllers/
│ │ ├── Services/
│ │ ├── Entities/
│ │ └── Data/
│ │
│ └── MiAssessment.Admin.Business/ # Admin Business Module
│ ├── Controllers/
│ └── Services/
├── scripts/ # Database Scripts
│ ├── init_admin_db.sql # Admin database initialization
│ └── init_business_db.sql # Business database initialization
├── tests/
│ └── MiAssessment.Tests/ # Unit & Property Tests
└── README.md
```
## Placeholder Locations
When generating a new project from this template, the following placeholders need to be replaced:
### Project Name Placeholders
| Placeholder | Description | Example |
|-------------|-------------|---------|
| `MiAssessment` | Project name (PascalCase) | `MyApp` |
| `MiAssessment` | Original project name to replace | → `MyApp` |
### Files Requiring Project Name Replacement
#### Solution & Project Files
- `MiAssessment.sln``MiAssessment.sln`
- `src/MiAssessment.Api/MiAssessment.Api.csproj``src/MiAssessment.Api/MiAssessment.Api.csproj`
- `src/MiAssessment.Core/MiAssessment.Core.csproj``src/MiAssessment.Core/MiAssessment.Core.csproj`
- `src/MiAssessment.Infrastructure/MiAssessment.Infrastructure.csproj``src/MiAssessment.Infrastructure/MiAssessment.Infrastructure.csproj`
- `src/MiAssessment.Model/MiAssessment.Model.csproj``src/MiAssessment.Model/MiAssessment.Model.csproj`
- `src/MiAssessment.Admin/MiAssessment.Admin.csproj``src/MiAssessment.Admin/MiAssessment.Admin.csproj`
- `src/MiAssessment.Admin.Business/MiAssessment.Admin.Business.csproj``src/MiAssessment.Admin.Business/MiAssessment.Admin.Business.csproj`
- `tests/MiAssessment.Tests/MiAssessment.Tests.csproj``tests/MiAssessment.Tests/MiAssessment.Tests.csproj`
#### Namespace Declarations (All .cs files)
Replace in all C# source files:
```csharp
// From:
namespace MiAssessment.Api.Controllers;
using MiAssessment.Core.Services;
// To:
namespace MiAssessment.Api.Controllers;
using MiAssessment.Core.Services;
```
#### Configuration Files
- `src/MiAssessment.Api/appsettings.json`
- Connection strings
- JWT settings
- WeChat configuration
- `src/MiAssessment.Api/appsettings.Development.json`
- `src/MiAssessment.Admin/appsettings.json`
### Database Placeholders
| Placeholder | Description | Example |
|-------------|-------------|---------|
| `MiAssessment_Admin` | Admin database name | `MyApp_Admin` |
| `MiAssessment_Business` | Business database name | `MyApp_Business` |
### Configuration Placeholders (appsettings.json)
| Placeholder | Description | Example |
|-------------|-------------|---------|
| `{{DB_SERVER}}` | SQL Server 地址 | `localhost` |
| `{{DB_USER}}` | 数据库用户名 | `sa` |
| `{{DB_PASSWORD}}` | 数据库密码 | `YourPassword123` |
| `{{DB_NAME}}` | 业务数据库名 | `myapp_business` |
| `{{ADMIN_DB_NAME}}` | 管理后台数据库名 | `myapp_admin` |
| `{{REDIS_HOST}}` | Redis 地址 | `localhost` |
| `{{REDIS_PORT}}` | Redis 端口 | `6379` |
| `{{JWT_SECRET_AT_LEAST_32_CHARACTERS}}` | JWT 密钥 (至少32字符) | `MySecretKey123...` |
| `{{PROJECT_NAME}}` | 项目名称 | `MyApp` |
| `{{WECHAT_MCH_ID}}` | 微信支付商户号 | `1234567890` |
| `{{WECHAT_APP_ID}}` | 小程序 AppId | `wx1234567890abcdef` |
| `{{WECHAT_API_KEY}}` | 微信支付 API 密钥 | `your_api_key` |
| `{{WECHAT_NOTIFY_URL}}` | 支付回调地址 | `https://api.example.com/api/notify/wechat` |
| `{{API_BASE_URL}}` | API 基础地址 | `https://api.example.com` |
| `{{AMAP_API_KEY}}` | 高德地图 API Key | `your_amap_key` |
## Database Initialization
### Admin Database
The `scripts/init_admin_db.sql` script creates:
**Tables:**
- `departments` - Department hierarchy
- `admin_users` - Admin accounts
- `roles` - Role definitions
- `permissions` - Permission definitions
- `menus` - Menu configuration
- `admin_user_roles` - Admin-Role associations
- `role_menus` - Role-Menu associations
- `role_permissions` - Role-Permission associations
- `admin_user_menus` - User-specific menus
- `department_menus` - Department-Menu associations
- `operation_logs` - Operation audit logs
- `refresh_tokens` - Admin refresh tokens
- `admin_configs` - Admin configurations
- `dict_types` - Dictionary types
- `dict_items` - Dictionary items
**Default Data:**
- Default department: 总部 (HQ)
- Default roles: 超级管理员, 管理员
- Default admin user: `admin` / `admin123`
- Default permissions: System management, User management
- Default menus: System management tree
- Default dictionaries: user_status, gender, yes_no
### Business Database
The `scripts/init_business_db.sql` script creates:
**Tables:**
- `users` - User accounts (simplified)
- `user_details` - User extension fields
- `user_addresses` - Shipping addresses
- `user_refresh_tokens` - User refresh tokens
- `user_login_logs` - Login audit logs
- `payment_orders` - Generic payment orders
- `order_notifies` - Payment callback records
- `configs` - System configurations
- `pictures` - Image management
- `deliveries` - Delivery companies
**Default Data:**
- Default configs: wechat, wechat_pay, sms, system
- Default deliveries: SF, ZTO, YTO, YD, STO, JTSD, YZPY, JD, DBL
## Quick Start
### 1. Generate Project
Use the template generator script:
```powershell
./create-project.ps1 `
-ProjectName "MyApp" `
-AdminDbName "MyApp_Admin" `
-BusinessDbName "MyApp_Business" `
-SqlServerHost "localhost" `
-SqlServerUser "sa" `
-SqlServerPassword "YourPassword"
```
### 2. Configure Database
Update `appsettings.json` with your database connection strings:
```json
{
"ConnectionStrings": {
"AdminConnection": "Server=localhost;Database=MyApp_Admin;User Id=sa;Password=YourPassword;TrustServerCertificate=True",
"DefaultConnection": "Server=localhost;Database=MyApp_Business;User Id=sa;Password=YourPassword;TrustServerCertificate=True"
}
}
```
### 3. Initialize Databases
Run the initialization scripts:
```sql
-- Create Admin database
CREATE DATABASE [MyApp_Admin];
GO
-- Run init_admin_db.sql
-- Create Business database
CREATE DATABASE [MyApp_Business];
GO
-- Run init_business_db.sql
```
### 4. Build and Run
```bash
cd server/MyApp
dotnet restore
dotnet build
dotnet run --project src/MyApp.Api
```
The API will be available at `http://localhost:5238`
### 5. Access Admin Panel
- URL: `http://localhost:5238/admin`
- Username: `admin`
- Password: `admin123`
## Extending the Template
### Adding Business Fields to User
Add fields to `user_details` table:
```sql
ALTER TABLE [dbo].[user_details]
ADD [Balance] DECIMAL(10,2) NOT NULL DEFAULT 0,
[Points] INT NOT NULL DEFAULT 0,
[Level] INT NOT NULL DEFAULT 1;
```
Update `UserDetail.cs` entity accordingly.
### Adding Payment Reward Handlers
Implement `IPaymentRewardHandler` interface:
```csharp
public class VipPurchaseRewardHandler : IPaymentRewardHandler
{
public string OrderType => "vip_purchase";
public async Task<RewardResult> ProcessRewardAsync(PaymentOrder order)
{
// Implement VIP activation logic
return new RewardResult { Success = true, Message = "VIP activated" };
}
}
```
Register in DI container:
```csharp
services.AddScoped<IPaymentRewardHandler, VipPurchaseRewardHandler>();
```
### Adding New Dictionary Types
Insert via SQL or Admin panel:
```sql
INSERT INTO [dict_types] ([code], [name], [source_type], [status])
VALUES ('order_status', N'订单状态', 1, 1);
INSERT INTO [dict_items] ([type_id], [label], [value], [css_class], [status], [sort])
VALUES
(@type_id, N'待支付', '0', 'warning', 1, 1),
(@type_id, N'已支付', '1', 'success', 1, 2),
(@type_id, N'已取消', '2', 'info', 1, 3);
```
## API Documentation
After starting the API, access Scalar documentation at:
- `http://localhost:5238/scalar/v1`
## Technology Stack
- **Framework**: ASP.NET Core (.NET 10)
- **ORM**: Entity Framework Core 8.0
- **Database**: SQL Server
- **Architecture**: Clean Architecture
- **DI Container**: Autofac
- **Authentication**: JWT Bearer
- **Logging**: Serilog
- **Object Mapping**: Mapster
- **API Documentation**: Scalar (OpenAPI)
## License
This template is provided as-is for internal use.