Item.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. namespace App\Module\GameItems\Logics;
  3. use App\Module\GameItems\Enums\ITEM_TYPE;
  4. use App\Module\GameItems\Enums\TRANSACTION_TYPE;
  5. use App\Module\GameItems\Events\ItemAcquired;
  6. use App\Module\GameItems\Events\ItemConsumed;
  7. use App\Module\GameItems\Events\ItemQuantityChanged;
  8. use App\Module\GameItems\Models\Item as ItemModel;
  9. use App\Module\GameItems\Models\ItemInstance;
  10. use App\Module\GameItems\Models\ItemTransactionLog;
  11. use App\Module\GameItems\Models\ItemUser;
  12. use Exception;
  13. use Illuminate\Support\Facades\Event;
  14. use UCore\Db\Helper;
  15. use UCore\Dto\Res;
  16. /**
  17. * 物品逻辑类
  18. */
  19. class Item
  20. {
  21. /**
  22. * 判断物品是否为宝箱
  23. *
  24. * @param ItemModel $item 物品模型
  25. * @return bool
  26. */
  27. public static function isChest(ItemModel $item): bool
  28. {
  29. return $item->type == ITEM_TYPE::CHEST; // 使用枚举代替魔法数字
  30. }
  31. /**
  32. * 检查物品是否已过期(全局过期)
  33. *
  34. * @param ItemModel $item 物品模型
  35. * @return bool
  36. */
  37. public static function isExpired(ItemModel $item): bool
  38. {
  39. if (empty($item->global_expire_at)) {
  40. return false;
  41. }
  42. // 确保 global_expire_at 是 Carbon 实例
  43. $expireAt = $item->global_expire_at;
  44. if (is_string($expireAt)) {
  45. $expireAt = \Carbon\Carbon::parse($expireAt);
  46. }
  47. return $expireAt->isPast();
  48. }
  49. /**
  50. * 添加统一属性物品
  51. *
  52. * @param int $userId 用户ID
  53. * @param int $itemId 物品ID
  54. * @param int $quantity 数量
  55. * @param array $options 选项
  56. * @return array 添加结果
  57. * @throws Exception
  58. */
  59. public static function addNormalItem(int $userId, int $itemId, int $quantity, array $options = []): array
  60. {
  61. // 获取物品信息
  62. $item = ItemModel::findOrFail($itemId);
  63. // 计算过期时间
  64. $expireAt = null;
  65. if (!empty($options['expire_at'])) {
  66. $expireAt = $options['expire_at'];
  67. } elseif ($item->default_expire_seconds > 0) {
  68. $expireAt = now()->addSeconds($item->default_expire_seconds);
  69. }
  70. // 检查事务是否已开启
  71. Helper::check_tr();
  72. // 获取来源信息
  73. $sourceType = $options['source_type'] ?? null;
  74. $sourceId = $options['source_id'] ?? null;
  75. // 检查用户是否已有该物品且过期时间相同,并且未满堆叠(排除冻结的物品)
  76. $userItem = ItemUser::where('user_id', $userId)
  77. ->where('item_id', $itemId)
  78. ->where(function ($query) use ($expireAt) {
  79. if ($expireAt === null) {
  80. $query->whereNull('expire_at');
  81. } else {
  82. $query->where('expire_at', $expireAt);
  83. }
  84. })
  85. ->whereNull('instance_id')
  86. ->where('is_frozen', false) // 排除冻结的物品
  87. ->where(function ($query) use ($item) {
  88. // 如果有最大堆叠限制,只查找未满的堆叠
  89. if ($item->max_stack > 0) {
  90. $query->where('quantity', '<', $item->max_stack);
  91. }
  92. })
  93. ->first();
  94. $addedQuantity = $quantity;
  95. $currentQuantity = 0;
  96. if ($userItem) {
  97. // 已有物品,增加数量
  98. $currentQuantity = $userItem->quantity;
  99. $newQuantity = $currentQuantity + $quantity;
  100. // 检查最大堆叠限制
  101. if ($item->max_stack > 0 && $newQuantity > $item->max_stack) {
  102. // 超过最大堆叠,先填满当前堆叠
  103. $canAddToCurrent = $item->max_stack - $currentQuantity;
  104. $userItem->quantity = $item->max_stack;
  105. $userItem->save();
  106. // 触发物品数量变更事件(更新现有堆叠)
  107. Event::dispatch(new ItemQuantityChanged(
  108. $userId,
  109. $itemId,
  110. null,
  111. $currentQuantity,
  112. $item->max_stack,
  113. $userItem->id,
  114. $options
  115. ));
  116. // 剩余数量递归添加到新堆叠
  117. $remainingQuantity = $quantity - $canAddToCurrent;
  118. if ($remainingQuantity > 0) {
  119. self::addNormalItem($userId, $itemId, $remainingQuantity, $options);
  120. }
  121. $addedQuantity = $quantity;
  122. $currentQuantity = $item->max_stack;
  123. } else {
  124. // 未超过最大堆叠,直接更新数量
  125. $oldQuantity = $userItem->quantity;
  126. $userItem->quantity = $newQuantity;
  127. $userItem->save();
  128. $currentQuantity = $newQuantity;
  129. // 触发物品数量变更事件
  130. Event::dispatch(new ItemQuantityChanged(
  131. $userId,
  132. $itemId,
  133. null,
  134. $oldQuantity,
  135. $newQuantity,
  136. $userItem->id,
  137. $options
  138. ));
  139. }
  140. } else {
  141. // 没有该物品,创建新记录
  142. $createQuantity = min($quantity, $item->max_stack > 0 ? $item->max_stack : $quantity);
  143. $userItem = new ItemUser([
  144. 'user_id' => $userId,
  145. 'item_id' => $itemId,
  146. 'quantity' => $createQuantity,
  147. 'expire_at' => $expireAt,
  148. ]);
  149. $userItem->save();
  150. // 触发物品数量变更事件(新增物品)
  151. Event::dispatch(new ItemQuantityChanged(
  152. $userId,
  153. $itemId,
  154. null,
  155. 0, // 旧数量为0
  156. $createQuantity,
  157. $userItem->id,
  158. $options
  159. ));
  160. // 如果数量超过最大堆叠,递归添加剩余数量
  161. if ($item->max_stack > 0 && $quantity > $item->max_stack) {
  162. $remainingQuantity = $quantity - $item->max_stack;
  163. self::addNormalItem($userId, $itemId, $remainingQuantity, $options);
  164. $addedQuantity = $quantity; // 总添加数量
  165. } else {
  166. $addedQuantity = $createQuantity;
  167. }
  168. $currentQuantity = $createQuantity;
  169. }
  170. // 记录交易日志
  171. self::logTransaction(
  172. $userId,
  173. $itemId,
  174. null,
  175. $addedQuantity,
  176. TRANSACTION_TYPE::ACQUIRE,
  177. $sourceType,
  178. $sourceId,
  179. $options['details'] ?? null,
  180. $expireAt,
  181. $options['ip_address'] ?? null,
  182. $options['device_info'] ?? null
  183. );
  184. // 触发物品获取事件
  185. Event::dispatch(new ItemAcquired($userId, $itemId, null, $addedQuantity, $options));
  186. return [
  187. 'success' => true,
  188. 'item_id' => $itemId,
  189. 'quantity' => $addedQuantity,
  190. 'current_quantity' => $currentQuantity,
  191. 'user_item_id' => $userItem->id,
  192. ];
  193. }
  194. /**
  195. * 添加单独属性物品
  196. *
  197. * @param int $userId 用户ID
  198. * @param int $itemId 物品ID
  199. * @param array $options 选项
  200. * @return array 添加结果
  201. * @throws Exception
  202. */
  203. public static function addUniqueItem(int $userId, int $itemId, array $options = []): array
  204. {
  205. // 获取物品信息
  206. $item = ItemModel::findOrFail($itemId);
  207. // 确保物品是单独属性物品
  208. if (!$item->is_unique) {
  209. throw new Exception("物品 {$itemId} 不是单独属性物品");
  210. }
  211. // 计算过期时间
  212. $expireAt = null;
  213. if (!empty($options['expire_at'])) {
  214. $expireAt = $options['expire_at'];
  215. } elseif ($item->default_expire_seconds > 0) {
  216. $expireAt = now()->addSeconds($item->default_expire_seconds);
  217. }
  218. // 检查事务是否已开启
  219. Helper::check_tr();
  220. // 获取来源信息
  221. $sourceType = $options['source_type'] ?? null;
  222. $sourceId = $options['source_id'] ?? null;
  223. if(!$sourceType || !$sourceId){
  224. throw new Exception("物品 {$itemId} ,缺少来源类型.");
  225. }
  226. // 创建物品实例
  227. $instance = new ItemInstance([
  228. 'item_id' => $itemId,
  229. 'name' => $options['name'] ?? $item->name,
  230. 'display_attributes' => $options['display_attributes'] ?? $item->display_attributes,
  231. 'numeric_attributes' => $options['numeric_attributes'] ?? $item->numeric_attributes,
  232. 'tradable' => $options['tradable'] ?? $item->tradable,
  233. 'is_bound' => $options['is_bound'] ?? false,
  234. 'bound_to' => $options['bound_to'] ?? null,
  235. 'bind_exp_time' => $options['bind_exp_time'] ?? null,
  236. 'expire_at' => $expireAt,
  237. ]);
  238. $instance->save();
  239. // 关联到用户
  240. $userItem = new ItemUser([
  241. 'user_id' => $userId,
  242. 'item_id' => $itemId,
  243. 'instance_id' => $instance->id,
  244. 'quantity' => 1, // 单独属性物品数量始终为1
  245. 'expire_at' => $expireAt,
  246. ]);
  247. $userItem->save();
  248. // 记录交易日志
  249. self::logTransaction(
  250. $userId,
  251. $itemId,
  252. $instance->id,
  253. 1,
  254. TRANSACTION_TYPE::ACQUIRE,
  255. $sourceType,
  256. $sourceId,
  257. $options['details'] ?? null,
  258. $expireAt,
  259. $options['ip_address'] ?? null,
  260. $options['device_info'] ?? null
  261. );
  262. // 触发物品获取事件
  263. Event::dispatch(new ItemAcquired($userId, $itemId, $instance->id, 1, $options));
  264. // 触发物品数量变更事件(新增物品)
  265. Event::dispatch(new ItemQuantityChanged(
  266. $userId,
  267. $itemId,
  268. $instance->id,
  269. 0, // 旧数量为0
  270. 1, // 新数量为1
  271. $userItem->id,
  272. $options
  273. ));
  274. return [
  275. 'success' => true,
  276. 'item_id' => $itemId,
  277. 'instance_id' => $instance->id,
  278. 'user_item_id' => $userItem->id,
  279. ];
  280. }
  281. /**
  282. * 消耗统一属性物品
  283. *
  284. * @param int $userId 用户ID
  285. * @param int $itemId 物品ID
  286. * @param int $quantity 数量
  287. * @param array $options 选项
  288. * @return array 消耗结果
  289. * @throws Exception
  290. */
  291. public static function consumeNormalItem(int $userId, int $itemId, int $quantity, array $options = []): array
  292. {
  293. Helper::check_tr();
  294. // 获取用户物品(排除冻结的物品)
  295. $userItems = ItemUser::where('user_id', $userId)
  296. ->where('item_id', $itemId)
  297. ->whereNull('instance_id')
  298. ->where('is_frozen', false) // 只获取未冻结的物品
  299. ->where('quantity', '>', 0) // 确保数量大于0
  300. ->orderBy('expire_at') // 优先消耗即将过期的物品
  301. ->get();
  302. // 检查物品数量是否足够
  303. $totalQuantity = $userItems->sum('quantity');
  304. if ($totalQuantity < $quantity) {
  305. throw new Exception("用户 {$userId} 的物品 {$itemId} 数量不足,需要 {$quantity},实际 {$totalQuantity}");
  306. }
  307. // 获取来源信息
  308. $sourceType = $options['source_type'] ?? null;
  309. $sourceId = $options['source_id'] ?? null;
  310. // 开始消耗物品
  311. $remainingQuantity = $quantity;
  312. foreach ($userItems as $userItem) {
  313. if ($remainingQuantity <= 0) {
  314. break;
  315. }
  316. if ($userItem->quantity <= $remainingQuantity) {
  317. // 当前堆叠数量不足,全部消耗
  318. $consumedQuantity = $userItem->quantity;
  319. $remainingQuantity -= $consumedQuantity;
  320. $oldQuantity = $userItem->quantity;
  321. // 记录交易日志
  322. self::logTransaction(
  323. $userId,
  324. $itemId,
  325. null,
  326. -$consumedQuantity,
  327. TRANSACTION_TYPE::CONSUME,
  328. $sourceType,
  329. $sourceId,
  330. $options['details'] ?? null,
  331. null,
  332. $options['ip_address'] ?? null,
  333. $options['device_info'] ?? null
  334. );
  335. // 将数量设置为0,不删除记录
  336. $userItem->quantity = 0;
  337. $userItem->save();
  338. // 触发物品数量变更事件
  339. Event::dispatch(new ItemQuantityChanged(
  340. $userId,
  341. $itemId,
  342. null,
  343. $oldQuantity,
  344. 0,
  345. $userItem->id,
  346. $options
  347. ));
  348. } else {
  349. // 当前堆叠数量足够,部分消耗
  350. $consumedQuantity = $remainingQuantity;
  351. $oldQuantity = $userItem->quantity;
  352. $newQuantity = $oldQuantity - $consumedQuantity;
  353. $userItem->quantity = $newQuantity;
  354. $userItem->save();
  355. $remainingQuantity = 0;
  356. // 记录交易日志
  357. self::logTransaction(
  358. $userId,
  359. $itemId,
  360. null,
  361. -$consumedQuantity,
  362. TRANSACTION_TYPE::CONSUME,
  363. $sourceType,
  364. $sourceId,
  365. $options['details'] ?? null,
  366. null,
  367. $options['ip_address'] ?? null,
  368. $options['device_info'] ?? null
  369. );
  370. // 触发物品数量变更事件
  371. Event::dispatch(new ItemQuantityChanged(
  372. $userId,
  373. $itemId,
  374. null,
  375. $oldQuantity,
  376. $newQuantity,
  377. $userItem->id,
  378. $options
  379. ));
  380. }
  381. // 触发物品消耗事件
  382. Event::dispatch(new ItemConsumed($userId, $itemId, null, $consumedQuantity, $options));
  383. }
  384. return [
  385. 'success' => true,
  386. 'item_id' => $itemId,
  387. 'quantity' => $quantity,
  388. 'remaining_quantity' => $totalQuantity - $quantity,
  389. ];
  390. }
  391. /**
  392. * 消耗单独属性物品
  393. *
  394. * @param int $userId 用户ID
  395. * @param int $itemId 物品ID
  396. * @param int $instanceId 物品实例ID
  397. * @param array $options 选项
  398. * @return array 消耗结果
  399. * @throws Exception
  400. */
  401. public static function consumeUniqueItem(int $userId, int $itemId, int $instanceId, array $options = []): Res
  402. {
  403. Helper::check_tr();
  404. // 获取用户物品(确保未冻结)
  405. $userItem = ItemUser::where('user_id', $userId)
  406. ->where('item_id', $itemId)
  407. ->where('instance_id', $instanceId)
  408. ->where('is_frozen', false) // 只获取未冻结的物品
  409. ->first();
  410. if (!$userItem) {
  411. throw new Exception("用户 {$userId} 没有物品实例 {$instanceId}");
  412. }
  413. // 获取来源信息
  414. $sourceType = $options['source_type'] ?? null;
  415. $sourceId = $options['source_id'] ?? null;
  416. // 记录交易日志
  417. self::logTransaction(
  418. $userId,
  419. $itemId,
  420. $instanceId,
  421. -1,
  422. TRANSACTION_TYPE::CONSUME,
  423. $sourceType,
  424. $sourceId,
  425. $options['details'] ?? null,
  426. null,
  427. $options['ip_address'] ?? null,
  428. $options['device_info'] ?? null
  429. );
  430. // 删除用户物品记录
  431. $userItem->delete();
  432. // 是否删除物品实例
  433. if (!empty($options['delete_instance'])) {
  434. ItemInstance::where('id', $instanceId)->delete();
  435. }
  436. // 触发物品消耗事件
  437. Event::dispatch(new ItemConsumed($userId, $itemId, $instanceId, 1, $options));
  438. return Res::success('', [
  439. 'item_id' => $itemId,
  440. 'instance_id' => $instanceId,
  441. ]);
  442. }
  443. /**
  444. * 记录物品交易日志
  445. *
  446. * @param int $userId 用户ID
  447. * @param int $itemId 物品ID
  448. * @param int|null $instanceId 物品实例ID
  449. * @param int $quantity 数量
  450. * @param int $transactionType 交易类型
  451. * @param string|null $sourceType 来源类型
  452. * @param int|null $sourceId 来源ID
  453. * @param array|null $details 详细信息
  454. * @param string|null $expireAt 过期时间
  455. * @param string|null $ipAddress IP地址
  456. * @param string|null $deviceInfo 设备信息
  457. * @return ItemTransactionLog
  458. */
  459. public static function logTransaction(
  460. int $userId,
  461. int $itemId,
  462. ?int $instanceId,
  463. int $quantity,
  464. int $transactionType,
  465. ?string $sourceType = null,
  466. ?int $sourceId = null,
  467. ?array $details = null,
  468. ?string $expireAt = null,
  469. ?string $ipAddress = null,
  470. ?string $deviceInfo = null
  471. ): ItemTransactionLog
  472. {
  473. return ItemTransactionLog::create([
  474. 'user_id' => $userId,
  475. 'item_id' => $itemId,
  476. 'instance_id' => $instanceId,
  477. 'quantity' => $quantity,
  478. 'transaction_type' => $transactionType,
  479. 'source_type' => $sourceType,
  480. 'source_id' => $sourceId,
  481. 'details' => $details,
  482. 'expire_at' => $expireAt,
  483. 'ip_address' => $ipAddress,
  484. 'device_info' => $deviceInfo,
  485. ]);
  486. }
  487. }