wbc
2025-12-11 8ee5f3d527a56a0dacc89337c240415713ccfb2f
WebApi/CLAUDE.md
@@ -4,80 +4,196 @@
## Project Overview
This is a .NET 8 MES (Manufacturing Execution System) solution built with ASP.NET Core Web API. The system is organized as a modular monolith with domain-separated projects for different business areas.
This is a .NET 8 MES (Manufacturing Execution System) solution built with ASP.NET Core Web API. The system uses a custom API framework with modular architecture, organizing business functionality into domain-separated projects.
## Solution Structure
The solution follows a modular architecture with these main projects:
- **Gs.HostIIS**: Main Web API host application with Swagger documentation
- **Gs.Entity**: Data entities organized by business domains (BaseInfo, QC, Sys, Warehouse)
- **Gs.Toolbox**: Core utilities, API framework, and dependency injection infrastructure
- **Business Modules**:
  - **Gs.BaseInfo**: Basic information management (items, customers, suppliers, staff, etc.)
  - **Gs.Warehouse**: Inventory and warehouse management
  - **Gs.QC** / **GS.QC**: Quality control functionality
- **Gs.HostIIS**: Main Web API host application (targets .NET 8.0)
- **Gs.Toolbox**: Core framework with custom DI, controller discovery, and utilities (targets .NET 6.0)
- **Gs.Entity**: Data entity models organized by domain (BaseInfo, QC, Sys, Warehouse)
- **Business Modules** (all target .NET 8.0):
  - **Gs.BaseInfo**: Basic information (items, customers, suppliers, staff, departments)
  - **Gs.Warehouse**: Inventory and warehouse operations
  - **GS.QC**: Quality control and inspection
  - **Gs.Sys**: System administration and user management
  - **Gs.Report**: Reporting functionality
  - **Gs.Wom**: Work order management
  - **Gs.Sales**: Sales management
  - **Gs.Pda**: Mobile/handheld device support
  - **Gs.QiTaCk** / **Gs.QiTaRk**: Additional business modules
  - **Gs.Ww**: Additional functionality
  - **Gs.QiTaCk** / **Gs.QiTaRk**: Miscellaneous in/out operations (其它出库/其它入库)
  - **Gs.Ww**: Outsourcing management (委外)
  - **Gs.JJGZ**: Piece-rate wage management (计件工资)
  - **Gs.OpenApi**: External API integration and open interfaces
## Development Commands
### Build and Run
- Build entire solution: `dotnet build GsMesSolution.sln`
- Run main API: `dotnet run --project Gs.HostIIS`
- Build specific project: `dotnet build Gs.ProjectName/Gs.ProjectName.csproj`
```bash
# Build entire solution
dotnet build GsMesSolution.sln
# Run main API (starts on http://localhost:5263 by default)
dotnet run --project Gs.HostIIS
# Build specific module
dotnet build Gs.BaseInfo/Gs.BaseInfo.csproj
```
### Development Server
- The API runs on `http://localhost:5263` (or `http://localhost:37005` via IIS Express)
- Swagger UI is available at `/swagger` endpoint
- CORS is configured to allow all origins for development
- API runs on `http://localhost:5263` (default Project profile) or `http://localhost:37005` (IIS Express)
- Ports configured in `Gs.HostIIS/Properties/launchSettings.json`
- Swagger UI: `http://localhost:5263/swagger` (always enabled, not just in Development)
- CORS configured to allow all origins via "AllowAll" policy
### Testing
- No automated tests currently exist in the solution
- Manual testing via Swagger UI at `/swagger` endpoint
- Test ERP integration endpoints configured in appsettings.json (`TestErpUrl`, `TestErpUrl2`)
## Architecture Details
### Custom API Framework
The solution uses a custom API framework built in `Gs.Toolbox`:
- Custom dependency injection with lifecycle attributes (`ITransient`, `IScope`, `ISingleton`)
- Custom controller convention and routing
- API grouping for Swagger documentation via `ApiGroupAttribute`
- Custom authorization with `ApiAuthorizeAttribute`
The solution uses a custom framework in `Gs.Toolbox` that replaces standard ASP.NET Core conventions:
#### Controller Discovery
- Controllers are discovered by implementing the `IRomteService` interface (not by inheriting `ControllerBase`)
- `CustomControllerFeatureProvider` scans assemblies and the `Services` folder for classes implementing `IRomteService`
- Controllers are automatically registered without `[ApiController]` or `[Route]` attributes
- Business logic classes in `Services/` folders act as controllers
#### Routing Convention
- Routes automatically generated as `/{ControllerName}/{ActionName}` by `CustomApplicationModelConvention`
- HTTP methods specified via `[RequestMethod(RequestMethods.POST)]` attribute (not standard `[HttpPost]`)
- Parameter binding: non-primitive types automatically bound from request body for POST/PUT/PATCH
#### Dependency Injection
- Custom DI system using lifecycle marker interfaces:
  - `ITransient`: Transient lifetime (new instance per request)
  - `IScope`: Scoped lifetime (one instance per request)
  - `ISingleton`: Singleton lifetime (one instance for application)
