Item.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. $includeFrozen = $options['include_frozen'] ?? false;
  296. // 构建查询条件
  297. $query = ItemUser::where('user_id', $userId)
  298. ->where('item_id', $itemId)
  299. ->whereNull('instance_id')
  300. ->where('quantity', '>', 0); // 确保数量大于0
  301. // 根据include_frozen参数决定是否包含冻结物品
  302. if (!$includeFrozen) {
  303. $query->where('is_frozen', false); // 只获取未冻结的物品
  304. }
  305. // 获取用户物品(优先消耗即将过期的物品)
  306. $userItems = $query->orderBy('expire_at')->get();
  307. // 检查物品数量是否足够
  308. $totalQuantity = $userItems->sum('quantity');
  309. if ($totalQuantity < $quantity) {
  310. throw new Exception("用户 {$userId} 的物品 {$itemId} 数量不足,需要 {$quantity},实际 {$totalQuantity}");
  311. }
  312. // 获取来源信息
  313. $sourceType = $options['source_type'] ?? null;
  314. $sourceId = $options['source_id'] ?? null;
  315. // 开始消耗物品
  316. $remainingQuantity = $quantity;
  317. foreach ($userItems as $userItem) {
  318. if ($remainingQuantity <= 0) {
  319. break;
  320. }
  321. if ($userItem->quantity <= $remainingQuantity) {
  322. // 当前堆叠数量不足,全部消耗
  323. $consumedQuantity = $userItem->quantity;
  324. $remainingQuantity -= $consumedQuantity;
  325. $oldQuantity = $userItem->quantity;
  326. // 记录交易日志
  327. self::logTransaction(
  328. $userId,
  329. $itemId,
  330. null,
  331. -$consumedQuantity,
  332. TRANSACTION_TYPE::CONSUME,
  333. $sourceType,
  334. $sourceId,
  335. $options['details'] ?? null,
  336. null,
  337. $options['ip_address'] ?? null,
  338. $options['device_info'] ?? null
  339. );
  340. // 将数量设置为0,不删除记录
  341. $userItem->quantity = 0;
  342. $userItem->save();
  343. // 触发物品数量变更事件
  344. Event::dispatch(new ItemQuantityChanged(
  345. $userId,
  346. $itemId,
  347. null,
  348. $oldQuantity,
  349. 0,
  350. $userItem->id,
  351. $options
  352. ));
  353. } else {
  354. // 当前堆叠数量足够,部分消耗
  355. $consumedQuantity = $remainingQuantity;
  356. $oldQuantity = $userItem->quantity;
  357. $newQuantity = $oldQuantity - $consumedQuantity;
  358. $userItem->quantity = $newQuantity;
  359. $userItem->save();
  360. $remainingQuantity = 0;
  361. // 记录交易日志
  362. self::logTransaction(
  363. $userId,
  364. $itemId,
  365. null,
  366. -$consumedQuantity,
  367. TRANSACTION_TYPE::CONSUME,
  368. $sourceType,
  369. $sourceId,
  370. $options['details'] ?? null,
  371. null,
  372. $options['ip_address'] ?? null,
  373. $options['device_info'] ?? null
  374. );
  375. // 触发物品数量变更事件
  376. Event::dispatch(new ItemQuantityChanged(
  377. $userId,
  378. $itemId,
  379. null,
  380. $oldQuantity,
  381. $newQuantity,
  382. $userItem->id,
  383. $options
  384. ));
  385. }
  386. // 触发物品消耗事件
  387. Event::dispatch(new ItemConsumed($userId, $itemId, null, $consumedQuantity, $options));
  388. }
  389. return [
  390. 'success' => true,
  391. 'item_id' => $itemId,
  392. 'quantity' => $quantity,
  393. 'remaining_quantity' => $totalQuantity - $quantity,
  394. ];
  395. }
  396. /**
  397. * 消耗单独属性物品
  398. *
  399. * @param int $userId 用户ID
  400. * @param int $itemId 物品ID
  401. * @param int $instanceId 物品实例ID
  402. * @param array $options 选项
  403. * @return array 消耗结果
  404. * @throws Exception
  405. */
  406. public static function consumeUniqueItem(int $userId, int $itemId, int $instanceId, array $options = []): Res
  407. {
  408. Helper::check_tr();
  409. // 检查是否包含冻结物品
  410. $includeFrozen = $options['include_frozen'] ?? false;
  411. // 构建查询条件
  412. $query = ItemUser::where('user_id', $userId)
  413. ->where('item_id', $itemId)
  414. ->where('instance_id', $instanceId);
  415. // 根据include_frozen参数决定是否包含冻结物品
  416. if (!$includeFrozen) {
  417. $query->where('is_frozen', false); // 只获取未冻结的物品
  418. }
  419. $userItem = $query->first();
  420. if (!$userItem) {
  421. $frozenText = $includeFrozen ? '' : '(未冻结)';
  422. throw new Exception("用户 {$userId} 没有物品实例 {$instanceId}{$frozenText}");
  423. }
  424. // 获取来源信息
  425. $sourceType = $options['source_type'] ?? null;
  426. $sourceId = $options['source_id'] ?? null;
  427. // 记录交易日志
  428. self::logTransaction(
  429. $userId,
  430. $itemId,
  431. $instanceId,
  432. -1,
  433. TRANSACTION_TYPE::CONSUME,
  434. $sourceType,
  435. $sourceId,
  436. $options['details'] ?? null,
  437. null,
  438. $options['ip_address'] ?? null,
  439. $options['device_info'] ?? null
  440. );
  441. // 删除用户物品记录
  442. $userItem->delete();
  443. // 是否删除物品实例
  444. if (!empty($options['delete_instance'])) {
  445. ItemInstance::where('id', $instanceId)->delete();
  446. }
  447. // 触发物品消耗事件
  448. Event::dispatch(new ItemConsumed($userId, $itemId, $instanceId, 1, $options));
  449. return Res::success('', [
  450. 'item_id' => $itemId,
  451. 'instance_id' => $instanceId,
  452. ]);
  453. }
  454. /**
  455. * 记录物品交易日志
  456. *
  457. * @param int $userId 用户ID
  458. * @param int $itemId 物品ID
  459. * @param int|null $instanceId 物品实例ID
  460. * @param int $quantity 数量
  461. * @param int $transactionType 交易类型
  462. * @param mixed $sourceType 来源类型(支持字符串或枚举类型)
  463. * @param int|null $sourceId 来源ID
  464. * @param array|null $details 详细信息
  465. * @param string|null $expireAt 过期时间
  466. * @param string|null $ipAddress IP地址
  467. * @param string|null $deviceInfo 设备信息
  468. * @return ItemTransactionLog
  469. */
  470. public static function logTransaction(
  471. int $userId,
  472. int $itemId,
  473. ?int $instanceId,
  474. int $quantity,
  475. int $transactionType,
  476. $sourceType = null,
  477. ?int $sourceId = null,
  478. ?array $details = null,
  479. ?string $expireAt = null,
  480. ?string $ipAddress = null,
  481. ?string $deviceInfo = null
  482. ): ItemTransactionLog
  483. {
  484. // 处理枚举类型的sourceType
  485. $sourceTypeValue = null;
  486. if ($sourceType !== null) {
  487. if (is_object($sourceType) && method_exists($sourceType, 'value')) {
  488. // 如果是枚举类型,获取其值
  489. $sourceTypeValue = $sourceType->value;
  490. } elseif (is_string($sourceType)) {
  491. // 如果是字符串,直接使用
  492. $sourceTypeValue = $sourceType;
  493. } else {
  494. // 其他类型转换为字符串
  495. $sourceTypeValue = (string)$sourceType;
  496. }
  497. }
  498. return ItemTransactionLog::create([
  499. 'user_id' => $userId,
  500. 'item_id' => $itemId,
  501. 'instance_id' => $instanceId,
  502. 'quantity' => $quantity,
  503. 'transaction_type' => $transactionType,
  504. 'source_type' => $sourceTypeValue,
  505. 'source_id' => $sourceId,
  506. 'details' => $details,
  507. 'expire_at' => $expireAt,
  508. 'ip_address' => $ipAddress,
  509. 'device_info' => $deviceInfo,
  510. ]);
  511. }
  512. }