QuotaService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace App\Module\ThirdParty\Services;
  3. use App\Module\ThirdParty\Models\ThirdPartyQuota;
  4. use App\Module\ThirdParty\Models\ThirdPartyService;
  5. use App\Module\ThirdParty\Enums\QUOTA_TYPE;
  6. use Illuminate\Support\Collection;
  7. /**
  8. * 第三方服务配额管理服务类
  9. */
  10. class QuotaService
  11. {
  12. /**
  13. * 创建配额
  14. *
  15. * @param array $data
  16. * @return ThirdPartyQuota
  17. * @throws \Exception
  18. */
  19. public static function create(array $data): ThirdPartyQuota
  20. {
  21. // 验证服务是否存在
  22. $service = ThirdPartyService::find($data['service_id']);
  23. if (!$service) {
  24. throw new \Exception("服务不存在: {$data['service_id']}");
  25. }
  26. // 验证配额类型
  27. if (!QUOTA_TYPE::tryFrom($data['type'])) {
  28. throw new \Exception("无效的配额类型: {$data['type']}");
  29. }
  30. // 检查是否已存在相同类型的配额
  31. $existing = ThirdPartyQuota::where('service_id', $data['service_id'])
  32. ->where('type', $data['type'])
  33. ->first();
  34. if ($existing) {
  35. throw new \Exception("服务已存在 {$data['type']} 类型的配额");
  36. }
  37. return ThirdPartyQuota::createQuota($data);
  38. }
  39. /**
  40. * 更新配额
  41. *
  42. * @param int $quotaId
  43. * @param array $data
  44. * @return bool
  45. * @throws \Exception
  46. */
  47. public static function update(int $quotaId, array $data): bool
  48. {
  49. $quota = ThirdPartyQuota::findOrFail($quotaId);
  50. // 如果更新配额类型,验证唯一性
  51. if (isset($data['type']) && $data['type'] !== $quota->type) {
  52. if (!QUOTA_TYPE::tryFrom($data['type'])) {
  53. throw new \Exception("无效的配额类型: {$data['type']}");
  54. }
  55. $existing = ThirdPartyQuota::where('service_id', $quota->service_id)
  56. ->where('type', $data['type'])
  57. ->where('id', '!=', $quotaId)
  58. ->first();
  59. if ($existing) {
  60. throw new \Exception("服务已存在 {$data['type']} 类型的配额");
  61. }
  62. }
  63. return $quota->update($data);
  64. }
  65. /**
  66. * 删除配额
  67. *
  68. * @param int $quotaId
  69. * @return bool
  70. */
  71. public static function delete(int $quotaId): bool
  72. {
  73. $quota = ThirdPartyQuota::findOrFail($quotaId);
  74. return $quota->delete();
  75. }
  76. /**
  77. * 获取配额详情
  78. *
  79. * @param int $quotaId
  80. * @return ThirdPartyQuota
  81. */
  82. public static function getById(int $quotaId): ThirdPartyQuota
  83. {
  84. return ThirdPartyQuota::with('service')->findOrFail($quotaId);
  85. }
  86. /**
  87. * 获取配额列表
  88. *
  89. * @param array $filters
  90. * @param array $options
  91. * @return Collection
  92. */
  93. public static function getList(array $filters = [], array $options = []): Collection
  94. {
  95. $query = ThirdPartyQuota::with('service');
  96. // 应用过滤条件
  97. if (isset($filters['service_id'])) {
  98. $query->where('service_id', $filters['service_id']);
  99. }
  100. if (isset($filters['type'])) {
  101. $query->where('type', $filters['type']);
  102. }
  103. if (isset($filters['is_active'])) {
  104. $query->where('is_active', $filters['is_active']);
  105. }
  106. if (isset($filters['is_exceeded'])) {
  107. $query->where('is_exceeded', $filters['is_exceeded']);
  108. }
  109. if (isset($filters['near_threshold'])) {
  110. if ($filters['near_threshold']) {
  111. $query->nearThreshold();
  112. }
  113. }
  114. // 应用排序
  115. $sortBy = $options['sort_by'] ?? 'created_at';
  116. $sortOrder = $options['sort_order'] ?? 'desc';
  117. $query->orderBy($sortBy, $sortOrder);
  118. return $query->get();
  119. }
  120. /**
  121. * 检查配额是否可用
  122. *
  123. * @param int $serviceId
  124. * @param int $amount
  125. * @return bool
  126. */
  127. public static function canUse(int $serviceId, int $amount = 1): bool
  128. {
  129. $quotas = ThirdPartyQuota::where('service_id', $serviceId)
  130. ->where('is_active', true)
  131. ->get();
  132. foreach ($quotas as $quota) {
  133. if (!$quota->canUse($amount)) {
  134. return false;
  135. }
  136. }
  137. return true;
  138. }
  139. /**
  140. * 使用配额
  141. *
  142. * @param int $serviceId
  143. * @param int $amount
  144. * @return bool
  145. */
  146. public static function use(int $serviceId, int $amount = 1): bool
  147. {
  148. $quotas = ThirdPartyQuota::where('service_id', $serviceId)
  149. ->where('is_active', true)
  150. ->get();
  151. foreach ($quotas as $quota) {
  152. $quota->incrementUsage($amount);
  153. }
  154. return true;
  155. }
  156. /**
  157. * 重置配额
  158. *
  159. * @param int $quotaId
  160. * @return bool
  161. */
  162. public static function reset(int $quotaId): bool
  163. {
  164. $quota = ThirdPartyQuota::findOrFail($quotaId);
  165. return $quota->resetQuota();
  166. }
  167. /**
  168. * 批量重置配额
  169. *
  170. * @param array $quotaIds
  171. * @return array
  172. */
  173. public static function batchReset(array $quotaIds): array
  174. {
  175. $results = [
  176. 'success' => [],
  177. 'failed' => [],
  178. ];
  179. foreach ($quotaIds as $quotaId) {
  180. try {
  181. static::reset($quotaId);
  182. $results['success'][] = $quotaId;
  183. } catch (\Exception $e) {
  184. $results['failed'][] = [
  185. 'id' => $quotaId,
  186. 'error' => $e->getMessage(),
  187. ];
  188. }
  189. }
  190. return $results;
  191. }
  192. /**
  193. * 获取需要重置的配额
  194. *
  195. * @return Collection
  196. */
  197. public static function getQuotasNeedingReset(): Collection
  198. {
  199. return ThirdPartyQuota::where('is_active', true)
  200. ->get()
  201. ->filter(function ($quota) {
  202. return $quota->needsReset();
  203. });
  204. }
  205. /**
  206. * 自动重置配额
  207. *
  208. * @return int 重置数量
  209. */
  210. public static function autoReset(): int
  211. {
  212. $quotas = static::getQuotasNeedingReset();
  213. $resetCount = 0;
  214. foreach ($quotas as $quota) {
  215. try {
  216. $quota->resetQuota();
  217. $resetCount++;
  218. } catch (\Exception $e) {
  219. \Log::warning("自动重置配额失败: {$quota->id}, 错误: {$e->getMessage()}");
  220. }
  221. }
  222. return $resetCount;
  223. }
  224. /**
  225. * 获取超限的配额
  226. *
  227. * @return Collection
  228. */
  229. public static function getExceededQuotas(): Collection
  230. {
  231. return ThirdPartyQuota::with('service')
  232. ->where('is_active', true)
  233. ->where('is_exceeded', true)
  234. ->get();
  235. }
  236. /**
  237. * 获取接近阈值的配额
  238. *
  239. * @return Collection
  240. */
  241. public static function getNearThresholdQuotas(): Collection
  242. {
  243. return ThirdPartyQuota::with('service')
  244. ->where('is_active', true)
  245. ->nearThreshold()
  246. ->get();
  247. }
  248. /**
  249. * 获取配额统计信息
  250. *
  251. * @param int|null $serviceId
  252. * @return array
  253. */
  254. public static function getStats(?int $serviceId = null): array
  255. {
  256. $query = ThirdPartyQuota::query();
  257. if ($serviceId) {
  258. $query->where('service_id', $serviceId);
  259. }
  260. $total = $query->count();
  261. $active = $query->where('is_active', true)->count();
  262. $exceeded = $query->where('is_exceeded', true)->count();
  263. $nearThreshold = $query->nearThreshold()->count();
  264. // 按类型统计
  265. $typeStats = $query->selectRaw('type, COUNT(*) as count')
  266. ->groupBy('type')
  267. ->pluck('count', 'type')
  268. ->toArray();
  269. // 使用率统计
  270. $usageStats = $query->where('is_active', true)
  271. ->get()
  272. ->map(function ($quota) {
  273. return [
  274. 'service_name' => $quota->service->name,
  275. 'type' => $quota->type,
  276. 'usage_percentage' => $quota->getUsagePercentage(),
  277. 'status' => $quota->getStatus(),
  278. ];
  279. })
  280. ->toArray();
  281. return [
  282. 'total' => $total,
  283. 'active' => $active,
  284. 'exceeded' => $exceeded,
  285. 'near_threshold' => $nearThreshold,
  286. 'by_type' => $typeStats,
  287. 'usage_stats' => $usageStats,
  288. 'health_rate' => $total > 0 ? round((($active - $exceeded) / $total) * 100, 2) : 0,
  289. ];
  290. }
  291. /**
  292. * 创建默认配额
  293. *
  294. * @param int $serviceId
  295. * @return array
  296. */
  297. public static function createDefaultQuotas(int $serviceId): array
  298. {
  299. $service = ThirdPartyService::findOrFail($serviceId);
  300. $defaultLimits = config('thirdparty.quota.default_limits', []);
  301. $created = [];
  302. foreach ($defaultLimits as $type => $limit) {
  303. try {
  304. $quota = static::create([
  305. 'service_id' => $serviceId,
  306. 'type' => $type,
  307. 'limit_value' => $limit,
  308. 'is_active' => true,
  309. ]);
  310. $created[] = $quota;
  311. } catch (\Exception $e) {
  312. // 如果配额已存在,跳过
  313. if (!str_contains($e->getMessage(), '已存在')) {
  314. throw $e;
  315. }
  316. }
  317. }
  318. return $created;
  319. }
  320. /**
  321. * 导出配额配置
  322. *
  323. * @param array $quotaIds
  324. * @return array
  325. */
  326. public static function export(array $quotaIds = []): array
  327. {
  328. $query = ThirdPartyQuota::with('service');
  329. if (!empty($quotaIds)) {
  330. $query->whereIn('id', $quotaIds);
  331. }
  332. $quotas = $query->get();
  333. $exported = [];
  334. foreach ($quotas as $quota) {
  335. $exported[] = [
  336. 'id' => $quota->id,
  337. 'service_name' => $quota->service->name,
  338. 'service_code' => $quota->service->code,
  339. 'type' => $quota->type,
  340. 'type_label' => $quota->getTypeLabel(),
  341. 'limit_value' => $quota->limit_value,
  342. 'used_value' => $quota->used_value,
  343. 'usage_percentage' => $quota->getUsagePercentage(),
  344. 'is_active' => $quota->is_active,
  345. 'alert_threshold' => $quota->alert_threshold,
  346. 'is_exceeded' => $quota->is_exceeded,
  347. 'status' => $quota->getStatusLabel(),
  348. 'created_at' => $quota->created_at->toDateTimeString(),
  349. ];
  350. }
  351. return $exported;
  352. }
  353. }