- Classes implementing these interfaces are auto-registered
- Use `[Expose(typeof(IYourInterface))]` attribute to specify service interface explicitly
- Auto-injection scans all referenced assemblies via `builder.AddCustomInject()`
#### API Grouping
- Swagger groups defined via `[ApiGroup(ApiGroupNames.BaseInfo)]` attribute on controller classes
- Groups defined in `ApiGroupNames` enum (BaseInfo, QC, PerMission, WOM, ErpMes, etc.)
- Each group generates separate Swagger document for organization
### Data Access
- Uses SqlSugar ORM for database operations
- Connection string configured in `appsettings.json`
- Repository pattern implemented in `Gs.Toolbox/Repository.cs`
### Configuration
- Database: SQL Server (connection string in appsettings.json)
- External services: ERP integration endpoints configured
- File paths: Services, logs, upload, and download paths configured
- Custom JSON serialization with Newtonsoft.Json
#### SqlSugar ORM
- Base repository: `Repository<T>` in `Gs.Toolbox/Repository.cs`
- Connection string: `appsettings.json` → `ConnectionStrings` key
- Static `SqlSugarScope Db` instance provides database context
- Business classes inherit from `Repository<TEntity>` for data access
- Transaction support via `UseTransaction()` method
### Key Components
- **CustomContractResolver**: Custom JSON property naming
- **ResponseResult**: Standardized API response format
- **ExcelHelper**: Excel import/export functionality
- **LogHelper**: Logging utilities
- **DbHelperSQL**: Additional database utilities
#### Pagination
- Standard pagination using `PageQuery` (input) and `PageList<T>` (output)
- `PageQuery` fields: `currentPage`, `everyPageSize`, `sortName`, `sortOrder`, `keyWord`, `keyWhere`, `keyType`
- `CommonPage()` methods provide built-in pagination logic
## Business Domains
### Response Format
The system handles typical MES functionality:
- Base information (items, customers, suppliers, departments, staff)
- Quality control and inspection
- Warehouse and inventory management
- Work order management
- Reporting and analytics
- Mobile device integration
All API responses use `ReturnDto<T>` wrapper:
```csharp
{
  "rtnCode": 1,        // ReturnCode enum: Success=1, Default=-100, Unauthorized=-101, Exception=-102
  "rtnData": {...},    // Generic data payload
  "rtnMsg": "..."      // Optional message
}
```
### JSON Serialization
- Uses Newtonsoft.Json with custom `CustomContractResolver`
- Property naming: Converts to camelCase (first letter lowercase)
- Handles underscore-separated names (e.g., `USER_NAME` → `userName`)
- Date format: `"yyyy-MM-dd HH:mm:ss"`
- Reference loop handling: Ignore
### Authorization
- Custom `ApiAuthorizeAttribute` filter validates `token` header
- Token format: `"token {guid}"` in request header
- Use `[AllowAnonymous]` to bypass authorization
- User context extraction via `UtilityHelper.GetUserGuidAndOrgGuid(IHttpContextAccessor)`
### Configuration (appsettings.json)
- `ConnectionStrings`: SQL Server connection string
- `TestErpUrl`, `TestErpUrl2`, `ProductionErpUrl`: ERP integration endpoints
- `ServicesPath`: Path to compiled DLLs for controller discovery (default: "Services")
- `LogPath`: Log file directory (default: "logs")
- `UploadPath`: File upload directory (mapped to `/upload` endpoint)
- `DownPath`: File download directory (mapped to `/down` endpoint)
### Project Output Configuration
Business modules use custom output paths:
- Compiled DLLs output to `Gs.HostIIS/bin/Debug/` (BaseOutputPath configured in .csproj)
- XML documentation files generated automatically for Swagger
- Framework scans `Services/` folder at runtime for controller DLLs
## Creating New Business Modules
1. **Create new class library project** targeting .NET 8.0
2. **Reference required projects**:
   ```xml
   <ProjectReference Include="..\Gs.Entity\Gs.Entity.csproj" />
   <ProjectReference Include="..\Gs.Toolbox\Gs.Toolbox.csproj" />
   ```
3. **Configure output path** in .csproj:
   ```xml
   <BaseOutputPath>..\Gs.HostIIS\bin</BaseOutputPath>
   <OutputPath>..\Gs.HostIIS\bin\Debug\</OutputPath>
   <GenerateDocumentationFile>True</GenerateDocumentationFile>
   ```
4. **Create Services folder** for controller classes
5. **Implement controller** by inheriting `Repository<TEntity>` and `IRomteService`:
   ```csharp
   [ApiGroup(ApiGroupNames.YourGroup)]
   public class YourManager : Repository<YourEntity>, IRomteService
   {
       [RequestMethod(RequestMethods.POST)]
       public ReturnDto<PageList<YourEntity>> GetListPage(PageQuery query) { ... }
   }
   ```
6. **Add to solution** and build (DLL auto-discovered at runtime)
## Common Patterns
### Creating API Endpoints
```csharp
[ApiGroup(ApiGroupNames.BaseInfo)]
public class MesItemsManager : Repository<MesItems>, IRomteService
{
    private readonly IHttpContextAccessor _http;
    public MesItemsManager(IHttpContextAccessor httpContextAccessor)
    {
        _http = httpContextAccessor;
    }
    [RequestMethod(RequestMethods.POST)]
    public ReturnDto<PageList<MesItems>> GetListPage(PageQuery query)
    {
        // Business logic using Db property from Repository<T>
    }
}
```
### Using Transactions
```csharp
var affectedRows = UseTransaction(db => {
    db.Insertable(entity).ExecuteCommand();
    db.Updateable(otherEntity).ExecuteCommand();
    return db.Ado.AffectedRows;
});
```
## Development Notes
- All projects target .NET 8.0
- Nullable reference types are enabled
- The system uses a Chinese interface (comments and some naming in Chinese)
- Custom API framework provides dependency injection and controller conventions
- Swagger documentation is automatically generated with XML comments
- The system uses Chinese for business domain comments and naming
- Gs.Toolbox targets .NET 6.0 for compatibility; all other projects target .NET 8.0
- Controllers are discovered at runtime from `Services/` folder - no need to manually register
- Swagger automatically includes all controllers with their XML documentation
- Static files (uploads/downloads) served from paths configured in appsettings.json