ActivityRewardService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Constants\Util;
  5. use App\Models\ActivityReward;
  6. use App\Models\Config;
  7. use App\Models\Role;
  8. use App\Models\UserSession;
  9. use App\Models\User;
  10. use Illuminate\Support\Facades\Validator;
  11. use Illuminate\Validation\Rule;
  12. use App\Support\ActivityCatalog;
  13. use App\Support\ContentLink;
  14. use Exception;
  15. class ActivityRewardService extends BaseService
  16. {
  17. public static string $MODEL = ActivityReward::class;
  18. /** 使用原始结束时间戳,避免日期展示格式截掉当天的时分秒。 */
  19. public static function expire(): int
  20. {
  21. return static::$MODEL::where('status', ActivityReward::STATUS_UP)
  22. ->where('end_time', '<', now()->timestamp)
  23. ->update(['status' => ActivityReward::STATUS_DOWN]);
  24. }
  25. public static function configurationDefaults(): array
  26. {
  27. return [
  28. 'publish_platforms' => [], 'budget' => null, 'reward_quota' => null, 'sort' => 0,
  29. 'register_time_limited' => false, 'register_start_time' => null, 'register_end_time' => null,
  30. 'register_platforms' => [], 'deposit_limited' => false, 'deposit_min' => null,
  31. 'deposit_max' => null, 'show_ineligible' => true,
  32. ];
  33. }
  34. private static function configuration(array $params, ?ActivityReward $existing): array
  35. {
  36. $defaults = static::configurationDefaults();
  37. if ((int)($params['type'] ?? $existing?->type) === 2) {
  38. return $defaults;
  39. }
  40. $quotaMode = !$existing || $existing->quota_enabled;
  41. Validator::make($params, [$quotaMode ? 'budget' : 'reward_quota' => ['prohibited']])->validate();
  42. $previous = $existing ? $existing->only(array_keys($defaults)) : [];
  43. foreach (['publish_platforms', 'register_platforms'] as $field) {
  44. if (($previous[$field] ?? null) === null) $previous[$field] = [];
  45. }
  46. $config = array_replace($defaults, $previous, array_intersect_key($params, $defaults));
  47. if ($quotaMode) $config['budget'] = null;
  48. else $config['reward_quota'] = null;
  49. if (empty($config['register_time_limited'])) {
  50. $config['register_start_time'] = $config['register_end_time'] = null;
  51. }
  52. if (empty($config['deposit_limited'])) {
  53. $config['deposit_min'] = $config['deposit_max'] = null;
  54. }
  55. $money = ['nullable', 'numeric', 'min:0', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
  56. Validator::make($config, [
  57. 'publish_platforms' => ['present', 'array'],
  58. 'publish_platforms.*' => ['required', 'string', 'distinct', Rule::in(['PC', 'H5', 'APP'])],
  59. 'reward_quota' => ['nullable', 'integer', 'min:0', 'max:2147483647'],
  60. 'budget' => $money,
  61. 'sort' => ['required', 'integer', 'min:0', 'max:4294967295'],
  62. 'register_time_limited' => ['required', 'boolean'],
  63. 'register_start_time' => ['nullable', 'required_if:register_time_limited,1', 'date'],
  64. 'register_end_time' => ['nullable', 'required_if:register_time_limited,1', 'date', 'after_or_equal:register_start_time'],
  65. 'register_platforms' => ['present', 'array'],
  66. 'register_platforms.*' => ['required', 'string', 'distinct', Rule::in(['PC', 'H5', 'APP'])],
  67. 'deposit_limited' => ['required', 'boolean'],
  68. 'deposit_min' => array_merge($money, ['required_if:deposit_limited,1']),
  69. 'deposit_max' => array_merge($money, ['required_if:deposit_limited,1', 'gte:deposit_min']),
  70. 'show_ineligible' => ['required', 'boolean'],
  71. ])->validate();
  72. foreach (['budget', 'deposit_min', 'deposit_max'] as $field) {
  73. if ($config[$field] !== null) {
  74. $config[$field] = bcadd((string)$config[$field], '0', 2);
  75. }
  76. }
  77. if ($config['reward_quota'] !== null) $config['reward_quota'] = (int)$config['reward_quota'];
  78. foreach (['register_start_time', 'register_end_time'] as $field) {
  79. if ($config[$field] !== null) {
  80. $config[$field] = date('Y-m-d H:i:s', strtotime($config[$field]));
  81. }
  82. }
  83. return $config;
  84. }
  85. /**
  86. * @description: 查询单条数据
  87. * @param array $search
  88. * @return ActivityReward|null
  89. */
  90. public static function findOne(array $search): ActivityReward|null
  91. {
  92. return static::$MODEL::where(static::getWhere($search))->first();
  93. }
  94. public static function activeForMember(int $type, $memberId): ?ActivityReward
  95. {
  96. $context = ActivityEligibilityService::memberContext($memberId);
  97. $activities = ActivityReward::where('lang', 'zh')->where('type', $type)->where('status', 1)
  98. ->where('start_time', '<=', time())->where('end_time', '>=', time())
  99. ->orderByDesc('sort')->orderByDesc('id')->get();
  100. foreach ($activities as $activity) {
  101. if (!ActivityEligibilityService::evaluate($activity, $context)['is_eligible']) continue;
  102. if (!ActivityQuotaService::canAward($activity, $memberId)) continue;
  103. return $activity;
  104. }
  105. return null;
  106. }
  107. public static function getWhere(array $search = []): array
  108. {
  109. $where = [];
  110. if (isset($search['id']) && !empty($search['id'])) {
  111. $where[] = ['id', '=', $search['id']];
  112. }
  113. if (isset($search['status']) && $search['status'] != '') {
  114. $where[] = ['status', '=', $search['status']];
  115. }
  116. if (isset($search['type']) && $search['type'] != '') {
  117. $where[] = ['type', '=', $search['type']];
  118. }
  119. if (isset($search['title']) && !empty($search['title'])) {
  120. $where[] = ['title', 'like', "%{$search['title']}%"];
  121. }
  122. if (isset($search['start_time']) && !empty($search['start_time'])) {
  123. if (is_array($search['start_time'])) {
  124. if (count($search['start_time']) == 2) {
  125. $where[] = ['start_time', $search['start_time'][0], $search['start_time'][1]];
  126. } else {
  127. $where[] = ['start_time', '=', $search['start_time'][0]];
  128. }
  129. } else {
  130. $where[] = ['start_time', '=', $search['start_time']];
  131. }
  132. }
  133. if (isset($search['end_time']) && !empty($search['end_time'])) {
  134. if (is_array($search['end_time'])) {
  135. if (count($search['end_time']) == 2) {
  136. $where[] = ['end_time', $search['end_time'][0], $search['end_time'][1]];
  137. } else {
  138. $where[] = ['end_time', '=', $search['end_time'][0]];
  139. }
  140. } else {
  141. $where[] = ['end_time', '=', $search['end_time']];
  142. }
  143. }
  144. return $where;
  145. }
  146. public static function deleteAll(array $search = []): bool
  147. {
  148. $count = static::$MODEL::where(static::getWhere($search))->delete();
  149. if ($count < 1) throw new Exception('删除失败', HttpStatus::CUSTOM_ERROR);
  150. return true;
  151. }
  152. /**
  153. * Update or create
  154. * @param array $params
  155. * @return bool
  156. * @throws Exception
  157. */
  158. public static function submit(array $params = []): bool
  159. {
  160. unset($params['detail_banner'], $params['pc_banner']);
  161. $info = !empty($params['id']) ? static::findOne(['id' => $params['id']]) : null;
  162. if (!empty($params['id']) && !$info) throw new Exception('操作失败', HttpStatus::CUSTOM_ERROR);
  163. if (array_key_exists('game_category', $params)) {
  164. Validator::make($params, [
  165. 'game_category' => ['nullable', 'string', Rule::in(array_keys(ActivityCatalog::gameTypes()))],
  166. ])->validate();
  167. if ($params['game_category'] === '') $params['game_category'] = null;
  168. }
  169. $params = array_merge($params, static::configuration($params, $info), static::clickBehavior($params, $info));
  170. unset($params['rewarded_count'], $params['quota_enabled'], $params['budget_used']); // Server-owned fields.
  171. if (isset($params['start_time']))
  172. $params['start_time'] = strtotime($params['start_time']);
  173. if (isset($params['end_time']))
  174. $params['end_time'] = strtotime($params['end_time']);
  175. if (isset($params['detail_image']))
  176. $params['detail_image'] = Util::replacePartInUrl($params['detail_image']);
  177. if (isset($params['pc_image']))
  178. $params['pc_image'] = Util::replacePartInUrl($params['pc_image']);
  179. if (!empty($params['id'])) {
  180. $info->update($params);
  181. } else {
  182. $info = new ActivityReward($params);
  183. // Legacy schemas require these unused columns; frontend inputs are never persisted.
  184. $info->detail_banner = '';
  185. $info->pc_banner = '';
  186. $info->quota_enabled = true; // Existing rows stay false; clients cannot change the mode.
  187. $info->save();
  188. }
  189. return true;
  190. }
  191. private static function clickBehavior(array $params, ?ActivityReward $existing): array
  192. {
  193. if (!array_intersect_key($params, array_flip(array_merge(ContentLink::FIELDS, ['click_position'])))) return [];
  194. $links = ContentLink::forSave($params, $existing?->getAttributes() ?? []);
  195. if ($links['click_type'] === 'none') return $links + ['click_position' => null];
  196. $position = array_key_exists('click_position', $params) ? $params['click_position'] : $existing?->click_position;
  197. Validator::make(['click_position' => $position], ['click_position' => ['required', 'string', Rule::in(['cover', 'detail'])]],
  198. ['click_position.required' => '请选择链接触发位置', 'click_position.in' => '链接触发位置仅支持活动列表封面或活动详情按钮'])->validate();
  199. return $links + ['click_position' => $position];
  200. }
  201. public static function promotionalActivity($chatId): array
  202. {
  203. $keyboard = [];
  204. $url = Config::where('field','activity_home_url')->first()->val;
  205. $url.="?member_id=".$chatId;
  206. $keyboard[] = [
  207. ['text'=>'活动首页','url'=>$url]
  208. ];
  209. $msg = [];
  210. $msg['chat_id'] = $chatId;
  211. $msg['text'] = "点击下方按钮进入活动首页";
  212. $msg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  213. return $msg;
  214. }
  215. //F1bet娱乐更多玩法(足球首页)
  216. public static function footballUrl($chatId): array
  217. {
  218. $token = UserSession::setToken($chatId);
  219. $is_bind = User::where('member_id', $chatId)->value('account') ? 1 : 0;
  220. $keyboard = [];
  221. $url = Config::where('field','football_home_url ')->first()->val;
  222. $url.="?token=".$token."&is_bind=".$is_bind;
  223. $keyboard[] = [
  224. ['text'=>'F1bet娱乐首页','url'=>$url]
  225. ];
  226. $msg = [];
  227. $msg['chat_id'] = $chatId;
  228. $msg['text'] = "点击下方按钮进入F1bet娱乐首页";
  229. $msg['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
  230. return $msg;
  231. }
  232. }