# 服务设计文档 (Crawlful Hub) > **定位**:Crawlful Hub 后端服务设计文档 - 定义服务层架构、服务职责和实现规范。 > **更新日期**: 2026-03-18 > **最高优先级参考**: [Business_ClosedLoops.md](../00_Business/Business_ClosedLoops.md) --- ## 1. 服务层架构 ### 1.1 核心原则(逻辑集中化) > **逻辑集中化 → 服务驱动**:所有业务逻辑必须集中在 Service 层,禁止分散在 Controller、前端或数据库操作中。 #### 强制约束 - ✅ **每个业务操作对应一个 Service**:前端的每个用户操作都必须有对应的后端 Service 处理 - ✅ **服务编排**:通过 Service 层串联多个模块,实现业务流程的完整执行 - ✅ **单一职责**:每个 Service 只负责一个核心业务领域 - ✅ **依赖注入**:通过依赖注入实现服务间的解耦 - ✅ **事务管理**:重要操作必须在事务中执行,确保数据一致性 - ✅ **状态管理统一**:所有状态更新必须通过 Service 层,禁止在 Controller 或前端直接修改 #### 禁止行为 - ❌ **Controller 中写业务逻辑**:Controller 只负责请求/响应和权限校验,业务决策、状态变化、数据校验必须在 Service 层 - ❌ **前端直接写业务规则**:复杂计算、权限判断、状态流转禁止在 React 组件中实现 - ❌ **数据库操作分散**:不同模块禁止直接调用数据库,必须通过 Service 层 - ❌ **脚本或工具处理逻辑**:AI 任务或异步脚本必须通过 Service 层统一调用 ### 1.2 服务层级结构 ``` Controller → Service (核心编排) → Repository / External API → 数据库/外部系统 ``` #### Controller 层职责(强制执行) - 接收 HTTP 请求和参数验证 - 调用 Service 层处理业务逻辑 - 返回响应给前端 - 权限校验(通过 `authorize()` 中间件) - **禁止**:业务决策、状态变化、数据校验 #### Service 层职责(核心) - 业务逻辑编排和状态流转 - 多模块协同和数据一致性保证 - 事务管理和异常处理 - 调用 Repository 层或外部 API - **必须**:所有业务逻辑必须在此层实现 #### Repository 层职责 - 数据库 CRUD 操作 - 数据模型映射 - 查询优化 - **禁止**:业务逻辑处理 --- ## 2. 核心服务列表 ### 2.1 商品服务 (ProductService) **职责**:管理商品全生命周期,包括创建、更新、查询、删除等操作 **核心方法**: - `createProduct()`: 创建商品 - `updateProduct()`: 更新商品信息 - `updatePrice()`: 更新商品价格,同时计算 ROI - `getProductById()`: 根据 ID 获取商品详情 - `getProducts()`: 获取商品列表 - `deleteProduct()`: 删除商品 - `publishProduct()`: 发布商品到平台 - `unpublishProduct()`: 从平台下架商品 **依赖**: - `PricingService`: 计算价格和 ROI - `InventoryService`: 管理商品库存 - `MediaService`: 管理商品媒体资源 ### 2.2 订单服务 (OrderService) **职责**:管理订单全生命周期,包括创建、更新、查询、处理等操作 **核心方法**: - `createOrder()`: 创建订单 - `updateOrderStatus()`: 更新订单状态 - `getOrderById()`: 根据 ID 获取订单详情 - `getOrders()`: 获取订单列表 - `processOrder()`: 处理订单(包括库存扣减、物流安排等) - `splitOrder()`: 拆分订单 - `mergeOrders()`: 合并订单 - `handleExceptionOrder()`: 处理异常订单 **依赖**: - `InventoryService`: 管理库存 - `LogisticsService`: 安排物流 - `SettlementService`: 处理结算 ### 2.3 定价服务 (PricingService) **职责**:负责商品定价和利润计算 **核心方法**: - `calculatePrice()`: 计算商品价格 - `calculateROI()`: 计算投资回报率 - `calculateProfit()`: 计算利润 - `getPricingStrategy()`: 获取定价策略 - `updatePricingStrategy()`: 更新定价策略 **依赖**: - `CostService`: 计算成本 - `MarketService`: 分析市场价格 ### 2.4 库存服务 (InventoryService) **职责**:管理库存,包括库存查询、扣减、预警等 **核心方法**: - `getInventory()`: 获取库存信息 - `updateInventory()`: 更新库存 - `deductInventory()`: 扣减库存 - `reserveInventory()`: 预留库存 - `releaseInventory()`: 释放预留库存 - `getInventoryAlert()`: 获取库存预警 **依赖**: - `WarehouseService`: 管理仓库 ### 2.5 物流服务 (LogisticsService) **职责**:管理物流,包括物流选择、追踪、费用计算等 **核心方法**: - `selectLogisticsChannel()`: 选择物流渠道 - `calculateFreight()`: 计算运费 - `trackLogistics()`: 追踪物流状态 - `createShippingLabel()`: 创建 shipping label **依赖**: - `ThirdPartyLogisticsAPI`: 对接第三方物流 API ### 2.6 结算服务 (SettlementService) **职责**:管理结算,包括收入计算、佣金扣除、打款等 **核心方法**: - `calculateSettlement()`: 计算结算金额 - `processSettlement()`: 处理结算 - `createSettlementBill()`: 创建结算账单 - `processPayment()`: 处理付款 **依赖**: - `FinanceService`: 财务管理 - `PaymentService`: 支付处理 ### 2.7 商户服务 (MerchantService) **职责**:管理商户,包括商户注册、认证、管理等 **核心方法**: - `registerMerchant()`: 注册商户 - `verifyMerchant()`: 验证商户资质 - `getMerchantById()`: 获取商户详情 - `updateMerchant()`: 更新商户信息 - `suspendMerchant()`: 暂停商户 - `activateMerchant()`: 激活商户 **依赖**: - `VerificationService`: 资质验证 - `RBACService`: 权限管理 ### 2.8 权限服务 (RBACService) **职责**:管理权限,包括角色定义、权限分配等 **核心方法**: - `createRole()`: 创建角色 - `assignPermission()`: 分配权限 - `checkPermission()`: 检查权限 - `getUserRoles()`: 获取用户角色 **依赖**: - `UserService`: 用户管理 ### 2.9 数据服务 (DataPipelineService) **职责**:管理数据采集、清洗、处理等 **核心方法**: - `collectData()`: 采集数据 - `cleanData()`: 清洗数据 - `processData()`: 处理数据 - `analyzeData()`: 分析数据 **依赖**: - `PlatformApiService`: 对接平台 API - `CrawlerService`: 网页爬虫 ### 2.10 AI 服务 (AIService) **职责**:提供 AI 相关功能,如智能定价、智能分析等 **核心方法**: - `predictPrice()`: 预测价格 - `analyzeMarket()`: 分析市场 - `optimizeStrategy()`: 优化策略 - `detectAnomaly()`: 检测异常 **依赖**: - `MachineLearningModel`: 机器学习模型 --- ## 3. 服务间调用规范 ### 3.1 同步调用 **适用场景**:需要立即获取结果的操作 **示例**: ```typescript // ProductService 调用 PricingService async updatePrice(productId: string, price: number): Promise { const product = await this.productRepository.findById(productId); const roi = await this.pricingService.calculateROI(product, price); product.price = price; product.roi = roi; return await this.productRepository.save(product); } ``` ### 3.2 异步调用 **适用场景**:不需要立即获取结果的操作,如发送通知、数据处理等 **示例**: ```typescript // OrderService 调用 NotificationService async processOrder(orderId: string): Promise { const order = await this.orderRepository.findById(orderId); // 处理订单 await this.orderRepository.save(order); // 异步发送通知 this.notificationService.sendOrderConfirmation(order).catch(err => { this.logger.error('Failed to send order confirmation', err); }); } ``` --- ## 4. 事务管理 ### 4.1 事务边界 **定义**:一组操作要么全部成功,要么全部失败 **示例**: ```typescript @Transactional() async createOrder(orderData: OrderCreateDto): Promise { // 1. 创建订单 const order = await this.orderRepository.create(orderData); // 2. 扣减库存 await this.inventoryService.deductInventory( orderData.productId, orderData.quantity ); // 3. 记录交易 await this.transactionRepository.create({ orderId: order.id, amount: order.totalAmount, type: 'ORDER_CREATED' }); return order; } ``` ### 4.2 幂等性 **定义**:同一个请求执行多次,结果应该相同 **实现**: - 使用唯一的 `requestId` - 记录已处理的请求 - 检查重复请求 **示例**: ```typescript async processPayment(paymentData: PaymentDto): Promise { // 检查是否已处理 const existingPayment = await this.paymentRepository.findByRequestId(paymentData.requestId); if (existingPayment) { return existingPayment; } // 处理支付 const payment = await this.paymentRepository.create(paymentData); return payment; } ``` --- ## 5. 错误处理 ### 5.1 业务错误 **定义**:业务逻辑错误,如库存不足、权限不足等 **处理**: - 抛出业务异常 - 上层捕获并返回适当的错误信息 **示例**: ```typescript async deductInventory(productId: string, quantity: number): Promise { const inventory = await this.inventoryRepository.findByProductId(productId); if (inventory.quantity < quantity) { throw new BusinessException('Insufficient inventory'); } inventory.quantity -= quantity; await this.inventoryRepository.save(inventory); } ``` ### 5.2 系统错误 **定义**:系统级错误,如数据库连接失败、API 调用失败等 **处理**: - 捕获系统异常 - 记录错误日志 - 尝试重试或降级策略 - 向上层返回适当的错误信息 **示例**: ```typescript async callExternalApi(endpoint: string, data: any): Promise { try { const response = await this.httpClient.post(endpoint, data); return response.data; } catch (error) { this.logger.error(`Failed to call external API: ${endpoint}`, error); throw new SystemException('External API error'); } } ``` --- ## 6. 日志和监控 ### 6.1 业务日志 **定义**:记录业务操作的日志 **内容**: - 操作人 - 操作时间 - 操作类型 - 操作对象 - 操作结果 **示例**: ```typescript async updatePrice(productId: string, price: number): Promise { this.logger.info(`Updating price for product ${productId} to ${price}`); try { const product = await this.productRepository.findById(productId); const roi = await this.pricingService.calculateROI(product, price); product.price = price; product.roi = roi; const updatedProduct = await this.productRepository.save(product); this.logger.info(`Successfully updated price for product ${productId}`, { oldPrice: product.oldPrice, newPrice: price, roi: roi }); return updatedProduct; } catch (error) { this.logger.error(`Failed to update price for product ${productId}`, error); throw error; } } ``` ### 6.2 性能监控 **定义**:监控服务性能 **指标**: - 响应时间 - 调用次数 - 错误率 - 资源使用情况 **实现**: - 使用 Prometheus 等监控工具 - 定期分析性能数据 - 优化性能瓶颈 --- ## 7. 服务版本管理 ### 7.1 版本控制 **定义**:管理服务的版本 **策略**: - 使用语义化版本号 - 向后兼容 - 版本迁移计划 ### 7.2 API 版本控制 **定义**:管理 API 的版本 **实现**: - 在 URL 中包含版本号 - 支持多个版本并存 - 逐步废弃旧版本 --- ## 8. 部署和扩展性 ### 8.1 部署策略 **定义**:服务的部署方式 **选项**: - 单体应用 - 微服务 - 容器化部署 ### 8.2 扩展性 **定义**:服务的扩展能力 **实现**: - 水平扩展 - 负载均衡 - 缓存策略 - 异步处理 --- ## 9. 相关文档 - [API_Specs](./API_Specs/) - [Database_Design](./Database_Design.md) - [Architecture_Overview](./Architecture_Overview.md) --- *本文档基于业务闭环设计,最后更新: 2026-03-18*