Explorar o código

Merge remote-tracking branch 'origin/dev' into prod

AI Assistant hai 6 meses
pai
achega
33adc1deba

+ 3 - 2
.augment-guidelines

@@ -1,7 +1,8 @@
 # Augment Guidelines for KKU Laravel Project
 
 ## 项目概述
-这是一个基于Laravel 11的农场游戏系统,本地使用Docker运行,访问地址:http://kku_laravel.local.gd
+- 这是一个基于Laravel 11的农场游戏系统
+- 项目本地使用Docker运行,访问地址:http://kku_laravel.local.gd
 - 当前项目处理维护期,不得随意对数据库的表结构进行修改,不得对涉及游戏数值的表进行修改
 
 ## 工作流程规范
@@ -89,7 +90,7 @@
 - 接口数据问题时优先检查数据结构字段名匹配
 - 注意Logic层返回字段名与Handler中访问字段名一致
 - Handler处理protobuf响应时确保所有必需字段有正确数据源
-- 使用 `php artisan debug:reproduce-error` 命令回放错误请求进行调试验证
+- 使用 `php artisan debug:reproduce-error {请求ID}` 命令回放错误请求进行调试验证,
 
 ## 特殊注意事项
 - 不使用数据库迁移,不注册路由(使用注解),不包含视图/前端资源/中间件/计划任务

+ 43 - 0
AiWork/202507/021252-git远程仓库重命名.md

@@ -0,0 +1,43 @@
+# Git 远程仓库重命名操作
+
+## 任务时间
+2025年07月02日 12:52
+
+## 任务描述
+设置 git lingma 的远程为主远程,处理旧远程
+
+## 执行操作
+
+### 1. 检查当前状态
+```bash
+git remote -v
+```
+原始配置:
+- origin: git@e.coding.net:g-ueau9359/kku/kku_laravel.git
+- lingma: git@e.coding.net:g-rqti0371/farm/kku_laravel.git
+
+### 2. 重命名远程仓库
+```bash
+# 将原 origin 重命名为 guomu
+git remote rename origin guomu
+
+# 将原 lingma 重命名为 origin(主远程)
+git remote rename lingma origin
+```
+
+### 3. 验证结果
+```bash
+git remote -v
+```
+最终配置:
+- origin: git@e.coding.net:g-rqti0371/farm/kku_laravel.git (主远程)
+- guomu: git@e.coding.net:g-ueau9359/kku/kku_laravel.git
+
+## 当前状态
+- 当前分支:dev
+- 上游分支:guomu/dev
+- 工作目录:clean
+
+## 备注
+- 操作成功完成
+- 如需要可以将当前分支上游设置为 origin/dev

+ 117 - 0
AiWork/2507/021323-模块梳理和README维护.md

@@ -0,0 +1,117 @@
+# 模块梳理和README.md维护任务
+
+## 任务概述
+以代码为准,梳理模块,维护 app/Module/README.md
+
+## 任务时间
+- 开始时间:2025年07月02日 13:23:44 CST
+- 完成时间:2025年07月02日 13:45:00 CST
+- 耗时:约21分钟
+
+## 发现的问题
+1. **模块数量不匹配**:文档显示35个,实际37个
+2. **新增模块未记录**:
+   - Cleanup - 数据清理模块(75%完成)
+   - Transfer - 新版划转系统(已完成)
+   - UrsPromotion - URS推广模块(开发中)
+3. **废弃模块未标记**:TransferOld(已被Transfer替代)
+4. **模块名称错误**:文档中的"Promotionurs"实际应该是"UrsPromotion"
+
+## 完成的工作
+
+### 1. 模块数量和分类更新
+- 模块总数:35个 → 37个
+- 重新分类为7大类:
+  - 🎮 核心业务模块 (8个)
+  - 💰 资金管理模块 (4个)
+  - 👥 用户与社交模块 (3个)
+  - 🔧 基础服务模块 (10个)
+  - 🛠️ 工具模块 (7个)
+  - 📝 内容模块 (2个)
+  - 🚀 扩展模块 (2个)
+
+### 2. 新增模块详细信息
+
+#### Transfer模块 - 划转系统
+- **状态**: ✅ 已完成
+- **功能**: 资金划转/流转系统,处理用户与外部系统之间的资金转入转出操作
+- **特点**: 基于TransferOld重新设计,采用现代化架构,支持完整的手续费统计功能
+
+#### Cleanup模块 - 数据清理模块
+- **状态**: 🔧 基础功能(75%完成)
+- **功能**: 专门用于数据清理的系统模块,提供灵活的数据清理配置和执行功能
+- **特点**: 主要用于测试环境数据清理,支持Model扫描和自动配置生成
+
+#### UrsPromotion模块 - URS推广模块
+- **状态**: 🚧 开发中
+- **功能**: 专门为URS业务场景设计的推广模块,管理URS用户推荐关系和团队收益分成
+- **特点**: 与Promotion模块完全独立,采用分离映射关系设计,支持跳过机制
+
+### 3. 废弃模块标记
+- **TransferOld模块**: 标记为⏸️已废弃,保留用于数据迁移和兼容性
+
+### 4. 模块状态分布更新
+- ✅ 已完成: 31个模块 (84%)
+- 🔧 基础功能: 3个模块 (8%)
+- 📋 文档阶段: 1个模块 (3%)
+- 🚧 开发中: 1个模块 (3%)
+- ⏸️ 已废弃: 1个模块 (3%)
+
+### 5. 依赖关系图更新
+- 移除不存在的Promotionurs模块
+- 添加Transfer、Cleanup、UrsPromotion模块
+- 更新模块间依赖关系
+- 添加扩展模块样式定义
+
+### 6. 核心依赖链更新
+```
+AppGame (适配层)
+    ↓
+Farm + GameItems + Pet + Shop + Activity + Task + Promotion (业务层)
+    ↓
+Fund + Point + Mex + Transfer (资金层)
+    ↓
+User + Friend + Game (用户层)
+    ↓
+ThirdParty + OpenAPI + Admin + System + File + Notification + Sms + Mail + Push + OAuth (基础服务层)
+    ↓
+UrsPromotion (扩展层)
+```
+
+## 技术细节
+
+### 文件修改
+- 文件路径:`app/Module/README.md`
+- 修改行数:约100+行
+- 主要修改:
+  - 更新模块总数和分类
+  - 添加新模块详细描述
+  - 更新依赖关系图
+  - 修正统计数据
+  - 更新最后修改时间
+
+### 模块发现方法
+```bash
+# 统计模块数量
+find app/Module -maxdepth 1 -type d -name "[A-Z]*" | wc -l
+
+# 列出所有模块
+find app/Module -maxdepth 1 -type d -name "[A-Z]*" | sort
+```
+
+## 验证结果
+- [x] 模块数量准确(37个)
+- [x] 新模块信息完整
+- [x] 废弃模块已标记
+- [x] 依赖关系图正确
+- [x] 统计数据准确
+- [x] 文档格式正确
+
+## 后续建议
+1. 定期检查模块变化,保持文档同步
+2. 新增模块时及时更新README.md
+3. 废弃模块时明确标记状态
+4. 考虑自动化脚本检测模块变化
+
+## 总结
+成功完成模块梳理和README.md维护任务,文档现在准确反映了系统的37个模块状态,包括新增的Transfer、Cleanup、UrsPromotion模块,以及废弃的TransferOld模块。所有模块信息、依赖关系和统计数据都已更新到最新状态。

+ 66 - 1
AiWork/now.md

@@ -1,2 +1,67 @@
-# 当前工作状态
+# 模块梳理和README.md维护任务
+
+## 任务概述
+以代码为准,梳理模块,维护 app/Module/README.md
+
+## 发现的问题
+1. **模块数量不匹配**:文档显示35个,实际37个
+2. **新增模块未记录**:
+   - Cleanup - 数据清理模块(75%完成)
+   - Transfer - 新版划转系统(已完成)
+   - UrsPromotion - URS推广模块(开发中)
+3. **废弃模块**:TransferOld(已被Transfer替代)
+4. **模块名称错误**:Promotionurs应为UrsPromotion
+
+## 工作计划
+- [x] 分析现有文档和实际模块
+- [x] 收集所有模块详细信息
+- [x] 重新分类模块
+- [x] 更新模块状态
+- [x] 修正依赖关系图
+- [x] 更新统计数据
+- [x] 更新README.md文件
+
+## 完成的工作
+1. **模块数量更新**:从35个更新为37个
+2. **新增模块记录**:
+   - Transfer模块(资金划转系统)- 已完成
+   - Cleanup模块(数据清理工具)- 基础功能75%
+   - UrsPromotion模块(URS推广系统)- 开发中
+3. **废弃模块标记**:TransferOld模块标记为已废弃
+4. **模块分类调整**:重新分类为7大类
+5. **依赖关系更新**:修正模块依赖关系图
+6. **统计数据更新**:更新状态分布图表
+
+## 当前进度
+✅ 模块梳理任务已完成
+🚧 SocialFarm模块创建中
+
+## 新任务:SocialFarm模块创建
+### 已完成工作
+- [x] 创建完整的模块目录结构
+- [x] 编写详细的README.md文档
+- [x] 设计数据库表结构和SQL文件
+- [x] 创建核心枚举类(STEAL_STATUS, SOCIAL_ACTION, VISIT_TYPE, HELP_TYPE)
+- [x] 实现主要服务类(SocialFarmService)
+- [x] 创建基础模型类(SocialFarmStealLog, SocialFarmSetting)
+- [x] 编写API接口文档
+- [x] 配置服务提供者和配置文件
+
+### 待完成工作
+- [ ] 创建逻辑层类(StealLogic, VisitLogic, HelpLogic, PermissionLogic)
+- [ ] 实现事件和监听器
+- [ ] 创建验证类和DTO类
+- [ ] 实现Handler层(AppGame模块集成)
+- [ ] 创建后台管理界面
+- [ ] 编写测试用例
+
+## Git提交记录
+- 模块梳理提交:✅ 成功 (commit: 95aea691)
+- SocialFarm模块:准备提交
+
+## 时间记录
+- 模块梳理开始:2025年07月02日 13:23:44 CST
+- 模块梳理完成:2025年07月02日 13:50:00 CST
+- SocialFarm开始:2025年07月02日 14:00:00 CST
+- 当前时间:2025年07月02日 14:30:00 CST
 

+ 6 - 2
app/Module/Game/Services/ConsumeTypeDescriptor.php

@@ -102,11 +102,15 @@ class ConsumeTypeDescriptor
     /**
      * 获取消耗类型的目标选项(用于表单)
      *
-     * @param int $consumeType 消耗类型
+     * @param int|null $consumeType 消耗类型
      * @return array 目标选项数组
      */
-    public static function getTargetOptions(int $consumeType): array
+    public static function getTargetOptions(?int $consumeType): array
     {
+        // 如果消耗类型为null,返回空数组
+        if ($consumeType === null) {
+            return [];
+        }
 
 //        dd($consumeType);
         switch ($consumeType) {

+ 107 - 47
app/Module/README.md

@@ -1,14 +1,14 @@
 # 开心农场系统模块目录
 
-> 更新时间:2025年06月14日 18:33:48 CST
+> 更新时间:2025年07月02日 13:23:44 CST
 
 ## 模块概览
 
-开心农场系统采用模块化架构设计,将不同的业务功能拆分为独立的模块,每个模块负责特定的业务领域。系统共包含 **35个模块**,分为核心业务模块、基础服务模块、工具模块和扩展模块四大类。
+开心农场系统采用模块化架构设计,将不同的业务功能拆分为独立的模块,每个模块负责特定的业务领域。系统共包含 **37个模块**,分为核心业务模块、资金管理模块、用户与社交模块、基础服务模块、工具模块、内容模块和扩展模块七大类。
 
 ## 模块列表
 
-### 🎮 [核心业务模块](#核心业务模块) (9个)
+### 🎮 [核心业务模块](#核心业务模块) (8个)
 - [AppGame - 游戏适配模块](#1-appgame---游戏适配模块) ✅
 - [Farm - 农场模块](#2-farm---农场模块) ✅
 - [GameItems - 游戏物品模块](#3-gameitems---游戏物品模块) ✅
@@ -18,11 +18,11 @@
 - [Task - 任务模块](#7-task---任务模块) ✅
 - [Promotion - 团队模块](#8-promotion---团队模块) ✅
 
-
-### 💰 [资金管理模块](#资金管理模块) (3个)
-- [Fund - 资金模块](#10-fund---资金模块) ✅
-- [Point - 积分模块](#11-point---积分模块) ✅
-- [Mex - 交易所模块](#12-mex---交易所模块) ✅
+### 💰 [资金管理模块](#资金管理模块) (4个)
+- [Fund - 资金模块](#9-fund---资金模块) ✅
+- [Point - 积分模块](#10-point---积分模块) ✅
+- [Mex - 交易所模块](#11-mex---交易所模块) ✅
+- [Transfer - 划转模块](#12-transfer---划转模块) ✅
 
 ### 👥 [用户与社交模块](#用户与社交模块) (3个)
 - [User - 用户模块](#13-user---用户模块) 🔧
@@ -41,21 +41,26 @@
 - [Push - 推送模块](#24-push---推送模块) ✅
 - [OAuth - OAuth认证模块](#25-oauth---oauth认证模块) ✅
 
-### 🛠️ [工具模块](#工具模块) (6个)
+### 🛠️ [工具模块](#工具模块) (7个)
 - [LCache - 本地缓存模块](#26-lcache---本地缓存模块) ✅
 - [DelayQueue - 延迟队列模块](#27-delayqueue---延迟队列模块) ✅
 - [Test - 测试模块](#28-test---测试模块) ✅
 - [Dev - 开发者模块](#29-dev---开发者模块) ✅
 - [Ulogic - 用户逻辑模块](#30-ulogic---用户逻辑模块) ✅
 - [Protobuf - Protobuf模块](#31-protobuf---protobuf模块) ✅
+- [Cleanup - 数据清理模块](#32-cleanup---数据清理模块) 🔧
 
 ### 📝 [内容模块](#内容模块) (2个)
-- [Article - 文章模块](#32-article---文章模块) 🔧
-- [China - 中国特殊内容模块](#33-china---中国特殊内容模块) ✅
+- [Article - 文章模块](#33-article---文章模块) 🔧
+- [China - 中国特殊内容模块](#34-china---中国特殊内容模块) ✅
+
+### 🚀 [扩展模块](#扩展模块) (2个)
+- [UrsPromotion - URS推广模块](#35-urspromotion---urs推广模块) 🚧
+- [TransferOld - 旧版划转模块](#36-transferold---旧版划转模块) ⏸️
 
 ## 模块分类
 
-### 🎮 核心业务模块 (9个)
+### 🎮 核心业务模块 (8个)
 
 这些模块构成了开心农场游戏的核心玩法和业务逻辑:
 
@@ -144,21 +149,7 @@
   - 团队数据统计
   - 推荐码生成
 
-#### 9. **Promotionurs** - 团队模块(增强版)
-- **路径**: `app/Module/Promotionurs`
-- **功能**: 完整的团队推荐系统,提供更强大的团队管理和收益分成功能
-- **状态**: ✅ 已完成
-- **核心功能**:
-  - 扁平化推荐关系存储(高效查询)
-  - 灵活的达人等级配置系统
-  - 多来源收益分成机制
-  - 团队关系缓存优化
-  - 推荐码管理和使用统计
-  - 邀请奖励系统
-  - 团队任务系统
-- **特点**: 采用事件驱动架构,支持异步处理,具备完整的缓存策略
-
-### 💰 资金管理模块 (3个)
+### 💰 资金管理模块 (4个)
 
 专门处理游戏内各种资金和积分的管理:
 
@@ -200,6 +191,19 @@
   - 交易记录
 - **特点**: 仓库账户USER_ID为15,调控账户USER_ID为16
 
+#### 13. **Transfer** - 划转模块
+- **路径**: `app/Module/Transfer`
+- **功能**: 资金划转/流转系统,处理用户与外部系统之间的资金转入转出操作
+- **状态**: ✅ 已完成
+- **核心功能**:
+  - 资金转入/转出管理
+  - 多应用支持和汇率转换
+  - 手续费机制和统计
+  - 订单管理和状态跟踪
+  - 自动化处理和回调
+  - 第三方应用集成
+- **特点**: 基于TransferOld重新设计,采用现代化架构,支持完整的手续费统计功能
+
 ### 👥 用户与社交模块 (3个)
 
 处理用户管理和社交功能:
@@ -340,7 +344,7 @@
   - 客户端管理
   - 访问令牌管理
 
-### 🛠️ 工具模块 (6个)
+### 🛠️ 工具模块 (7个)
 
 提供开发和运维工具:
 
@@ -384,6 +388,18 @@
 - **状态**: ✅ 已完成
 - **核心功能**: 枚举验证器
 
+#### 32. **Cleanup** - 数据清理模块
+- **路径**: `app/Module/Cleanup`
+- **功能**: 专门用于数据清理的系统模块,提供灵活的数据清理配置和执行功能
+- **状态**: 🔧 基础功能(75%完成)
+- **核心功能**:
+  - 灵活表选择(自定义、模块、分类、全量、混合)
+  - 5种清理类型(清空表、删除所有、按时间、按用户、按条件)
+  - 安全机制(多重确认、预览模式、自动备份)
+  - 批量处理和实时监控
+  - 命令行工具和后台管理
+- **特点**: 主要用于测试环境数据清理,支持Model扫描和自动配置生成
+
 ### 📝 内容模块 (2个)
 
 处理内容管理:
@@ -393,36 +409,60 @@
 - **功能**: 文章管理
 - **状态**: 🔧 基础功能
 
-#### 33. **China** - 中国特殊内容模块
+#### 34. **China** - 中国特殊内容模块
 - **路径**: `app/Module/China`
 - **功能**: 中国特殊内容模块
 - **状态**: ✅ 已完成
 
+### 🚀 扩展模块 (2个)
+
+处理特殊业务需求和扩展功能:
+
+#### 35. **UrsPromotion** - URS推广模块
+- **路径**: `app/Module/UrsPromotion`
+- **功能**: 专门为URS业务场景设计的推广模块,管理URS用户推荐关系和团队收益分成
+- **状态**: 🚧 开发中
+- **核心功能**:
+  - URS推荐关系管理(直推、间推、三推)
+  - URS达人等级系统(6个等级)
+  - URS团队收益分成(推广收益、种植收益)
+  - URS转账手续费配置(基于房屋等级和达人等级)
+  - 用户映射关系管理
+- **特点**: 与Promotion模块完全独立,采用分离映射关系设计,支持跳过机制
+
+#### 36. **TransferOld** - 旧版划转模块
+- **路径**: `app/Module/TransferOld`
+- **功能**: 旧版资金划转系统,已被Transfer模块替代
+- **状态**: ⏸️ 已废弃
+- **说明**: 保留用于数据迁移和兼容性,新功能请使用Transfer模块
+
 ## 模块状态说明
 
 - ✅ **已完成**: 模块功能完整,可正常使用
 - 🔧 **基础功能**: 模块基本功能可用,可能需要进一步完善
 - 📋 **文档阶段**: 模块处于设计文档阶段,未开始开发
 - 🚧 **开发中**: 模块正在开发中
-- ⏸️ **暂停**: 模块开发暂停
+- ⏸️ **已废弃**: 模块已废弃,不再维护
 
 ## 模块状态分布
 
 ### 状态分布图表
 
 ```mermaid
-pie title 模块状态分布 (总计35个模块)
-    "✅ 已完成" : 30
-    "🔧 基础功能" : 2
+pie title 模块状态分布 (总计37个模块)
+    "✅ 已完成" : 31
+    "🔧 基础功能" : 3
     "📋 文档阶段" : 1
-    "其他" : 2
+    "🚧 开发中" : 1
+    "⏸️ 已废弃" : 1
 ```
 
 ### 详细统计
-- ✅ **已完成**: 30个模块 (86%) - 功能完整,可正常使用
-- 🔧 **基础功能**: 2个模块 (6%) - 基本功能可用,需进一步完善
+- ✅ **已完成**: 31个模块 (84%) - 功能完整,可正常使用
+- 🔧 **基础功能**: 3个模块 (8%) - 基本功能可用,需进一步完善
 - 📋 **文档阶段**: 1个模块 (3%) - 处于设计文档阶段,未开始开发
-- **其他**: 2个模块 (6%) - 包含开发中、暂停等状态
+- 🚧 **开发中**: 1个模块 (3%) - 正在开发中
+- ⏸️ **已废弃**: 1个模块 (3%) - 已废弃,不再维护
 
 ## 模块依赖关系
 
@@ -441,12 +481,12 @@ graph TD
     Activity[Activity<br/>活动模块]
     Task[Task<br/>任务模块]
     Promotion[Promotion<br/>团队模块]
-    Promotionurs[Promotionurs<br/>团队模块增强版]
 
     %% 资金层
     Fund[Fund<br/>资金模块]
     Point[Point<br/>积分模块]
     Mex[Mex<br/>交易所模块]
+    Transfer[Transfer<br/>划转模块]
 
     %% 用户层
     User[User<br/>用户模块]
@@ -469,6 +509,10 @@ graph TD
     LCache[LCache<br/>本地缓存]
     DelayQueue[DelayQueue<br/>延迟队列]
     Ulogic[Ulogic<br/>用户逻辑]
+    Cleanup[Cleanup<br/>数据清理]
+
+    %% 扩展模块
+    UrsPromotion[UrsPromotion<br/>URS推广模块]
 
     %% 依赖关系
     AppGame --> Farm
@@ -478,7 +522,6 @@ graph TD
     AppGame --> Activity
     AppGame --> Task
     AppGame --> Promotion
-    AppGame --> Promotionurs
 
     Farm --> GameItems
     Pet --> GameItems
@@ -490,6 +533,7 @@ graph TD
     Activity --> Fund
     Mex --> Fund
     Point --> Fund
+    Transfer --> Fund
 
     Mex --> GameItems
     Pet --> Game
@@ -502,7 +546,7 @@ graph TD
     Activity --> User
     Task --> User
     Promotion --> User
-    Promotionurs --> User
+    UrsPromotion --> User
     Friend --> User
 
     Notification --> Sms
@@ -525,25 +569,29 @@ graph TD
     classDef userModule fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px
     classDef serviceModule fill:#fff3e0,stroke:#e65100,stroke-width:2px
     classDef toolModule fill:#fce4ec,stroke:#880e4f,stroke-width:2px
+    classDef extModule fill:#f1f8e9,stroke:#33691e,stroke-width:2px
 
-    class AppGame,Farm,GameItems,Pet,Shop,Activity,Task,Promotion,Promotionurs coreModule
-    class Fund,Point,Mex fundModule
+    class AppGame,Farm,GameItems,Pet,Shop,Activity,Task,Promotion coreModule
+    class Fund,Point,Mex,Transfer fundModule
     class User,Friend,Game userModule
     class ThirdParty,OpenAPI,Admin,System,File,Notification,Sms,Mail,Push,OAuth serviceModule
-    class LCache,DelayQueue,Ulogic toolModule
+    class LCache,DelayQueue,Ulogic,Cleanup toolModule
+    class UrsPromotion extModule
 ```
 
 ### 核心依赖链
 ```
 AppGame (适配层)
-Farm + GameItems + Pet + Shop + Activity + Task + Promotion + Promotionurs (业务层)
+Farm + GameItems + Pet + Shop + Activity + Task + Promotion (业务层)
-Fund + Point + Mex (资金层)
+Fund + Point + Mex + Transfer (资金层)
 User + Friend + Game (用户层)
 ThirdParty + OpenAPI + Admin + System + File + Notification + Sms + Mail + Push + OAuth (基础服务层)
+    ↓
+UrsPromotion (扩展层)
 ```
 
 ### 重要依赖关系
@@ -551,10 +599,13 @@ ThirdParty + OpenAPI + Admin + System + File + Notification + Sms + Mail + Push
 - **OpenAPI模块**: 为第三方应用提供API接入服务,依赖OAuth、User、Admin、System模块
 - **Admin模块**: 为所有模块提供后台基础功能和通用组件,依赖System、File、User模块
 - **GameItems模块**: 被Farm、Pet、Shop、Activity、Task等模块依赖
-- **Fund模块**: 被Mex、Shop、Activity等模块依赖,提供资金管理
+- **Fund模块**: 被Mex、Shop、Activity、Transfer等模块依赖,提供资金管理
 - **Point模块**: 基于Fund模块架构,专门处理积分
+- **Transfer模块**: 基于Fund模块,提供资金划转功能,替代TransferOld模块
 - **Notification模块**: 整合Sms、Mail、Push模块,提供统一通知接口
 - **Game模块**: 提供暂存系统,被Pet等模块使用
+- **UrsPromotion模块**: 独立的URS推广系统,与Promotion模块完全分离
+- **Cleanup模块**: 独立的数据清理工具,可清理所有模块数据
 
 ## 开发规范
 
@@ -600,6 +651,15 @@ app/Module/ModuleName/
 
 ## 最后更新
 
-本文档最后更新时间:**2025年06月14日 18:33:48 CST**
+本文档最后更新时间:**2025年07月02日 13:23:44 CST**
+
+### 本次更新内容
+- 更新模块总数从35个到37个
+- 新增Transfer模块(资金划转系统)
+- 新增Cleanup模块(数据清理工具)
+- 新增UrsPromotion模块(URS推广系统)
+- 标记TransferOld模块为已废弃
+- 修正模块分类和依赖关系
+- 更新统计图表和状态分布
 
 如需了解具体模块的详细信息,请查看各模块目录下的README.md文件。

+ 202 - 0
app/Module/SocialFarm/Databases/createsql/social_farm_tables.sql

@@ -0,0 +1,202 @@
+-- SocialFarm模块数据表创建SQL
+-- 创建时间: 2025-07-02
+-- 模块: SocialFarm
+-- 描述: 社交农场系统相关数据表
+
+-- 1. 偷菜记录表
+CREATE TABLE `kku_social_farm_steal_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `stealer_id` bigint(20) unsigned NOT NULL COMMENT '偷菜者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `land_id` bigint(20) unsigned NOT NULL COMMENT '被偷的土地ID',
+  `crop_id` bigint(20) unsigned NOT NULL COMMENT '被偷的作物ID',
+  `item_id` bigint(20) unsigned NOT NULL COMMENT '偷到的物品ID',
+  `item_amount` int(11) NOT NULL DEFAULT '0' COMMENT '偷到的物品数量',
+  `original_amount` int(11) NOT NULL DEFAULT '0' COMMENT '作物原始数量',
+  `steal_ratio` decimal(5,4) NOT NULL DEFAULT '0.0000' COMMENT '偷菜比例',
+  `steal_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '偷菜时间',
+  `steal_status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '偷菜状态:1成功,2失败,3被保护',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '偷菜者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_stealer_time` (`stealer_id`, `steal_time`),
+  KEY `idx_owner_time` (`owner_id`, `steal_time`),
+  KEY `idx_land_crop` (`land_id`, `crop_id`),
+  KEY `idx_steal_status` (`steal_status`, `steal_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='偷菜记录表';
+
+-- 2. 农场访问记录表
+CREATE TABLE `kku_social_farm_visit_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `visitor_id` bigint(20) unsigned NOT NULL COMMENT '访问者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `visit_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
+  `visit_type` tinyint(4) NOT NULL DEFAULT '1' COMMENT '访问类型:1普通访问,2偷菜访问,3互助访问',
+  `actions` json DEFAULT NULL COMMENT '访问期间的行为记录',
+  `duration` int(11) NOT NULL DEFAULT '0' COMMENT '访问持续时间(秒)',
+  `steal_count` int(11) NOT NULL DEFAULT '0' COMMENT '本次访问偷菜次数',
+  `help_count` int(11) NOT NULL DEFAULT '0' COMMENT '本次访问互助次数',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '访问者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_visitor_time` (`visitor_id`, `visit_time`),
+  KEY `idx_owner_time` (`owner_id`, `visit_time`),
+  KEY `idx_visit_type` (`visit_type`, `visit_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='农场访问记录表';
+
+-- 3. 社交设置表
+CREATE TABLE `kku_social_farm_settings` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `allow_steal` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许偷菜:1允许,0禁止',
+  `allow_help` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许互助:1允许,0禁止',
+  `allow_visit` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许访问:1允许,0禁止',
+  `steal_protection_hours` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜保护时长(小时)',
+  `daily_steal_limit` int(11) NOT NULL DEFAULT '10' COMMENT '每日被偷次数限制',
+  `daily_help_limit` int(11) NOT NULL DEFAULT '20' COMMENT '每日被帮助次数限制',
+  `notification_enabled` tinyint(4) NOT NULL DEFAULT '1' COMMENT '通知开关:1开启,0关闭',
+  `auto_revenge` tinyint(4) NOT NULL DEFAULT '0' COMMENT '自动反偷:1开启,0关闭',
+  `friend_only` tinyint(4) NOT NULL DEFAULT '1' COMMENT '仅好友可访问:1是,0否',
+  `blacklist_users` json DEFAULT NULL COMMENT '黑名单用户ID列表',
+  `whitelist_users` json DEFAULT NULL COMMENT '白名单用户ID列表',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_user_id` (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='社交农场设置表';
+
+-- 4. 互助记录表
+CREATE TABLE `kku_social_farm_help_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `helper_id` bigint(20) unsigned NOT NULL COMMENT '帮助者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `land_id` bigint(20) unsigned NOT NULL COMMENT '帮助的土地ID',
+  `help_type` tinyint(4) NOT NULL COMMENT '帮助类型:1浇水,2施肥,3除草,4杀虫,5收获',
+  `help_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '帮助时间',
+  `item_consumed_id` bigint(20) unsigned DEFAULT NULL COMMENT '消耗的道具ID',
+  `item_consumed_amount` int(11) NOT NULL DEFAULT '0' COMMENT '消耗的道具数量',
+  `reward_item_id` bigint(20) unsigned DEFAULT NULL COMMENT '奖励物品ID',
+  `reward_amount` int(11) NOT NULL DEFAULT '0' COMMENT '奖励数量',
+  `exp_reward` int(11) NOT NULL DEFAULT '0' COMMENT '经验奖励',
+  `help_effect` json DEFAULT NULL COMMENT '帮助效果详情',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '帮助者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_helper_time` (`helper_id`, `help_time`),
+  KEY `idx_owner_time` (`owner_id`, `help_time`),
+  KEY `idx_land_type` (`land_id`, `help_type`),
+  KEY `idx_help_type` (`help_type`, `help_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='互助记录表';
+
+-- 5. 社交统计表
+CREATE TABLE `kku_social_farm_stats` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `stat_date` date NOT NULL COMMENT '统计日期',
+  `steal_count` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜次数',
+  `stolen_count` int(11) NOT NULL DEFAULT '0' COMMENT '被偷次数',
+  `help_count` int(11) NOT NULL DEFAULT '0' COMMENT '帮助次数',
+  `helped_count` int(11) NOT NULL DEFAULT '0' COMMENT '被帮助次数',
+  `visit_count` int(11) NOT NULL DEFAULT '0' COMMENT '访问次数',
+  `visited_count` int(11) NOT NULL DEFAULT '0' COMMENT '被访问次数',
+  `steal_items_gained` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜获得物品数',
+  `steal_items_lost` int(11) NOT NULL DEFAULT '0' COMMENT '被偷失去物品数',
+  `help_rewards_gained` int(11) NOT NULL DEFAULT '0' COMMENT '互助获得奖励数',
+  `total_exp_gained` int(11) NOT NULL DEFAULT '0' COMMENT '总经验获得',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_user_date` (`user_id`, `stat_date`),
+  KEY `idx_stat_date` (`stat_date`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='社交农场统计表';
+
+-- 6. 偷菜保护记录表
+CREATE TABLE `kku_social_farm_protections` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `land_id` bigint(20) unsigned DEFAULT NULL COMMENT '土地ID(NULL表示全农场保护)',
+  `protection_type` tinyint(4) NOT NULL COMMENT '保护类型:1时间保护,2道具保护,3系统保护',
+  `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '保护开始时间',
+  `end_time` timestamp NOT NULL COMMENT '保护结束时间',
+  `protection_item_id` bigint(20) unsigned DEFAULT NULL COMMENT '保护道具ID',
+  `is_active` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否激活:1激活,0失效',
+  `created_by` bigint(20) unsigned DEFAULT NULL COMMENT '创建者ID',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_user_active` (`user_id`, `is_active`),
+  KEY `idx_land_active` (`land_id`, `is_active`),
+  KEY `idx_end_time` (`end_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='偷菜保护记录表';
+
+-- 插入默认配置数据
+-- 注意:实际使用时需要根据具体需求调整这些默认值
+
+-- 为现有用户创建默认社交设置(如果需要)
+-- INSERT INTO kku_social_farm_settings (user_id) 
+-- SELECT id FROM kku_users 
+-- WHERE id NOT IN (SELECT user_id FROM kku_social_farm_settings);
+
+-- 创建索引优化查询性能
+-- 这些索引在表创建时已经包含,这里仅作为说明
+
+-- 偷菜记录表的复合索引
+-- ALTER TABLE kku_social_farm_steal_logs ADD INDEX idx_stealer_owner_time (stealer_id, owner_id, steal_time);
+
+-- 访问记录表的复合索引  
+-- ALTER TABLE kku_social_farm_visit_logs ADD INDEX idx_visitor_owner_time (visitor_id, owner_id, visit_time);
+
+-- 互助记录表的复合索引
+-- ALTER TABLE kku_social_farm_help_logs ADD INDEX idx_helper_owner_time (helper_id, owner_id, help_time);
+
+-- 统计表的日期范围索引
+-- ALTER TABLE kku_social_farm_stats ADD INDEX idx_user_date_range (user_id, stat_date);
+
+-- 保护表的时间范围索引
+-- ALTER TABLE kku_social_farm_protections ADD INDEX idx_time_range (start_time, end_time);
+
+-- 创建视图用于常用查询(可选)
+
+-- 用户每日偷菜统计视图
+CREATE VIEW v_daily_steal_stats AS
+SELECT 
+    user_id,
+    DATE(steal_time) as steal_date,
+    COUNT(*) as steal_count,
+    SUM(item_amount) as total_items
+FROM kku_social_farm_steal_logs 
+WHERE steal_status = 1
+GROUP BY user_id, DATE(steal_time);
+
+-- 用户社交活跃度视图
+CREATE VIEW v_user_social_activity AS
+SELECT 
+    u.id as user_id,
+    u.nickname,
+    COALESCE(s.steal_count, 0) as today_steal_count,
+    COALESCE(s.help_count, 0) as today_help_count,
+    COALESCE(s.visit_count, 0) as today_visit_count,
+    COALESCE(settings.allow_steal, 1) as allow_steal,
+    COALESCE(settings.allow_help, 1) as allow_help,
+    COALESCE(settings.allow_visit, 1) as allow_visit
+FROM kku_users u
+LEFT JOIN kku_social_farm_stats s ON u.id = s.user_id AND s.stat_date = CURDATE()
+LEFT JOIN kku_social_farm_settings settings ON u.id = settings.user_id;
+
+-- 添加表注释说明
+ALTER TABLE kku_social_farm_steal_logs COMMENT = '偷菜记录表 - 记录所有偷菜行为的详细信息';
+ALTER TABLE kku_social_farm_visit_logs COMMENT = '农场访问记录表 - 记录用户访问好友农场的行为';
+ALTER TABLE kku_social_farm_settings COMMENT = '社交设置表 - 存储用户的社交农场相关设置';
+ALTER TABLE kku_social_farm_help_logs COMMENT = '互助记录表 - 记录用户间的互助行为';
+ALTER TABLE kku_social_farm_stats COMMENT = '社交统计表 - 记录用户的社交行为统计数据';
+ALTER TABLE kku_social_farm_protections COMMENT = '偷菜保护记录表 - 记录偷菜保护状态';
+
+-- 数据表创建完成
+-- 请根据实际需求调整表结构和索引策略
+-- 建议在生产环境部署前进行充分的性能测试

+ 448 - 0
app/Module/SocialFarm/Docs/API接口文档.md

@@ -0,0 +1,448 @@
+# SocialFarm模块API接口文档
+
+## 概述
+
+SocialFarm模块提供社交农场功能的API接口,包括偷菜、互助、访问等功能。所有接口都需要用户认证。
+
+## 基础信息
+
+- **模块路径**: `/api/social-farm`
+- **认证方式**: Bearer Token
+- **响应格式**: JSON
+- **字符编码**: UTF-8
+
+## 通用响应格式
+
+### 成功响应
+```json
+{
+    "success": true,
+    "data": {
+        // 具体数据
+    },
+    "message": "操作成功"
+}
+```
+
+### 失败响应
+```json
+{
+    "success": false,
+    "code": "ERROR_CODE",
+    "message": "错误描述",
+    "data": null
+}
+```
+
+## 接口列表
+
+### 1. 获取可偷菜的好友列表
+
+**接口地址**: `GET /api/social-farm/stealable-friends`
+
+**功能描述**: 获取当前用户可以偷菜的好友列表
+
+**请求参数**: 无
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": [
+        {
+            "user_id": 123,
+            "nickname": "农场主小明",
+            "avatar": "https://example.com/avatar.jpg",
+            "level": 15,
+            "stealable_count": 3,
+            "last_visit_time": "2025-07-02 10:30:00"
+        }
+    ]
+}
+```
+
+### 2. 访问好友农场
+
+**接口地址**: `POST /api/social-farm/visit-farm`
+
+**功能描述**: 访问指定好友的农场
+
+**请求参数**:
+```json
+{
+    "owner_id": 123,
+    "visit_type": 1
+}
+```
+
+**参数说明**:
+- `owner_id`: 农场主用户ID (必填)
+- `visit_type`: 访问类型 (可选,默认1普通访问)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "visit_id": 456,
+        "farm_info": {
+            "owner": {
+                "user_id": 123,
+                "nickname": "农场主小明",
+                "level": 15
+            },
+            "lands": [
+                {
+                    "id": 1,
+                    "position_x": 0,
+                    "position_y": 0,
+                    "crop": {
+                        "id": 789,
+                        "item_id": 1001,
+                        "item_name": "胡萝卜",
+                        "growth_stage": 4,
+                        "is_mature": true,
+                        "can_steal": true,
+                        "steal_reason": ""
+                    },
+                    "help_types": [1, 2]
+                }
+            ]
+        },
+        "permissions": {
+            "can_steal": true,
+            "can_help": true,
+            "daily_steal_remaining": 8
+        }
+    }
+}
+```
+
+### 3. 偷菜操作
+
+**接口地址**: `POST /api/social-farm/steal-crop`
+
+**功能描述**: 偷取指定土地的作物
+
+**请求参数**:
+```json
+{
+    "owner_id": 123,
+    "land_id": 456
+}
+```
+
+**参数说明**:
+- `owner_id`: 农场主用户ID (必填)
+- `land_id`: 土地ID (必填)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "steal_id": 789,
+        "item_id": 1001,
+        "item_name": "胡萝卜",
+        "item_amount": 5,
+        "original_amount": 20,
+        "steal_ratio": 0.25,
+        "exp_gained": 10,
+        "message": "成功偷到5个胡萝卜!"
+    }
+}
+```
+
+**错误响应示例**:
+```json
+{
+    "success": false,
+    "code": "CROP_NOT_READY",
+    "message": "作物还未成熟,无法偷菜"
+}
+```
+
+### 4. 互助操作
+
+**接口地址**: `POST /api/social-farm/help-friend`
+
+**功能描述**: 帮助好友处理农场事务
+
+**请求参数**:
+```json
+{
+    "owner_id": 123,
+    "land_id": 456,
+    "help_type": 1
+}
+```
+
+**参数说明**:
+- `owner_id`: 农场主用户ID (必填)
+- `land_id`: 土地ID (必填)
+- `help_type`: 帮助类型 (必填,1浇水 2施肥 3除草 4杀虫 5收获)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "help_id": 321,
+        "help_type": 1,
+        "help_type_name": "浇水",
+        "exp_gained": 5,
+        "reward_item": {
+            "item_id": 2001,
+            "item_name": "经验药水",
+            "amount": 1
+        },
+        "message": "成功帮助好友浇水,获得5点经验!"
+    }
+}
+```
+
+### 5. 获取用户社交设置
+
+**接口地址**: `GET /api/social-farm/settings`
+
+**功能描述**: 获取当前用户的社交农场设置
+
+**请求参数**: 无
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "allow_steal": true,
+        "allow_help": true,
+        "allow_visit": true,
+        "steal_protection_hours": 2,
+        "daily_steal_limit": 10,
+        "daily_help_limit": 20,
+        "notification_enabled": true,
+        "auto_revenge": false,
+        "friend_only": true,
+        "blacklist_count": 0,
+        "whitelist_count": 0
+    }
+}
+```
+
+### 6. 更新用户社交设置
+
+**接口地址**: `PUT /api/social-farm/settings`
+
+**功能描述**: 更新当前用户的社交农场设置
+
+**请求参数**:
+```json
+{
+    "allow_steal": true,
+    "allow_help": true,
+    "allow_visit": true,
+    "steal_protection_hours": 2,
+    "daily_steal_limit": 10,
+    "daily_help_limit": 20,
+    "notification_enabled": true,
+    "auto_revenge": false,
+    "friend_only": true
+}
+```
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "allow_steal": true,
+        "allow_help": true,
+        "allow_visit": true,
+        "steal_protection_hours": 2,
+        "daily_steal_limit": 10,
+        "daily_help_limit": 20,
+        "notification_enabled": true,
+        "auto_revenge": false,
+        "friend_only": true
+    },
+    "message": "设置更新成功"
+}
+```
+
+### 7. 获取社交统计
+
+**接口地址**: `GET /api/social-farm/stats`
+
+**功能描述**: 获取用户的社交行为统计数据
+
+**请求参数**:
+- `date`: 统计日期 (可选,格式:YYYY-MM-DD,默认今天)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "steal_count": 5,
+        "stolen_count": 3,
+        "help_count": 8,
+        "helped_count": 6,
+        "visit_count": 12,
+        "visited_count": 9,
+        "steal_items_gained": 25,
+        "steal_items_lost": 15,
+        "help_rewards_gained": 3,
+        "total_exp_gained": 45
+    }
+}
+```
+
+### 8. 获取偷菜记录
+
+**接口地址**: `GET /api/social-farm/steal-logs`
+
+**功能描述**: 获取用户的偷菜记录
+
+**请求参数**:
+- `type`: 记录类型 (可选,steal我偷的 stolen被偷的,默认steal)
+- `page`: 页码 (可选,默认1)
+- `limit`: 每页数量 (可选,默认20)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "items": [
+            {
+                "id": 123,
+                "stealer": {
+                    "user_id": 456,
+                    "nickname": "偷菜小能手"
+                },
+                "owner": {
+                    "user_id": 789,
+                    "nickname": "农场主大佬"
+                },
+                "item": {
+                    "item_id": 1001,
+                    "item_name": "胡萝卜",
+                    "amount": 5
+                },
+                "steal_time": "2025-07-02 14:30:00",
+                "steal_status": 1,
+                "steal_status_desc": "偷菜成功"
+            }
+        ],
+        "pagination": {
+            "current_page": 1,
+            "total_pages": 5,
+            "total_items": 100,
+            "per_page": 20
+        }
+    }
+}
+```
+
+### 9. 获取访问记录
+
+**接口地址**: `GET /api/social-farm/visit-logs`
+
+**功能描述**: 获取农场访问记录
+
+**请求参数**:
+- `type`: 记录类型 (可选,visit我访问的 visited被访问的,默认visit)
+- `page`: 页码 (可选,默认1)
+- `limit`: 每页数量 (可选,默认20)
+
+**响应示例**:
+```json
+{
+    "success": true,
+    "data": {
+        "items": [
+            {
+                "id": 456,
+                "visitor": {
+                    "user_id": 123,
+                    "nickname": "访客小明"
+                },
+                "owner": {
+                    "user_id": 789,
+                    "nickname": "农场主大佬"
+                },
+                "visit_time": "2025-07-02 15:20:00",
+                "visit_type": 2,
+                "visit_type_desc": "偷菜访问",
+                "duration": 180,
+                "steal_count": 2,
+                "help_count": 1
+            }
+        ],
+        "pagination": {
+            "current_page": 1,
+            "total_pages": 3,
+            "total_items": 60,
+            "per_page": 20
+        }
+    }
+}
+```
+
+## 错误码说明
+
+| 错误码 | 描述 |
+|--------|------|
+| NO_PERMISSION | 无权限访问 |
+| NOT_FRIEND | 不是好友关系 |
+| FARM_NOT_FOUND | 农场不存在 |
+| LAND_NOT_FOUND | 土地不存在 |
+| CROP_NOT_FOUND | 作物不存在 |
+| CROP_NOT_READY | 作物未成熟 |
+| ALREADY_STOLEN | 作物已被偷过 |
+| STEAL_LIMIT_EXCEEDED | 超过偷菜次数限制 |
+| HELP_LIMIT_EXCEEDED | 超过互助次数限制 |
+| UNDER_PROTECTION | 农场受保护中 |
+| INSUFFICIENT_ITEMS | 道具不足 |
+| INVALID_HELP_TYPE | 无效的帮助类型 |
+| OPERATION_FAILED | 操作失败 |
+
+## 状态码说明
+
+### 偷菜状态 (steal_status)
+- 1: 偷菜成功
+- 2: 偷菜失败
+- 3: 受保护无法偷
+- 4: 无权限偷菜
+- 5: 超过次数限制
+- 6: 作物未成熟
+- 7: 已被偷过
+
+### 访问类型 (visit_type)
+- 1: 普通访问
+- 2: 偷菜访问
+- 3: 互助访问
+- 4: 社交访问
+- 5: 报复访问
+
+### 帮助类型 (help_type)
+- 1: 浇水
+- 2: 施肥
+- 3: 除草
+- 4: 杀虫
+- 5: 收获
+
+## 注意事项
+
+1. **频率限制**: 每个用户每分钟最多调用100次API
+2. **数据缓存**: 农场信息会缓存5分钟,偷菜后立即更新
+3. **事务处理**: 偷菜和互助操作使用数据库事务确保数据一致性
+4. **日志记录**: 所有关键操作都会记录详细日志
+5. **安全验证**: 所有操作前都会验证用户权限和好友关系
+
+## 开发建议
+
+1. **错误处理**: 客户端应该妥善处理各种错误情况
+2. **用户体验**: 建议在操作前显示确认对话框
+3. **数据刷新**: 操作成功后应该刷新相关页面数据
+4. **离线处理**: 网络异常时应该提供重试机制

+ 309 - 0
app/Module/SocialFarm/Docs/数据库设计.md

@@ -0,0 +1,309 @@
+# SocialFarm模块数据库设计
+
+## 概述
+
+SocialFarm模块的数据库设计围绕社交农场互动功能,主要包括偷菜记录、访问记录、互助记录和用户社交设置等核心数据表。
+
+## 数据表设计
+
+### 1. 偷菜记录表 (kku_social_farm_steal_logs)
+
+记录所有偷菜行为的详细信息。
+
+```sql
+CREATE TABLE `kku_social_farm_steal_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `stealer_id` bigint(20) unsigned NOT NULL COMMENT '偷菜者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `land_id` bigint(20) unsigned NOT NULL COMMENT '被偷的土地ID',
+  `crop_id` bigint(20) unsigned NOT NULL COMMENT '被偷的作物ID',
+  `item_id` bigint(20) unsigned NOT NULL COMMENT '偷到的物品ID',
+  `item_amount` int(11) NOT NULL DEFAULT '0' COMMENT '偷到的物品数量',
+  `original_amount` int(11) NOT NULL DEFAULT '0' COMMENT '作物原始数量',
+  `steal_ratio` decimal(5,4) NOT NULL DEFAULT '0.0000' COMMENT '偷菜比例',
+  `steal_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '偷菜时间',
+  `steal_status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '偷菜状态:1成功,2失败,3被保护',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '偷菜者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_stealer_time` (`stealer_id`, `steal_time`),
+  KEY `idx_owner_time` (`owner_id`, `steal_time`),
+  KEY `idx_land_crop` (`land_id`, `crop_id`),
+  KEY `idx_steal_status` (`steal_status`, `steal_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='偷菜记录表';
+```
+
+### 2. 农场访问记录表 (kku_social_farm_visit_logs)
+
+记录用户访问好友农场的行为。
+
+```sql
+CREATE TABLE `kku_social_farm_visit_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `visitor_id` bigint(20) unsigned NOT NULL COMMENT '访问者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `visit_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
+  `visit_type` tinyint(4) NOT NULL DEFAULT '1' COMMENT '访问类型:1普通访问,2偷菜访问,3互助访问',
+  `actions` json DEFAULT NULL COMMENT '访问期间的行为记录',
+  `duration` int(11) NOT NULL DEFAULT '0' COMMENT '访问持续时间(秒)',
+  `steal_count` int(11) NOT NULL DEFAULT '0' COMMENT '本次访问偷菜次数',
+  `help_count` int(11) NOT NULL DEFAULT '0' COMMENT '本次访问互助次数',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '访问者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_visitor_time` (`visitor_id`, `visit_time`),
+  KEY `idx_owner_time` (`owner_id`, `visit_time`),
+  KEY `idx_visit_type` (`visit_type`, `visit_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='农场访问记录表';
+```
+
+### 3. 社交设置表 (kku_social_farm_settings)
+
+存储用户的社交农场相关设置。
+
+```sql
+CREATE TABLE `kku_social_farm_settings` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `allow_steal` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许偷菜:1允许,0禁止',
+  `allow_help` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许互助:1允许,0禁止',
+  `allow_visit` tinyint(4) NOT NULL DEFAULT '1' COMMENT '允许访问:1允许,0禁止',
+  `steal_protection_hours` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜保护时长(小时)',
+  `daily_steal_limit` int(11) NOT NULL DEFAULT '10' COMMENT '每日被偷次数限制',
+  `daily_help_limit` int(11) NOT NULL DEFAULT '20' COMMENT '每日被帮助次数限制',
+  `notification_enabled` tinyint(4) NOT NULL DEFAULT '1' COMMENT '通知开关:1开启,0关闭',
+  `auto_revenge` tinyint(4) NOT NULL DEFAULT '0' COMMENT '自动反偷:1开启,0关闭',
+  `friend_only` tinyint(4) NOT NULL DEFAULT '1' COMMENT '仅好友可访问:1是,0否',
+  `blacklist_users` json DEFAULT NULL COMMENT '黑名单用户ID列表',
+  `whitelist_users` json DEFAULT NULL COMMENT '白名单用户ID列表',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_user_id` (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='社交农场设置表';
+```
+
+### 4. 互助记录表 (kku_social_farm_help_logs)
+
+记录用户间的互助行为。
+
+```sql
+CREATE TABLE `kku_social_farm_help_logs` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `helper_id` bigint(20) unsigned NOT NULL COMMENT '帮助者用户ID',
+  `owner_id` bigint(20) unsigned NOT NULL COMMENT '农场主用户ID',
+  `land_id` bigint(20) unsigned NOT NULL COMMENT '帮助的土地ID',
+  `help_type` tinyint(4) NOT NULL COMMENT '帮助类型:1浇水,2施肥,3除草,4杀虫,5收获',
+  `help_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '帮助时间',
+  `item_consumed_id` bigint(20) unsigned DEFAULT NULL COMMENT '消耗的道具ID',
+  `item_consumed_amount` int(11) NOT NULL DEFAULT '0' COMMENT '消耗的道具数量',
+  `reward_item_id` bigint(20) unsigned DEFAULT NULL COMMENT '奖励物品ID',
+  `reward_amount` int(11) NOT NULL DEFAULT '0' COMMENT '奖励数量',
+  `exp_reward` int(11) NOT NULL DEFAULT '0' COMMENT '经验奖励',
+  `help_effect` json DEFAULT NULL COMMENT '帮助效果详情',
+  `ip_address` varchar(45) DEFAULT NULL COMMENT '帮助者IP地址',
+  `user_agent` text COMMENT '用户代理信息',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_helper_time` (`helper_id`, `help_time`),
+  KEY `idx_owner_time` (`owner_id`, `help_time`),
+  KEY `idx_land_type` (`land_id`, `help_type`),
+  KEY `idx_help_type` (`help_type`, `help_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='互助记录表';
+```
+
+### 5. 社交统计表 (kku_social_farm_stats)
+
+记录用户的社交行为统计数据。
+
+```sql
+CREATE TABLE `kku_social_farm_stats` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `stat_date` date NOT NULL COMMENT '统计日期',
+  `steal_count` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜次数',
+  `stolen_count` int(11) NOT NULL DEFAULT '0' COMMENT '被偷次数',
+  `help_count` int(11) NOT NULL DEFAULT '0' COMMENT '帮助次数',
+  `helped_count` int(11) NOT NULL DEFAULT '0' COMMENT '被帮助次数',
+  `visit_count` int(11) NOT NULL DEFAULT '0' COMMENT '访问次数',
+  `visited_count` int(11) NOT NULL DEFAULT '0' COMMENT '被访问次数',
+  `steal_items_gained` int(11) NOT NULL DEFAULT '0' COMMENT '偷菜获得物品数',
+  `steal_items_lost` int(11) NOT NULL DEFAULT '0' COMMENT '被偷失去物品数',
+  `help_rewards_gained` int(11) NOT NULL DEFAULT '0' COMMENT '互助获得奖励数',
+  `total_exp_gained` int(11) NOT NULL DEFAULT '0' COMMENT '总经验获得',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_user_date` (`user_id`, `stat_date`),
+  KEY `idx_stat_date` (`stat_date`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='社交农场统计表';
+```
+
+### 6. 偷菜保护记录表 (kku_social_farm_protections)
+
+记录偷菜保护状态。
+
+```sql
+CREATE TABLE `kku_social_farm_protections` (
+  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
+  `land_id` bigint(20) unsigned DEFAULT NULL COMMENT '土地ID(NULL表示全农场保护)',
+  `protection_type` tinyint(4) NOT NULL COMMENT '保护类型:1时间保护,2道具保护,3系统保护',
+  `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '保护开始时间',
+  `end_time` timestamp NOT NULL COMMENT '保护结束时间',
+  `protection_item_id` bigint(20) unsigned DEFAULT NULL COMMENT '保护道具ID',
+  `is_active` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否激活:1激活,0失效',
+  `created_by` bigint(20) unsigned DEFAULT NULL COMMENT '创建者ID',
+  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  KEY `idx_user_active` (`user_id`, `is_active`),
+  KEY `idx_land_active` (`land_id`, `is_active`),
+  KEY `idx_end_time` (`end_time`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='偷菜保护记录表';
+```
+
+## 索引设计说明
+
+### 主要索引策略
+
+1. **时间范围查询索引**
+   - `idx_stealer_time`: 支持查询某用户的偷菜历史
+   - `idx_owner_time`: 支持查询某农场的被偷历史
+   - `idx_visitor_time`: 支持查询访问记录
+
+2. **状态查询索引**
+   - `idx_steal_status`: 支持按偷菜状态查询
+   - `idx_visit_type`: 支持按访问类型查询
+   - `idx_help_type`: 支持按帮助类型查询
+
+3. **关联查询索引**
+   - `idx_land_crop`: 支持土地作物关联查询
+   - `idx_user_active`: 支持用户保护状态查询
+
+## 数据完整性约束
+
+### 外键关系
+
+虽然表结构中没有显式定义外键约束,但存在以下逻辑外键关系:
+
+1. **用户关系**
+   - `stealer_id`, `owner_id`, `visitor_id`, `helper_id` → `kku_users.id`
+   - `user_id` → `kku_users.id`
+
+2. **农场关系**
+   - `land_id` → `kku_farm_land_users.id`
+   - `crop_id` → `kku_farm_crop_users.id`
+
+3. **物品关系**
+   - `item_id`, `reward_item_id` → `kku_item_configs.id`
+
+### 数据验证规则
+
+1. **偷菜记录验证**
+   - `stealer_id` ≠ `owner_id` (不能偷自己的菜)
+   - `item_amount` > 0 (偷到的数量必须大于0)
+   - `steal_ratio` ∈ [0, 1] (偷菜比例在0-1之间)
+
+2. **访问记录验证**
+   - `visitor_id` ≠ `owner_id` (不记录访问自己农场)
+   - `duration` ≥ 0 (访问时长不能为负)
+
+3. **设置表验证**
+   - `steal_protection_hours` ≥ 0 (保护时长不能为负)
+   - `daily_steal_limit` > 0 (每日限制必须大于0)
+
+## 性能优化建议
+
+### 1. 分区策略
+
+对于日志类表,建议按时间分区:
+
+```sql
+-- 偷菜记录表按月分区
+ALTER TABLE kku_social_farm_steal_logs 
+PARTITION BY RANGE (YEAR(steal_time) * 100 + MONTH(steal_time)) (
+    PARTITION p202501 VALUES LESS THAN (202502),
+    PARTITION p202502 VALUES LESS THAN (202503),
+    -- ... 更多分区
+);
+```
+
+### 2. 数据清理策略
+
+定期清理过期数据:
+
+```sql
+-- 清理3个月前的访问记录
+DELETE FROM kku_social_farm_visit_logs 
+WHERE visit_time < DATE_SUB(NOW(), INTERVAL 3 MONTH);
+
+-- 清理6个月前的偷菜记录
+DELETE FROM kku_social_farm_steal_logs 
+WHERE steal_time < DATE_SUB(NOW(), INTERVAL 6 MONTH);
+```
+
+### 3. 缓存策略
+
+建议缓存的数据:
+
+1. **用户社交设置**: 缓存时间1小时
+2. **每日统计数据**: 缓存时间30分钟
+3. **保护状态**: 缓存时间10分钟
+4. **好友农场状态**: 缓存时间5分钟
+
+## 数据迁移注意事项
+
+### 1. 初始化数据
+
+新用户注册时需要初始化社交设置:
+
+```sql
+INSERT INTO kku_social_farm_settings (user_id) 
+VALUES (?) 
+ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;
+```
+
+### 2. 历史数据处理
+
+如果有历史的偷菜数据需要迁移,注意:
+
+1. 数据格式转换
+2. 时间戳统一
+3. 状态码映射
+4. 用户ID验证
+
+### 3. 数据一致性检查
+
+定期执行数据一致性检查:
+
+```sql
+-- 检查孤立的偷菜记录
+SELECT * FROM kku_social_farm_steal_logs s
+LEFT JOIN kku_users u1 ON s.stealer_id = u1.id
+LEFT JOIN kku_users u2 ON s.owner_id = u2.id
+WHERE u1.id IS NULL OR u2.id IS NULL;
+```
+
+## 备份和恢复策略
+
+### 1. 备份策略
+
+- **全量备份**: 每日凌晨执行
+- **增量备份**: 每4小时执行
+- **日志备份**: 实时备份binlog
+
+### 2. 恢复策略
+
+- **数据恢复**: 基于时间点恢复
+- **表恢复**: 单表恢复机制
+- **应急恢复**: 快速恢复关键表
+
+---
+
+本文档详细描述了SocialFarm模块的数据库设计,包括表结构、索引、约束和优化建议。在实际开发中,请根据具体需求调整表结构和索引策略。

+ 149 - 0
app/Module/SocialFarm/Enums/HELP_TYPE.php

@@ -0,0 +1,149 @@
+<?php
+
+namespace App\Module\SocialFarm\Enums;
+
+/**
+ * 互助类型枚举
+ * 
+ * 定义农场互助的各种类型
+ */
+enum HELP_TYPE: int
+{
+    case WATER = 1;      // 浇水
+    case FERTILIZE = 2;  // 施肥
+    case WEED = 3;       // 除草
+    case PEST = 4;       // 杀虫
+    case HARVEST = 5;    // 收获
+
+    /**
+     * 获取互助类型描述
+     */
+    public function getDescription(): string
+    {
+        return match($this) {
+            self::WATER => '浇水',
+            self::FERTILIZE => '施肥',
+            self::WEED => '除草',
+            self::PEST => '杀虫',
+            self::HARVEST => '收获',
+        };
+    }
+
+    /**
+     * 获取互助类型图标
+     */
+    public function getIcon(): string
+    {
+        return match($this) {
+            self::WATER => '💧',
+            self::FERTILIZE => '🌱',
+            self::WEED => '🌿',
+            self::PEST => '🐛',
+            self::HARVEST => '🌾',
+        ];
+    }
+
+    /**
+     * 获取对应的农场灾害类型
+     */
+    public function getDisasterType(): ?int
+    {
+        return match($this) {
+            self::WEED => \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value,
+            self::PEST => \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value,
+            default => null,
+        };
+    }
+
+    /**
+     * 获取需要消耗的道具类型
+     */
+    public function getRequiredItemType(): ?string
+    {
+        return match($this) {
+            self::WATER => 'water_tool',
+            self::FERTILIZE => 'fertilizer',
+            self::WEED => 'weed_killer',
+            self::PEST => 'pesticide',
+            self::HARVEST => null, // 收获不需要道具
+        };
+    }
+
+    /**
+     * 获取基础经验奖励
+     */
+    public function getBaseExpReward(): int
+    {
+        return match($this) {
+            self::WATER => 2,
+            self::FERTILIZE => 3,
+            self::WEED => 5,
+            self::PEST => 5,
+            self::HARVEST => 8,
+        };
+    }
+
+    /**
+     * 获取奖励概率
+     */
+    public function getRewardProbability(): float
+    {
+        return match($this) {
+            self::WATER => 0.1,      // 10%
+            self::FERTILIZE => 0.15, // 15%
+            self::WEED => 0.2,       // 20%
+            self::PEST => 0.2,       // 20%
+            self::HARVEST => 0.3,    // 30%
+        };
+    }
+
+    /**
+     * 是否需要消耗道具
+     */
+    public function requiresItem(): bool
+    {
+        return $this->getRequiredItemType() !== null;
+    }
+
+    /**
+     * 是否为灾害处理类型
+     */
+    public function isDisasterHelp(): bool
+    {
+        return in_array($this, [self::WEED, self::PEST]);
+    }
+
+    /**
+     * 是否为作物护理类型
+     */
+    public function isCropCare(): bool
+    {
+        return in_array($this, [self::WATER, self::FERTILIZE]);
+    }
+
+    /**
+     * 获取所有互助类型选项(用于后台管理)
+     */
+    public static function getOptions(): array
+    {
+        return [
+            self::WATER->value => self::WATER->getDescription(),
+            self::FERTILIZE->value => self::FERTILIZE->getDescription(),
+            self::WEED->value => self::WEED->getDescription(),
+            self::PEST->value => self::PEST->getDescription(),
+            self::HARVEST->value => self::HARVEST->getDescription(),
+        ];
+    }
+
+    /**
+     * 根据农场灾害类型获取对应的互助类型
+     */
+    public static function fromDisasterType(int $disasterType): ?self
+    {
+        return match($disasterType) {
+            \App\Module\Farm\Enums\DISASTER_TYPE::WEED->value => self::WEED,
+            \App\Module\Farm\Enums\DISASTER_TYPE::PEST->value => self::PEST,
+            default => null,
+        };
+    }
+}

+ 136 - 0
app/Module/SocialFarm/Enums/SOCIAL_ACTION.php

@@ -0,0 +1,136 @@
+<?php
+
+namespace App\Module\SocialFarm\Enums;
+
+/**
+ * 社交行为枚举
+ * 
+ * 定义社交农场中的各种行为类型
+ */
+enum SOCIAL_ACTION: string
+{
+    case STEAL = 'steal';           // 偷菜
+    case HELP_WATER = 'help_water'; // 帮助浇水
+    case HELP_FERTILIZE = 'help_fertilize'; // 帮助施肥
+    case HELP_WEED = 'help_weed';   // 帮助除草
+    case HELP_PEST = 'help_pest';   // 帮助杀虫
+    case HELP_HARVEST = 'help_harvest'; // 帮助收获
+    case VISIT = 'visit';           // 访问农场
+    case GIFT = 'gift';             // 赠送礼物
+    case LIKE = 'like';             // 点赞
+
+    /**
+     * 获取行为描述
+     */
+    public function getDescription(): string
+    {
+        return match($this) {
+            self::STEAL => '偷菜',
+            self::HELP_WATER => '帮助浇水',
+            self::HELP_FERTILIZE => '帮助施肥',
+            self::HELP_WEED => '帮助除草',
+            self::HELP_PEST => '帮助杀虫',
+            self::HELP_HARVEST => '帮助收获',
+            self::VISIT => '访问农场',
+            self::GIFT => '赠送礼物',
+            self::LIKE => '点赞',
+        };
+    }
+
+    /**
+     * 获取行为图标
+     */
+    public function getIcon(): string
+    {
+        return match($this) {
+            self::STEAL => '🥕',
+            self::HELP_WATER => '💧',
+            self::HELP_FERTILIZE => '🌱',
+            self::HELP_WEED => '🌿',
+            self::HELP_PEST => '🐛',
+            self::HELP_HARVEST => '🌾',
+            self::VISIT => '👀',
+            self::GIFT => '🎁',
+            self::LIKE => '👍',
+        };
+    }
+
+    /**
+     * 是否为帮助类行为
+     */
+    public function isHelpAction(): bool
+    {
+        return in_array($this, [
+            self::HELP_WATER,
+            self::HELP_FERTILIZE,
+            self::HELP_WEED,
+            self::HELP_PEST,
+            self::HELP_HARVEST,
+        ]);
+    }
+
+    /**
+     * 是否为负面行为
+     */
+    public function isNegativeAction(): bool
+    {
+        return $this === self::STEAL;
+    }
+
+    /**
+     * 是否为正面行为
+     */
+    public function isPositiveAction(): bool
+    {
+        return $this->isHelpAction() || in_array($this, [
+            self::GIFT,
+            self::LIKE,
+        ]);
+    }
+
+    /**
+     * 获取行为分类
+     */
+    public function getCategory(): string
+    {
+        return match($this) {
+            self::STEAL => 'steal',
+            self::HELP_WATER, self::HELP_FERTILIZE, self::HELP_WEED, 
+            self::HELP_PEST, self::HELP_HARVEST => 'help',
+            self::VISIT => 'visit',
+            self::GIFT, self::LIKE => 'social',
+        };
+    }
+
+    /**
+     * 获取所有帮助类行为
+     */
+    public static function getHelpActions(): array
+    {
+        return [
+            self::HELP_WATER,
+            self::HELP_FERTILIZE,
+            self::HELP_WEED,
+            self::HELP_PEST,
+            self::HELP_HARVEST,
+        ];
+    }
+
+    /**
+     * 获取所有行为选项(用于后台管理)
+     */
+    public static function getOptions(): array
+    {
+        return [
+            self::STEAL->value => self::STEAL->getDescription(),
+            self::HELP_WATER->value => self::HELP_WATER->getDescription(),
+            self::HELP_FERTILIZE->value => self::HELP_FERTILIZE->getDescription(),
+            self::HELP_WEED->value => self::HELP_WEED->getDescription(),
+            self::HELP_PEST->value => self::HELP_PEST->getDescription(),
+            self::HELP_HARVEST->value => self::HELP_HARVEST->getDescription(),
+            self::VISIT->value => self::VISIT->getDescription(),
+            self::GIFT->value => self::GIFT->getDescription(),
+            self::LIKE->value => self::LIKE->getDescription(),
+        ];
+    }
+}

+ 83 - 0
app/Module/SocialFarm/Enums/STEAL_STATUS.php

@@ -0,0 +1,83 @@
+<?php
+
+namespace App\Module\SocialFarm\Enums;
+
+/**
+ * 偷菜状态枚举
+ * 
+ * 定义偷菜操作的各种状态
+ */
+enum STEAL_STATUS: int
+{
+    case SUCCESS = 1;      // 偷菜成功
+    case FAILED = 2;       // 偷菜失败
+    case PROTECTED = 3;    // 受保护无法偷
+    case NO_PERMISSION = 4; // 无权限偷菜
+    case LIMIT_EXCEEDED = 5; // 超过次数限制
+    case CROP_NOT_READY = 6; // 作物未成熟
+    case ALREADY_STOLEN = 7; // 已被偷过
+
+    /**
+     * 获取状态描述
+     */
+    public function getDescription(): string
+    {
+        return match($this) {
+            self::SUCCESS => '偷菜成功',
+            self::FAILED => '偷菜失败',
+            self::PROTECTED => '受保护无法偷菜',
+            self::NO_PERMISSION => '无权限偷菜',
+            self::LIMIT_EXCEEDED => '超过每日偷菜次数限制',
+            self::CROP_NOT_READY => '作物未成熟',
+            self::ALREADY_STOLEN => '作物已被偷过',
+        };
+    }
+
+    /**
+     * 获取状态颜色(用于前端显示)
+     */
+    public function getColor(): string
+    {
+        return match($this) {
+            self::SUCCESS => 'green',
+            self::FAILED => 'red',
+            self::PROTECTED => 'orange',
+            self::NO_PERMISSION => 'red',
+            self::LIMIT_EXCEEDED => 'orange',
+            self::CROP_NOT_READY => 'gray',
+            self::ALREADY_STOLEN => 'gray',
+        };
+    }
+
+    /**
+     * 是否为成功状态
+     */
+    public function isSuccess(): bool
+    {
+        return $this === self::SUCCESS;
+    }
+
+    /**
+     * 是否为失败状态
+     */
+    public function isFailed(): bool
+    {
+        return !$this->isSuccess();
+    }
+
+    /**
+     * 获取所有状态选项(用于后台管理)
+     */
+    public static function getOptions(): array
+    {
+        return [
+            self::SUCCESS->value => self::SUCCESS->getDescription(),
+            self::FAILED->value => self::FAILED->getDescription(),
+            self::PROTECTED->value => self::PROTECTED->getDescription(),
+            self::NO_PERMISSION->value => self::NO_PERMISSION->getDescription(),
+            self::LIMIT_EXCEEDED->value => self::LIMIT_EXCEEDED->getDescription(),
+            self::CROP_NOT_READY->value => self::CROP_NOT_READY->getDescription(),
+            self::ALREADY_STOLEN->value => self::ALREADY_STOLEN->getDescription(),
+        ];
+    }
+}

+ 103 - 0
app/Module/SocialFarm/Enums/VISIT_TYPE.php

@@ -0,0 +1,103 @@
+<?php
+
+namespace App\Module\SocialFarm\Enums;
+
+/**
+ * 访问类型枚举
+ * 
+ * 定义农场访问的各种类型
+ */
+enum VISIT_TYPE: int
+{
+    case NORMAL = 1;        // 普通访问
+    case STEAL_VISIT = 2;   // 偷菜访问
+    case HELP_VISIT = 3;    // 互助访问
+    case SOCIAL_VISIT = 4;  // 社交访问(点赞、留言等)
+    case REVENGE_VISIT = 5; // 报复访问
+
+    /**
+     * 获取访问类型描述
+     */
+    public function getDescription(): string
+    {
+        return match($this) {
+            self::NORMAL => '普通访问',
+            self::STEAL_VISIT => '偷菜访问',
+            self::HELP_VISIT => '互助访问',
+            self::SOCIAL_VISIT => '社交访问',
+            self::REVENGE_VISIT => '报复访问',
+        };
+    }
+
+    /**
+     * 获取访问类型颜色
+     */
+    public function getColor(): string
+    {
+        return match($this) {
+            self::NORMAL => 'blue',
+            self::STEAL_VISIT => 'red',
+            self::HELP_VISIT => 'green',
+            self::SOCIAL_VISIT => 'purple',
+            self::REVENGE_VISIT => 'orange',
+        };
+    }
+
+    /**
+     * 获取访问类型图标
+     */
+    public function getIcon(): string
+    {
+        return match($this) {
+            self::NORMAL => '👀',
+            self::STEAL_VISIT => '🥕',
+            self::HELP_VISIT => '🤝',
+            self::SOCIAL_VISIT => '💬',
+            self::REVENGE_VISIT => '⚔️',
+        };
+    }
+
+    /**
+     * 是否为负面访问
+     */
+    public function isNegative(): bool
+    {
+        return in_array($this, [
+            self::STEAL_VISIT,
+            self::REVENGE_VISIT,
+        ]);
+    }
+
+    /**
+     * 是否为正面访问
+     */
+    public function isPositive(): bool
+    {
+        return in_array($this, [
+            self::HELP_VISIT,
+            self::SOCIAL_VISIT,
+        ]);
+    }
+
+    /**
+     * 是否为中性访问
+     */
+    public function isNeutral(): bool
+    {
+        return $this === self::NORMAL;
+    }
+
+    /**
+     * 获取所有访问类型选项(用于后台管理)
+     */
+    public static function getOptions(): array
+    {
+        return [
+            self::NORMAL->value => self::NORMAL->getDescription(),
+            self::STEAL_VISIT->value => self::STEAL_VISIT->getDescription(),
+            self::HELP_VISIT->value => self::HELP_VISIT->getDescription(),
+            self::SOCIAL_VISIT->value => self::SOCIAL_VISIT->getDescription(),
+            self::REVENGE_VISIT->value => self::REVENGE_VISIT->getDescription(),
+        ];
+    }
+}

+ 358 - 0
app/Module/SocialFarm/Models/SocialFarmSetting.php

@@ -0,0 +1,358 @@
+<?php
+
+namespace App\Module\SocialFarm\Models;
+
+use UCore\ModelCore;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+/**
+ * 社交农场设置模型
+ * 
+ * @property int $id 主键ID
+ * @property int $user_id 用户ID
+ * @property bool $allow_steal 允许偷菜
+ * @property bool $allow_help 允许互助
+ * @property bool $allow_visit 允许访问
+ * @property int $steal_protection_hours 偷菜保护时长(小时)
+ * @property int $daily_steal_limit 每日被偷次数限制
+ * @property int $daily_help_limit 每日被帮助次数限制
+ * @property bool $notification_enabled 通知开关
+ * @property bool $auto_revenge 自动反偷
+ * @property bool $friend_only 仅好友可访问
+ * @property array|null $blacklist_users 黑名单用户ID列表
+ * @property array|null $whitelist_users 白名单用户ID列表
+ * @property \Carbon\Carbon $created_at 创建时间
+ * @property \Carbon\Carbon $updated_at 更新时间
+ */
+class SocialFarmSetting extends ModelCore
+{
+    /**
+     * 数据表名
+     */
+    protected $table = 'social_farm_settings';
+
+    /**
+     * 可批量赋值的属性
+     */
+    protected $fillable = [
+        'user_id',
+        'allow_steal',
+        'allow_help',
+        'allow_visit',
+        'steal_protection_hours',
+        'daily_steal_limit',
+        'daily_help_limit',
+        'notification_enabled',
+        'auto_revenge',
+        'friend_only',
+        'blacklist_users',
+        'whitelist_users',
+    ];
+
+    /**
+     * 属性类型转换
+     */
+    protected $casts = [
+        'user_id' => 'integer',
+        'allow_steal' => 'boolean',
+        'allow_help' => 'boolean',
+        'allow_visit' => 'boolean',
+        'steal_protection_hours' => 'integer',
+        'daily_steal_limit' => 'integer',
+        'daily_help_limit' => 'integer',
+        'notification_enabled' => 'boolean',
+        'auto_revenge' => 'boolean',
+        'friend_only' => 'boolean',
+        'blacklist_users' => 'array',
+        'whitelist_users' => 'array',
+        'created_at' => 'datetime',
+        'updated_at' => 'datetime',
+    ];
+
+    /**
+     * 默认属性值
+     */
+    protected $attributes = [
+        'allow_steal' => true,
+        'allow_help' => true,
+        'allow_visit' => true,
+        'steal_protection_hours' => 0,
+        'daily_steal_limit' => 10,
+        'daily_help_limit' => 20,
+        'notification_enabled' => true,
+        'auto_revenge' => false,
+        'friend_only' => true,
+        'blacklist_users' => null,
+        'whitelist_users' => null,
+    ];
+
+    /**
+     * 获取用户信息
+     */
+    public function user(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\User\Models\User::class, 'user_id');
+    }
+
+    /**
+     * 检查用户是否在黑名单中
+     */
+    public function isUserBlacklisted(int $userId): bool
+    {
+        if (empty($this->blacklist_users)) {
+            return false;
+        }
+        return in_array($userId, $this->blacklist_users);
+    }
+
+    /**
+     * 检查用户是否在白名单中
+     */
+    public function isUserWhitelisted(int $userId): bool
+    {
+        if (empty($this->whitelist_users)) {
+            return false;
+        }
+        return in_array($userId, $this->whitelist_users);
+    }
+
+    /**
+     * 添加用户到黑名单
+     */
+    public function addToBlacklist(int $userId): void
+    {
+        $blacklist = $this->blacklist_users ?: [];
+        if (!in_array($userId, $blacklist)) {
+            $blacklist[] = $userId;
+            $this->blacklist_users = $blacklist;
+            $this->save();
+        }
+    }
+
+    /**
+     * 从黑名单移除用户
+     */
+    public function removeFromBlacklist(int $userId): void
+    {
+        $blacklist = $this->blacklist_users ?: [];
+        $key = array_search($userId, $blacklist);
+        if ($key !== false) {
+            unset($blacklist[$key]);
+            $this->blacklist_users = array_values($blacklist);
+            $this->save();
+        }
+    }
+
+    /**
+     * 添加用户到白名单
+     */
+    public function addToWhitelist(int $userId): void
+    {
+        $whitelist = $this->whitelist_users ?: [];
+        if (!in_array($userId, $whitelist)) {
+            $whitelist[] = $userId;
+            $this->whitelist_users = $whitelist;
+            $this->save();
+        }
+    }
+
+    /**
+     * 从白名单移除用户
+     */
+    public function removeFromWhitelist(int $userId): void
+    {
+        $whitelist = $this->whitelist_users ?: [];
+        $key = array_search($userId, $whitelist);
+        if ($key !== false) {
+            unset($whitelist[$key]);
+            $this->whitelist_users = array_values($whitelist);
+            $this->save();
+        }
+    }
+
+    /**
+     * 检查是否允许偷菜
+     */
+    public function canBeStolen(int $stealerId): bool
+    {
+        // 基础设置检查
+        if (!$this->allow_steal) {
+            return false;
+        }
+
+        // 黑名单检查
+        if ($this->isUserBlacklisted($stealerId)) {
+            return false;
+        }
+
+        // 如果有白名单,检查是否在白名单中
+        if (!empty($this->whitelist_users) && !$this->isUserWhitelisted($stealerId)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 检查是否允许互助
+     */
+    public function canBeHelped(int $helperId): bool
+    {
+        // 基础设置检查
+        if (!$this->allow_help) {
+            return false;
+        }
+
+        // 黑名单检查
+        if ($this->isUserBlacklisted($helperId)) {
+            return false;
+        }
+
+        // 如果有白名单,检查是否在白名单中
+        if (!empty($this->whitelist_users) && !$this->isUserWhitelisted($helperId)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 检查是否允许访问
+     */
+    public function canBeVisited(int $visitorId): bool
+    {
+        // 基础设置检查
+        if (!$this->allow_visit) {
+            return false;
+        }
+
+        // 黑名单检查
+        if ($this->isUserBlacklisted($visitorId)) {
+            return false;
+        }
+
+        // 如果有白名单,检查是否在白名单中
+        if (!empty($this->whitelist_users) && !$this->isUserWhitelisted($visitorId)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * 获取保护结束时间
+     */
+    public function getProtectionEndTime(): ?\Carbon\Carbon
+    {
+        if ($this->steal_protection_hours <= 0) {
+            return null;
+        }
+
+        // 这里需要根据实际的保护机制来计算
+        // 可能需要查询最近的保护记录
+        return now()->addHours($this->steal_protection_hours);
+    }
+
+    /**
+     * 是否在保护期内
+     */
+    public function isUnderProtection(): bool
+    {
+        $endTime = $this->getProtectionEndTime();
+        return $endTime && now()->lt($endTime);
+    }
+
+    /**
+     * 获取黑名单用户数量
+     */
+    public function getBlacklistCountAttribute(): int
+    {
+        return count($this->blacklist_users ?: []);
+    }
+
+    /**
+     * 获取白名单用户数量
+     */
+    public function getWhitelistCountAttribute(): int
+    {
+        return count($this->whitelist_users ?: []);
+    }
+
+    /**
+     * 作用域:按用户查询
+     */
+    public function scopeByUser($query, int $userId)
+    {
+        return $query->where('user_id', $userId);
+    }
+
+    /**
+     * 作用域:允许偷菜的用户
+     */
+    public function scopeAllowSteal($query)
+    {
+        return $query->where('allow_steal', true);
+    }
+
+    /**
+     * 作用域:允许互助的用户
+     */
+    public function scopeAllowHelp($query)
+    {
+        return $query->where('allow_help', true);
+    }
+
+    /**
+     * 作用域:允许访问的用户
+     */
+    public function scopeAllowVisit($query)
+    {
+        return $query->where('allow_visit', true);
+    }
+
+    /**
+     * 获取或创建用户设置
+     */
+    public static function getOrCreateForUser(int $userId): self
+    {
+        return static::firstOrCreate(
+            ['user_id' => $userId],
+            [
+                'allow_steal' => true,
+                'allow_help' => true,
+                'allow_visit' => true,
+                'steal_protection_hours' => 0,
+                'daily_steal_limit' => 10,
+                'daily_help_limit' => 20,
+                'notification_enabled' => true,
+                'auto_revenge' => false,
+                'friend_only' => true,
+            ]
+        );
+    }
+
+    /**
+     * 批量更新设置
+     */
+    public function updateSettings(array $settings): bool
+    {
+        $allowedFields = [
+            'allow_steal', 'allow_help', 'allow_visit',
+            'steal_protection_hours', 'daily_steal_limit', 'daily_help_limit',
+            'notification_enabled', 'auto_revenge', 'friend_only'
+        ];
+
+        $updateData = [];
+        foreach ($allowedFields as $field) {
+            if (array_key_exists($field, $settings)) {
+                $updateData[$field] = $settings[$field];
+            }
+        }
+
+        if (empty($updateData)) {
+            return false;
+        }
+
+        return $this->update($updateData);
+    }
+}

+ 318 - 0
app/Module/SocialFarm/Models/SocialFarmStealLog.php

@@ -0,0 +1,318 @@
+<?php
+
+namespace App\Module\SocialFarm\Models;
+
+use UCore\ModelCore;
+use App\Module\SocialFarm\Enums\STEAL_STATUS;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+/**
+ * 偷菜记录模型
+ * 
+ * @property int $id 主键ID
+ * @property int $stealer_id 偷菜者用户ID
+ * @property int $owner_id 农场主用户ID
+ * @property int $land_id 被偷的土地ID
+ * @property int $crop_id 被偷的作物ID
+ * @property int $item_id 偷到的物品ID
+ * @property int $item_amount 偷到的物品数量
+ * @property int $original_amount 作物原始数量
+ * @property float $steal_ratio 偷菜比例
+ * @property string $steal_time 偷菜时间
+ * @property int $steal_status 偷菜状态
+ * @property string|null $ip_address 偷菜者IP地址
+ * @property string|null $user_agent 用户代理信息
+ * @property \Carbon\Carbon $created_at 创建时间
+ * @property \Carbon\Carbon $updated_at 更新时间
+ */
+class SocialFarmStealLog extends ModelCore
+{
+    /**
+     * 数据表名
+     */
+    protected $table = 'social_farm_steal_logs';
+
+    /**
+     * 可批量赋值的属性
+     */
+    protected $fillable = [
+        'stealer_id',
+        'owner_id',
+        'land_id',
+        'crop_id',
+        'item_id',
+        'item_amount',
+        'original_amount',
+        'steal_ratio',
+        'steal_time',
+        'steal_status',
+        'ip_address',
+        'user_agent',
+    ];
+
+    /**
+     * 属性类型转换
+     */
+    protected $casts = [
+        'stealer_id' => 'integer',
+        'owner_id' => 'integer',
+        'land_id' => 'integer',
+        'crop_id' => 'integer',
+        'item_id' => 'integer',
+        'item_amount' => 'integer',
+        'original_amount' => 'integer',
+        'steal_ratio' => 'decimal:4',
+        'steal_time' => 'datetime',
+        'steal_status' => 'integer',
+        'created_at' => 'datetime',
+        'updated_at' => 'datetime',
+    ];
+
+    /**
+     * 日期字段
+     */
+    protected $dates = [
+        'steal_time',
+        'created_at',
+        'updated_at',
+    ];
+
+    /**
+     * 获取偷菜者用户信息
+     */
+    public function stealer(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\User\Models\User::class, 'stealer_id');
+    }
+
+    /**
+     * 获取农场主用户信息
+     */
+    public function owner(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\User\Models\User::class, 'owner_id');
+    }
+
+    /**
+     * 获取土地信息
+     */
+    public function land(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\Farm\Models\FarmLandUser::class, 'land_id');
+    }
+
+    /**
+     * 获取作物信息
+     */
+    public function crop(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\Farm\Models\FarmCropUser::class, 'crop_id');
+    }
+
+    /**
+     * 获取物品信息
+     */
+    public function item(): BelongsTo
+    {
+        return $this->belongsTo(\App\Module\GameItems\Models\ItemConfig::class, 'item_id');
+    }
+
+    /**
+     * 获取偷菜状态枚举
+     */
+    public function getStealStatusEnum(): STEAL_STATUS
+    {
+        return STEAL_STATUS::from($this->steal_status);
+    }
+
+    /**
+     * 获取偷菜状态描述
+     */
+    public function getStealStatusDescAttribute(): string
+    {
+        return $this->getStealStatusEnum()->getDescription();
+    }
+
+    /**
+     * 获取偷菜状态颜色
+     */
+    public function getStealStatusColorAttribute(): string
+    {
+        return $this->getStealStatusEnum()->getColor();
+    }
+
+    /**
+     * 是否偷菜成功
+     */
+    public function isSuccess(): bool
+    {
+        return $this->getStealStatusEnum()->isSuccess();
+    }
+
+    /**
+     * 是否偷菜失败
+     */
+    public function isFailed(): bool
+    {
+        return $this->getStealStatusEnum()->isFailed();
+    }
+
+    /**
+     * 获取偷菜收益率
+     */
+    public function getYieldRateAttribute(): float
+    {
+        if ($this->original_amount <= 0) {
+            return 0;
+        }
+        return round($this->item_amount / $this->original_amount, 4);
+    }
+
+    /**
+     * 获取格式化的偷菜时间
+     */
+    public function getFormattedStealTimeAttribute(): string
+    {
+        return $this->steal_time->format('Y-m-d H:i:s');
+    }
+
+    /**
+     * 获取偷菜时间距离现在的描述
+     */
+    public function getStealTimeHumanAttribute(): string
+    {
+        return $this->steal_time->diffForHumans();
+    }
+
+    /**
+     * 作用域:按偷菜者查询
+     */
+    public function scopeByStealer($query, int $stealerId)
+    {
+        return $query->where('stealer_id', $stealerId);
+    }
+
+    /**
+     * 作用域:按农场主查询
+     */
+    public function scopeByOwner($query, int $ownerId)
+    {
+        return $query->where('owner_id', $ownerId);
+    }
+
+    /**
+     * 作用域:按偷菜状态查询
+     */
+    public function scopeByStatus($query, int $status)
+    {
+        return $query->where('steal_status', $status);
+    }
+
+    /**
+     * 作用域:成功的偷菜记录
+     */
+    public function scopeSuccessful($query)
+    {
+        return $query->where('steal_status', STEAL_STATUS::SUCCESS->value);
+    }
+
+    /**
+     * 作用域:失败的偷菜记录
+     */
+    public function scopeFailed($query)
+    {
+        return $query->where('steal_status', '!=', STEAL_STATUS::SUCCESS->value);
+    }
+
+    /**
+     * 作用域:按时间范围查询
+     */
+    public function scopeByTimeRange($query, string $startTime, string $endTime)
+    {
+        return $query->whereBetween('steal_time', [$startTime, $endTime]);
+    }
+
+    /**
+     * 作用域:今日记录
+     */
+    public function scopeToday($query)
+    {
+        return $query->whereDate('steal_time', today());
+    }
+
+    /**
+     * 作用域:本周记录
+     */
+    public function scopeThisWeek($query)
+    {
+        return $query->whereBetween('steal_time', [
+            now()->startOfWeek(),
+            now()->endOfWeek()
+        ]);
+    }
+
+    /**
+     * 作用域:本月记录
+     */
+    public function scopeThisMonth($query)
+    {
+        return $query->whereMonth('steal_time', now()->month)
+                    ->whereYear('steal_time', now()->year);
+    }
+
+    /**
+     * 获取用户今日偷菜次数
+     */
+    public static function getTodayStealCount(int $stealerId): int
+    {
+        return static::byStealer($stealerId)
+                    ->today()
+                    ->count();
+    }
+
+    /**
+     * 获取用户今日被偷次数
+     */
+    public static function getTodayStolenCount(int $ownerId): int
+    {
+        return static::byOwner($ownerId)
+                    ->today()
+                    ->successful()
+                    ->count();
+    }
+
+    /**
+     * 获取用户偷菜统计
+     */
+    public static function getStealStats(int $userId, string $date = null): array
+    {
+        $date = $date ?: today()->toDateString();
+        
+        $stealCount = static::byStealer($userId)
+                           ->whereDate('steal_time', $date)
+                           ->successful()
+                           ->count();
+                           
+        $stolenCount = static::byOwner($userId)
+                            ->whereDate('steal_time', $date)
+                            ->successful()
+                            ->count();
+                            
+        $itemsGained = static::byStealer($userId)
+                            ->whereDate('steal_time', $date)
+                            ->successful()
+                            ->sum('item_amount');
+                            
+        $itemsLost = static::byOwner($userId)
+                          ->whereDate('steal_time', $date)
+                          ->successful()
+                          ->sum('item_amount');
+
+        return [
+            'steal_count' => $stealCount,
+            'stolen_count' => $stolenCount,
+            'items_gained' => $itemsGained,
+            'items_lost' => $itemsLost,
+        ];
+    }
+}

+ 93 - 0
app/Module/SocialFarm/Providers/SocialFarmServiceProvider.php

@@ -0,0 +1,93 @@
+<?php
+
+namespace App\Module\SocialFarm\Providers;
+
+use Illuminate\Support\ServiceProvider;
+use Illuminate\Support\Facades\Event;
+
+/**
+ * SocialFarm模块服务提供者
+ */
+class SocialFarmServiceProvider extends ServiceProvider
+{
+    /**
+     * 注册服务
+     */
+    public function register(): void
+    {
+        // 注册配置文件
+        $this->mergeConfigFrom(
+            __DIR__ . '/../config/socialfarm.php',
+            'socialfarm'
+        );
+    }
+
+    /**
+     * 启动服务
+     */
+    public function boot(): void
+    {
+        // 发布配置文件
+        if ($this->app->runningInConsole()) {
+            $this->publishes([
+                __DIR__ . '/../config/socialfarm.php' => config_path('socialfarm.php'),
+            ], 'socialfarm-config');
+        }
+
+        // 注册事件监听器
+        $this->registerEventListeners();
+
+        // 注册命令
+        $this->registerCommands();
+    }
+
+    /**
+     * 注册事件监听器
+     */
+    protected function registerEventListeners(): void
+    {
+        // 偷菜成功事件
+        Event::listen(
+            \App\Module\SocialFarm\Events\CropStolenEvent::class,
+            \App\Module\SocialFarm\Listeners\SendStealNotificationListener::class
+        );
+
+        Event::listen(
+            \App\Module\SocialFarm\Events\CropStolenEvent::class,
+            \App\Module\SocialFarm\Listeners\UpdateSocialStatsListener::class
+        );
+
+        // 农场访问事件
+        Event::listen(
+            \App\Module\SocialFarm\Events\FarmVisitedEvent::class,
+            \App\Module\SocialFarm\Listeners\UpdateSocialStatsListener::class
+        );
+
+        // 互助行为事件
+        Event::listen(
+            \App\Module\SocialFarm\Events\HelpActionEvent::class,
+            \App\Module\SocialFarm\Listeners\UpdateSocialStatsListener::class
+        );
+    }
+
+    /**
+     * 注册命令
+     */
+    protected function registerCommands(): void
+    {
+        if ($this->app->runningInConsole()) {
+            $this->commands([
+                \App\Module\SocialFarm\Commands\CleanExpiredLogsCommand::class,
+                \App\Module\SocialFarm\Commands\SocialFarmStatsCommand::class,
+            ]);
+        }
+    }
+
+    /**
+     * 获取提供的服务
+     */
+    public function provides(): array
+    {
+        return [];
+    }
+}

+ 286 - 0
app/Module/SocialFarm/README.md

@@ -0,0 +1,286 @@
+# SocialFarm模块 - 社交农场系统
+
+SocialFarm模块是开心农场系统的社交互动核心模块,负责处理好友间的农场互动功能,包括偷菜、互助、访问等社交玩法。
+
+## 📋 目录
+
+- [模块概述](#模块概述)
+- [核心功能](#核心功能)
+- [架构设计](#架构设计)
+- [数据库设计](#数据库设计)
+- [API接口](#api接口)
+- [模块交互](#模块交互)
+- [配置说明](#配置说明)
+- [开发指南](#开发指南)
+
+## 🎯 模块概述
+
+### 基本信息
+- **模块名称**: SocialFarm
+- **功能定位**: 社交农场互动系统
+- **开发状态**: 🚧 开发中
+- **依赖模块**: Friend、Farm、GameItems、User、Notification
+
+### 主要特性
+- **好友农场访问**: 访问好友农场,查看农场状态
+- **偷菜系统**: 偷取好友成熟作物,获得物品奖励
+- **互助功能**: 帮助好友处理农场事务(浇水、施肥、除草等)
+- **社交记录**: 完整的社交行为记录和统计
+- **权限控制**: 灵活的农场访问权限设置
+- **防护机制**: 偷菜保护、次数限制等平衡机制
+
+## 🎮 核心功能
+
+### 1. 偷菜系统
+- **偷菜条件检查**: 好友关系、作物状态、权限验证
+- **偷菜执行**: 计算收益、更新作物、记录日志
+- **偷菜限制**: 每日次数限制、冷却时间、保护机制
+- **收益计算**: 基于作物类型、成熟度的动态收益
+
+### 2. 好友农场访问
+- **农场浏览**: 查看好友农场布局和作物状态
+- **访问记录**: 记录访问行为和时间
+- **权限控制**: 基于好友关系的访问权限
+- **实时状态**: 获取农场实时数据
+
+### 3. 互助功能
+- **帮助浇水**: 帮助好友给作物浇水
+- **协助施肥**: 使用道具帮助好友施肥
+- **清除灾害**: 帮助清除好友农场的灾害
+- **互助奖励**: 互助行为的奖励机制
+
+### 4. 社交设置
+- **隐私控制**: 设置农场访问权限
+- **偷菜保护**: 开启偷菜保护时间
+- **互助设置**: 允许/禁止好友互助
+- **通知设置**: 社交行为通知开关
+
+## 🏗️ 架构设计
+
+### 目录结构
+```
+app/Module/SocialFarm/
+├── AdminControllers/        # 后台管理控制器
+│   ├── StealLogController.php          # 偷菜记录管理
+│   ├── VisitLogController.php          # 访问记录管理
+│   ├── SocialSettingController.php     # 社交设置管理
+│   └── Helper/                         # 辅助类
+├── Commands/                           # 命令行工具
+│   ├── CleanExpiredLogsCommand.php     # 清理过期日志
+│   └── SocialFarmStatsCommand.php      # 社交统计命令
+├── Databases/                          # 数据库相关文件
+│   ├── createsql/                      # 表创建SQL
+│   └── GenerateSql/                    # 生成的SQL文件
+├── Docs/                               # 详细文档目录
+│   ├── 设计概述.md                      # 设计概述
+│   ├── 数据库设计.md                    # 数据库设计
+│   ├── API接口文档.md                   # API接口文档
+│   ├── 偷菜系统设计.md                  # 偷菜系统设计
+│   └── 互助系统设计.md                  # 互助系统设计
+├── Dtos/                               # 数据传输对象
+│   ├── FarmVisitDto.php                # 农场访问DTO
+│   ├── StealResultDto.php              # 偷菜结果DTO
+│   └── SocialActionDto.php             # 社交行为DTO
+├── Enums/                              # 枚举定义
+│   ├── STEAL_STATUS.php                # 偷菜状态枚举
+│   ├── SOCIAL_ACTION.php               # 社交行为枚举
+│   ├── VISIT_TYPE.php                  # 访问类型枚举
+│   └── PROTECTION_TYPE.php             # 保护类型枚举
+├── Events/                             # 事件类
+│   ├── CropStolenEvent.php             # 作物被偷事件
+│   ├── FarmVisitedEvent.php            # 农场被访问事件
+│   └── HelpActionEvent.php             # 互助行为事件
+├── Listeners/                          # 事件监听器
+│   ├── SendStealNotificationListener.php   # 发送偷菜通知
+│   └── UpdateSocialStatsListener.php       # 更新社交统计
+├── Logics/                             # 业务逻辑类
+│   ├── StealLogic.php                  # 偷菜逻辑
+│   ├── VisitLogic.php                  # 访问逻辑
+│   ├── HelpLogic.php                   # 互助逻辑
+│   └── PermissionLogic.php             # 权限逻辑
+├── Models/                             # 数据模型
+│   ├── SocialFarmStealLog.php          # 偷菜记录模型
+│   ├── SocialFarmVisitLog.php          # 访问记录模型
+│   ├── SocialFarmSetting.php           # 社交设置模型
+│   └── SocialFarmHelpLog.php           # 互助记录模型
+├── Providers/                          # 服务提供者
+│   └── SocialFarmServiceProvider.php   # 模块服务提供者
+├── Repositories/                       # 数据仓库(后台专用)
+│   ├── StealLogRepository.php          # 偷菜记录仓库
+│   └── VisitLogRepository.php          # 访问记录仓库
+├── Services/                           # 对外服务类
+│   ├── SocialFarmService.php           # 主服务类
+│   ├── StealService.php                # 偷菜服务
+│   ├── VisitService.php                # 访问服务
+│   └── HelpService.php                 # 互助服务
+├── Validations/                        # 验证规则
+│   ├── StealValidation.php             # 偷菜验证
+│   └── VisitValidation.php             # 访问验证
+├── Validators/                         # 验证器
+│   ├── StealValidator.php              # 偷菜验证器
+│   └── PermissionValidator.php         # 权限验证器
+└── README.md                           # 本文档
+```
+
+### 核心类设计
+
+#### 1. 服务层 (Services)
+- **SocialFarmService**: 主服务类,提供统一的对外接口
+- **StealService**: 偷菜功能服务
+- **VisitService**: 农场访问服务
+- **HelpService**: 互助功能服务
+
+#### 2. 逻辑层 (Logics)
+- **StealLogic**: 偷菜业务逻辑处理
+- **VisitLogic**: 访问权限和逻辑处理
+- **HelpLogic**: 互助行为逻辑处理
+- **PermissionLogic**: 权限验证逻辑
+
+#### 3. 数据层 (Models)
+- **SocialFarmStealLog**: 偷菜记录数据模型
+- **SocialFarmVisitLog**: 访问记录数据模型
+- **SocialFarmSetting**: 用户社交设置模型
+- **SocialFarmHelpLog**: 互助记录数据模型
+
+## 📊 数据库设计
+
+### 核心数据表
+
+#### 1. 偷菜记录表 (social_farm_steal_logs)
+| 字段名 | 类型 | 说明 |
+|--------|------|------|
+| id | bigint | 主键ID |
+| stealer_id | bigint | 偷菜者用户ID |
+| owner_id | bigint | 农场主用户ID |
+| land_id | bigint | 被偷的土地ID |
+| crop_id | bigint | 被偷的作物ID |
+| item_id | bigint | 偷到的物品ID |
+| item_amount | int | 偷到的物品数量 |
+| steal_time | timestamp | 偷菜时间 |
+| steal_status | tinyint | 偷菜状态 |
+
+#### 2. 农场访问记录表 (social_farm_visit_logs)
+| 字段名 | 类型 | 说明 |
+|--------|------|------|
+| id | bigint | 主键ID |
+| visitor_id | bigint | 访问者用户ID |
+| owner_id | bigint | 农场主用户ID |
+| visit_time | timestamp | 访问时间 |
+| visit_type | tinyint | 访问类型 |
+| actions | json | 访问期间的行为记录 |
+| duration | int | 访问持续时间(秒) |
+
+#### 3. 社交设置表 (social_farm_settings)
+| 字段名 | 类型 | 说明 |
+|--------|------|------|
+| id | bigint | 主键ID |
+| user_id | bigint | 用户ID |
+| allow_steal | tinyint | 允许偷菜 |
+| allow_help | tinyint | 允许互助 |
+| allow_visit | tinyint | 允许访问 |
+| steal_protection_hours | int | 偷菜保护时长 |
+| daily_steal_limit | int | 每日偷菜次数限制 |
+| notification_enabled | tinyint | 通知开关 |
+
+#### 4. 互助记录表 (social_farm_help_logs)
+| 字段名 | 类型 | 说明 |
+|--------|------|------|
+| id | bigint | 主键ID |
+| helper_id | bigint | 帮助者用户ID |
+| owner_id | bigint | 农场主用户ID |
+| land_id | bigint | 帮助的土地ID |
+| help_type | tinyint | 帮助类型 |
+| help_time | timestamp | 帮助时间 |
+| reward_item_id | bigint | 奖励物品ID |
+| reward_amount | int | 奖励数量 |
+
+## 🔧 配置说明
+
+### 系统配置
+```php
+// config/socialfarm.php
+return [
+    // 偷菜配置
+    'steal' => [
+        'daily_limit' => 10,           // 每日偷菜次数限制
+        'cooldown_minutes' => 5,       // 偷菜冷却时间(分钟)
+        'protection_hours' => 2,       // 默认保护时长(小时)
+        'min_yield_ratio' => 0.1,      // 最小偷菜收益比例
+        'max_yield_ratio' => 0.3,      // 最大偷菜收益比例
+    ],
+    
+    // 访问配置
+    'visit' => [
+        'max_duration' => 1800,        // 最大访问时长(秒)
+        'log_retention_days' => 30,    // 访问日志保留天数
+    ],
+    
+    // 互助配置
+    'help' => [
+        'daily_limit' => 20,           // 每日互助次数限制
+        'reward_probability' => 0.3,   // 互助奖励概率
+        'exp_reward' => 5,             // 互助经验奖励
+    ],
+];
+```
+
+## 🚀 开发计划
+
+### 第一阶段:基础功能 (预计2周)
+- [x] 模块目录结构创建
+- [ ] 数据库表设计和创建
+- [ ] 基础模型和枚举定义
+- [ ] 核心服务类框架
+- [ ] 基础偷菜功能实现
+
+### 第二阶段:完善功能 (预计2周)
+- [ ] 农场访问功能
+- [ ] 权限控制系统
+- [ ] 社交设置管理
+- [ ] 通知系统集成
+- [ ] 后台管理界面
+
+### 第三阶段:扩展功能 (预计1周)
+- [ ] 互助功能实现
+- [ ] 社交统计和排行
+- [ ] 性能优化
+- [ ] 测试和文档完善
+
+## 📚 相关文档
+
+- [设计概述](Docs/设计概述.md) - 模块整体设计思路
+- [数据库设计](Docs/数据库设计.md) - 详细的数据库表结构
+- [API接口文档](Docs/API接口文档.md) - 完整的API接口说明
+- [偷菜系统设计](Docs/偷菜系统设计.md) - 偷菜功能详细设计
+- [互助系统设计](Docs/互助系统设计.md) - 互助功能详细设计
+
+## 🔗 模块依赖
+
+### 依赖的模块
+- **Friend模块**: 获取好友关系和好友列表
+- **Farm模块**: 获取农场和作物信息
+- **GameItems模块**: 处理物品奖励和消耗
+- **User模块**: 获取用户基础信息
+- **Notification模块**: 发送社交行为通知
+
+### 被依赖的模块
+- **AppGame模块**: 提供客户端接口处理
+
+## 📝 开发注意事项
+
+1. **数据一致性**: 所有涉及多个操作的功能都使用数据库事务
+2. **性能优化**: 社交查询和统计应考虑缓存策略
+3. **安全验证**: 所有操作前验证用户权限和好友关系
+4. **防刷机制**: 实现完善的防刷和限流机制
+5. **日志记录**: 记录关键操作,便于问题排查和数据分析
+
+## 📈 版本信息
+
+- **创建时间**: 2025年07月02日
+- **当前版本**: v1.0.0-dev
+- **开发状态**: 🚧 开发中
+- **维护者**: 开发团队
+
+---
+
+如需了解具体功能的详细信息,请查看Docs目录下的相关文档。

+ 394 - 0
app/Module/SocialFarm/Services/SocialFarmService.php

@@ -0,0 +1,394 @@
+<?php
+
+namespace App\Module\SocialFarm\Services;
+
+use App\Module\SocialFarm\Logics\StealLogic;
+use App\Module\SocialFarm\Logics\VisitLogic;
+use App\Module\SocialFarm\Logics\HelpLogic;
+use App\Module\SocialFarm\Logics\PermissionLogic;
+use App\Module\SocialFarm\Models\SocialFarmSetting;
+use App\Module\SocialFarm\Enums\STEAL_STATUS;
+use App\Module\SocialFarm\Enums\VISIT_TYPE;
+use App\Module\SocialFarm\Enums\HELP_TYPE;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * 社交农场主服务类
+ * 
+ * 提供社交农场功能的统一对外接口
+ */
+class SocialFarmService
+{
+    /**
+     * 访问好友农场
+     *
+     * @param int $visitorId 访问者ID
+     * @param int $ownerId 农场主ID
+     * @param int $visitType 访问类型
+     * @return array 访问结果
+     */
+    public static function visitFriendFarm(int $visitorId, int $ownerId, int $visitType = VISIT_TYPE::NORMAL->value): array
+    {
+        try {
+            // 验证访问权限
+            $permissionCheck = PermissionLogic::checkVisitPermission($visitorId, $ownerId);
+            if (!$permissionCheck['allowed']) {
+                return [
+                    'success' => false,
+                    'code' => 'NO_PERMISSION',
+                    'message' => $permissionCheck['reason']
+                ];
+            }
+
+            // 执行访问逻辑
+            $visitResult = VisitLogic::recordVisit($visitorId, $ownerId, $visitType);
+
+            // 获取农场信息
+            $farmInfo = static::getFriendFarmInfo($ownerId, $visitorId);
+
+            return [
+                'success' => true,
+                'data' => [
+                    'visit_id' => $visitResult['visit_id'],
+                    'farm_info' => $farmInfo,
+                    'permissions' => $permissionCheck['permissions']
+                ]
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('访问好友农场失败', [
+                'visitor_id' => $visitorId,
+                'owner_id' => $ownerId,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'success' => false,
+                'code' => 'VISIT_FAILED',
+                'message' => '访问失败,请稍后重试'
+            ];
+        }
+    }
+
+    /**
+     * 偷菜操作
+     *
+     * @param int $stealerId 偷菜者ID
+     * @param int $ownerId 农场主ID
+     * @param int $landId 土地ID
+     * @return array 偷菜结果
+     */
+    public static function stealCrop(int $stealerId, int $ownerId, int $landId): array
+    {
+        try {
+            // 开启事务
+            return DB::transaction(function () use ($stealerId, $ownerId, $landId) {
+                // 验证偷菜条件
+                $canSteal = StealLogic::canSteal($stealerId, $ownerId, $landId);
+                if (!$canSteal['allowed']) {
+                    return [
+                        'success' => false,
+                        'code' => $canSteal['code'],
+                        'message' => $canSteal['reason']
+                    ];
+                }
+
+                // 执行偷菜
+                $stealResult = StealLogic::executeSteal($stealerId, $ownerId, $landId);
+
+                // 记录访问(如果还没有记录)
+                VisitLogic::recordVisit($stealerId, $ownerId, VISIT_TYPE::STEAL_VISIT->value);
+
+                return [
+                    'success' => true,
+                    'data' => $stealResult
+                ];
+            });
+
+        } catch (\Exception $e) {
+            Log::error('偷菜操作失败', [
+                'stealer_id' => $stealerId,
+                'owner_id' => $ownerId,
+                'land_id' => $landId,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'success' => false,
+                'code' => 'STEAL_FAILED',
+                'message' => '偷菜失败,请稍后重试'
+            ];
+        }
+    }
+
+    /**
+     * 互助操作
+     *
+     * @param int $helperId 帮助者ID
+     * @param int $ownerId 农场主ID
+     * @param int $landId 土地ID
+     * @param int $helpType 帮助类型
+     * @return array 互助结果
+     */
+    public static function helpFriend(int $helperId, int $ownerId, int $landId, int $helpType): array
+    {
+        try {
+            // 开启事务
+            return DB::transaction(function () use ($helperId, $ownerId, $landId, $helpType) {
+                // 验证互助条件
+                $canHelp = HelpLogic::canHelp($helperId, $ownerId, $landId, $helpType);
+                if (!$canHelp['allowed']) {
+                    return [
+                        'success' => false,
+                        'code' => $canHelp['code'],
+                        'message' => $canHelp['reason']
+                    ];
+                }
+
+                // 执行互助
+                $helpResult = HelpLogic::executeHelp($helperId, $ownerId, $landId, $helpType);
+
+                // 记录访问(如果还没有记录)
+                VisitLogic::recordVisit($helperId, $ownerId, VISIT_TYPE::HELP_VISIT->value);
+
+                return [
+                    'success' => true,
+                    'data' => $helpResult
+                ];
+            });
+
+        } catch (\Exception $e) {
+            Log::error('互助操作失败', [
+                'helper_id' => $helperId,
+                'owner_id' => $ownerId,
+                'land_id' => $landId,
+                'help_type' => $helpType,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'success' => false,
+                'code' => 'HELP_FAILED',
+                'message' => '互助失败,请稍后重试'
+            ];
+        }
+    }
+
+    /**
+     * 获取可偷菜的好友列表
+     *
+     * @param int $userId 用户ID
+     * @return array 好友列表
+     */
+    public static function getStealableFriends(int $userId): array
+    {
+        try {
+            // 获取好友列表
+            $friends = \App\Module\Friend\Services\FriendService::getFriendList($userId);
+
+            $stealableFriends = [];
+            foreach ($friends['items'] as $friend) {
+                $friendId = $friend['user_id'];
+                
+                // 检查是否允许偷菜
+                $permission = PermissionLogic::checkStealPermission($userId, $friendId);
+                if (!$permission['allowed']) {
+                    continue;
+                }
+
+                // 获取可偷菜的作物数量
+                $stealableCount = StealLogic::getStealableCropCount($friendId);
+                if ($stealableCount > 0) {
+                    $friend['stealable_count'] = $stealableCount;
+                    $friend['last_visit_time'] = VisitLogic::getLastVisitTime($userId, $friendId);
+                    $stealableFriends[] = $friend;
+                }
+            }
+
+            return [
+                'success' => true,
+                'data' => $stealableFriends
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('获取可偷菜好友列表失败', [
+                'user_id' => $userId,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'success' => false,
+                'message' => '获取好友列表失败'
+            ];
+        }
+    }
+
+    /**
+     * 获取好友农场信息
+     *
+     * @param int $ownerId 农场主ID
+     * @param int $visitorId 访问者ID
+     * @return array 农场信息
+     */
+    public static function getFriendFarmInfo(int $ownerId, int $visitorId): array
+    {
+        try {
+            // 获取农场基础信息
+            $farmInfo = \App\Module\Farm\Services\FarmService::getFarmInfo($ownerId);
+            
+            // 获取土地信息(包含作物状态)
+            $lands = \App\Module\Farm\Services\LandService::getUserLands($ownerId);
+            
+            // 为每块土地添加社交相关信息
+            foreach ($lands as &$land) {
+                if ($land['crop']) {
+                    // 检查是否可偷菜
+                    $canSteal = StealLogic::canStealCrop($visitorId, $ownerId, $land['id']);
+                    $land['can_steal'] = $canSteal['allowed'];
+                    $land['steal_reason'] = $canSteal['reason'] ?? '';
+                    
+                    // 检查是否可互助
+                    $canHelp = HelpLogic::getAvailableHelpTypes($visitorId, $ownerId, $land['id']);
+                    $land['help_types'] = $canHelp;
+                }
+            }
+
+            return [
+                'farm_info' => $farmInfo,
+                'lands' => $lands,
+                'owner_settings' => static::getUserSocialSettings($ownerId)
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('获取好友农场信息失败', [
+                'owner_id' => $ownerId,
+                'visitor_id' => $visitorId,
+                'error' => $e->getMessage()
+            ]);
+
+            return [];
+        }
+    }
+
+    /**
+     * 获取用户社交设置
+     *
+     * @param int $userId 用户ID
+     * @return array 社交设置
+     */
+    public static function getUserSocialSettings(int $userId): array
+    {
+        $settings = SocialFarmSetting::where('user_id', $userId)->first();
+        
+        if (!$settings) {
+            // 创建默认设置
+            $settings = SocialFarmSetting::create(['user_id' => $userId]);
+        }
+
+        return [
+            'allow_steal' => $settings->allow_steal,
+            'allow_help' => $settings->allow_help,
+            'allow_visit' => $settings->allow_visit,
+            'steal_protection_hours' => $settings->steal_protection_hours,
+            'daily_steal_limit' => $settings->daily_steal_limit,
+            'daily_help_limit' => $settings->daily_help_limit,
+            'notification_enabled' => $settings->notification_enabled,
+            'friend_only' => $settings->friend_only,
+        ];
+    }
+
+    /**
+     * 更新用户社交设置
+     *
+     * @param int $userId 用户ID
+     * @param array $settings 设置数据
+     * @return array 更新结果
+     */
+    public static function updateUserSocialSettings(int $userId, array $settings): array
+    {
+        try {
+            $userSettings = SocialFarmSetting::where('user_id', $userId)->first();
+            
+            if (!$userSettings) {
+                $userSettings = new SocialFarmSetting(['user_id' => $userId]);
+            }
+
+            // 更新设置
+            $allowedFields = [
+                'allow_steal', 'allow_help', 'allow_visit',
+                'steal_protection_hours', 'daily_steal_limit', 'daily_help_limit',
+                'notification_enabled', 'auto_revenge', 'friend_only'
+            ];
+
+            foreach ($allowedFields as $field) {
+                if (isset($settings[$field])) {
+                    $userSettings->$field = $settings[$field];
+                }
+            }
+
+            $userSettings->save();
+
+            return [
+                'success' => true,
+                'data' => $userSettings->toArray()
+            ];
+
+        } catch (\Exception $e) {
+            Log::error('更新用户社交设置失败', [
+                'user_id' => $userId,
+                'settings' => $settings,
+                'error' => $e->getMessage()
+            ]);
+
+            return [
+                'success' => false,
+                'message' => '设置更新失败'
+            ];
+        }
+    }
+
+    /**
+     * 获取用户社交统计
+     *
+     * @param int $userId 用户ID
+     * @param string $date 统计日期(可选,默认今天)
+     * @return array 统计数据
+     */
+    public static function getUserSocialStats(int $userId, string $date = null): array
+    {
+        try {
+            $date = $date ?: date('Y-m-d');
+            
+            $stats = \App\Module\SocialFarm\Models\SocialFarmStats::where('user_id', $userId)
+                ->where('stat_date', $date)
+                ->first();
+
+            if (!$stats) {
+                return [
+                    'steal_count' => 0,
+                    'stolen_count' => 0,
+                    'help_count' => 0,
+                    'helped_count' => 0,
+                    'visit_count' => 0,
+                    'visited_count' => 0,
+                    'steal_items_gained' => 0,
+                    'steal_items_lost' => 0,
+                    'help_rewards_gained' => 0,
+                    'total_exp_gained' => 0,
+                ];
+            }
+
+            return $stats->toArray();
+
+        } catch (\Exception $e) {
+            Log::error('获取用户社交统计失败', [
+                'user_id' => $userId,
+                'date' => $date,
+                'error' => $e->getMessage()
+            ]);
+
+            return [];
+        }
+    }
+}

+ 234 - 0
app/Module/SocialFarm/config/socialfarm.php

@@ -0,0 +1,234 @@
+<?php
+
+return [
+    /*
+    |--------------------------------------------------------------------------
+    | 社交农场配置
+    |--------------------------------------------------------------------------
+    |
+    | 这里配置社交农场模块的各种参数和规则
+    |
+    */
+
+    // 偷菜相关配置
+    'steal' => [
+        // 每日偷菜次数限制
+        'daily_limit' => env('SOCIAL_FARM_DAILY_STEAL_LIMIT', 10),
+        
+        // 偷菜冷却时间(分钟)
+        'cooldown_minutes' => env('SOCIAL_FARM_STEAL_COOLDOWN', 5),
+        
+        // 默认保护时长(小时)
+        'protection_hours' => env('SOCIAL_FARM_PROTECTION_HOURS', 2),
+        
+        // 最小偷菜收益比例
+        'min_yield_ratio' => env('SOCIAL_FARM_MIN_YIELD_RATIO', 0.1),
+        
+        // 最大偷菜收益比例
+        'max_yield_ratio' => env('SOCIAL_FARM_MAX_YIELD_RATIO', 0.3),
+        
+        // 偷菜经验奖励
+        'exp_reward' => env('SOCIAL_FARM_STEAL_EXP', 10),
+        
+        // 是否允许偷取未成熟作物
+        'allow_unripe' => env('SOCIAL_FARM_ALLOW_UNRIPE', false),
+        
+        // 偷菜成功率(0-1)
+        'success_rate' => env('SOCIAL_FARM_STEAL_SUCCESS_RATE', 0.8),
+    ],
+
+    // 访问相关配置
+    'visit' => [
+        // 最大访问时长(秒)
+        'max_duration' => env('SOCIAL_FARM_MAX_VISIT_DURATION', 1800),
+        
+        // 访问日志保留天数
+        'log_retention_days' => env('SOCIAL_FARM_VISIT_LOG_RETENTION', 30),
+        
+        // 是否记录访问详情
+        'record_details' => env('SOCIAL_FARM_RECORD_VISIT_DETAILS', true),
+        
+        // 访问频率限制(次/小时)
+        'hourly_limit' => env('SOCIAL_FARM_VISIT_HOURLY_LIMIT', 50),
+    ],
+
+    // 互助相关配置
+    'help' => [
+        // 每日互助次数限制
+        'daily_limit' => env('SOCIAL_FARM_DAILY_HELP_LIMIT', 20),
+        
+        // 互助奖励概率
+        'reward_probability' => env('SOCIAL_FARM_HELP_REWARD_PROBABILITY', 0.3),
+        
+        // 互助经验奖励
+        'exp_reward' => env('SOCIAL_FARM_HELP_EXP', 5),
+        
+        // 互助冷却时间(分钟)
+        'cooldown_minutes' => env('SOCIAL_FARM_HELP_COOLDOWN', 2),
+        
+        // 是否消耗道具
+        'consume_items' => env('SOCIAL_FARM_HELP_CONSUME_ITEMS', true),
+        
+        // 互助类型配置
+        'types' => [
+            'water' => [
+                'exp_reward' => 2,
+                'reward_probability' => 0.1,
+                'required_item_type' => 'water_tool',
+            ],
+            'fertilize' => [
+                'exp_reward' => 3,
+                'reward_probability' => 0.15,
+                'required_item_type' => 'fertilizer',
+            ],
+            'weed' => [
+                'exp_reward' => 5,
+                'reward_probability' => 0.2,
+                'required_item_type' => 'weed_killer',
+            ],
+            'pest' => [
+                'exp_reward' => 5,
+                'reward_probability' => 0.2,
+                'required_item_type' => 'pesticide',
+            ],
+            'harvest' => [
+                'exp_reward' => 8,
+                'reward_probability' => 0.3,
+                'required_item_type' => null,
+            ],
+        ],
+    ],
+
+    // 通知相关配置
+    'notification' => [
+        // 是否启用通知
+        'enabled' => env('SOCIAL_FARM_NOTIFICATION_ENABLED', true),
+        
+        // 偷菜通知
+        'steal_notification' => env('SOCIAL_FARM_STEAL_NOTIFICATION', true),
+        
+        // 互助通知
+        'help_notification' => env('SOCIAL_FARM_HELP_NOTIFICATION', true),
+        
+        // 访问通知
+        'visit_notification' => env('SOCIAL_FARM_VISIT_NOTIFICATION', false),
+        
+        // 通知延迟发送(秒)
+        'delay_seconds' => env('SOCIAL_FARM_NOTIFICATION_DELAY', 0),
+        
+        // 批量通知阈值
+        'batch_threshold' => env('SOCIAL_FARM_NOTIFICATION_BATCH_THRESHOLD', 5),
+    ],
+
+    // 权限相关配置
+    'permission' => [
+        // 是否只允许好友访问
+        'friend_only_default' => env('SOCIAL_FARM_FRIEND_ONLY_DEFAULT', true),
+        
+        // 黑名单最大数量
+        'max_blacklist_size' => env('SOCIAL_FARM_MAX_BLACKLIST_SIZE', 100),
+        
+        // 白名单最大数量
+        'max_whitelist_size' => env('SOCIAL_FARM_MAX_WHITELIST_SIZE', 50),
+        
+        // 是否允许自动反偷
+        'allow_auto_revenge' => env('SOCIAL_FARM_ALLOW_AUTO_REVENGE', true),
+        
+        // 新用户默认设置
+        'default_settings' => [
+            'allow_steal' => true,
+            'allow_help' => true,
+            'allow_visit' => true,
+            'steal_protection_hours' => 0,
+            'daily_steal_limit' => 10,
+            'daily_help_limit' => 20,
+            'notification_enabled' => true,
+            'auto_revenge' => false,
+            'friend_only' => true,
+        ],
+    ],
+
+    // 统计相关配置
+    'stats' => [
+        // 是否启用统计
+        'enabled' => env('SOCIAL_FARM_STATS_ENABLED', true),
+        
+        // 统计数据保留天数
+        'retention_days' => env('SOCIAL_FARM_STATS_RETENTION', 90),
+        
+        // 是否实时更新统计
+        'realtime_update' => env('SOCIAL_FARM_STATS_REALTIME', true),
+        
+        // 统计任务执行时间
+        'cron_schedule' => env('SOCIAL_FARM_STATS_CRON', '0 1 * * *'),
+    ],
+
+    // 缓存相关配置
+    'cache' => [
+        // 缓存前缀
+        'prefix' => env('SOCIAL_FARM_CACHE_PREFIX', 'social_farm'),
+        
+        // 农场信息缓存时间(分钟)
+        'farm_info_ttl' => env('SOCIAL_FARM_CACHE_FARM_INFO_TTL', 5),
+        
+        // 用户设置缓存时间(分钟)
+        'user_settings_ttl' => env('SOCIAL_FARM_CACHE_USER_SETTINGS_TTL', 60),
+        
+        // 好友列表缓存时间(分钟)
+        'friend_list_ttl' => env('SOCIAL_FARM_CACHE_FRIEND_LIST_TTL', 30),
+        
+        // 统计数据缓存时间(分钟)
+        'stats_ttl' => env('SOCIAL_FARM_CACHE_STATS_TTL', 30),
+    ],
+
+    // 安全相关配置
+    'security' => [
+        // API调用频率限制(次/分钟)
+        'api_rate_limit' => env('SOCIAL_FARM_API_RATE_LIMIT', 100),
+        
+        // 是否记录IP地址
+        'log_ip_address' => env('SOCIAL_FARM_LOG_IP_ADDRESS', true),
+        
+        // 是否记录用户代理
+        'log_user_agent' => env('SOCIAL_FARM_LOG_USER_AGENT', true),
+        
+        // 异常操作检测
+        'anomaly_detection' => env('SOCIAL_FARM_ANOMALY_DETECTION', true),
+        
+        // 异常操作阈值
+        'anomaly_threshold' => env('SOCIAL_FARM_ANOMALY_THRESHOLD', 50),
+    ],
+
+    // 数据清理配置
+    'cleanup' => [
+        // 是否启用自动清理
+        'enabled' => env('SOCIAL_FARM_CLEANUP_ENABLED', true),
+        
+        // 偷菜记录保留天数
+        'steal_logs_retention' => env('SOCIAL_FARM_STEAL_LOGS_RETENTION', 180),
+        
+        // 访问记录保留天数
+        'visit_logs_retention' => env('SOCIAL_FARM_VISIT_LOGS_RETENTION', 30),
+        
+        // 互助记录保留天数
+        'help_logs_retention' => env('SOCIAL_FARM_HELP_LOGS_RETENTION', 90),
+        
+        // 清理任务执行时间
+        'cron_schedule' => env('SOCIAL_FARM_CLEANUP_CRON', '0 2 * * 0'),
+    ],
+
+    // 调试相关配置
+    'debug' => [
+        // 是否启用调试模式
+        'enabled' => env('SOCIAL_FARM_DEBUG', false),
+        
+        // 详细日志记录
+        'verbose_logging' => env('SOCIAL_FARM_VERBOSE_LOGGING', false),
+        
+        // 性能监控
+        'performance_monitoring' => env('SOCIAL_FARM_PERFORMANCE_MONITORING', false),
+        
+        // 测试模式
+        'test_mode' => env('SOCIAL_FARM_TEST_MODE', false),
+    ],
+];

+ 2 - 2
docker-compose.yml

@@ -1,5 +1,5 @@
 networks:
-    ggggg:
+    aaaaa:
         external: true
 services:
   dev:
@@ -17,4 +17,4 @@ services:
     ports:
        - 36019:80
     networks:
-        - ggggg
+        - aaaaa