ReadingTimeService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\ReadingDaily;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Validation\ValidationException;
  6. /**
  7. * 登录用户读经时长的上报与核减。读经时长按策略换积分(见 {@see CreditService::settle()})。
  8. *
  9. * 时长是客户端自报的,服务端只做两道核减:
  10. * - 当天的上报,计入的秒数不超过「距上次上报过去的时间 + 30 秒余量」——
  11. * 多台设备同时报、或者一次报个大数,都只按墙钟时间算;
  12. * - 单日累计不超过 24 小时。
  13. * 断网补报允许最多 2 天前,补报的那几天不做墙钟核减(换积分时每天另有上限)。
  14. */
  15. class ReadingTimeService
  16. {
  17. private const SLACK_SECONDS = 30;
  18. private const BACKFILL_DAYS = 2;
  19. /**
  20. * @throws ValidationException day 早于补报期限或在未来
  21. */
  22. public function report(string $userUid, int $seconds, ?string $day): ReadingDaily
  23. {
  24. $today = now('UTC')->startOfDay();
  25. $target = $day ? now('UTC')->parse($day)->startOfDay() : $today;
  26. if ($target->gt($today) || $target->lt($today->copy()->subDays(self::BACKFILL_DAYS))) {
  27. throw ValidationException::withMessages(['day' => __('messages.reading_time_day_out_of_range')]);
  28. }
  29. $isToday = $target->equalTo($today);
  30. return DB::transaction(function () use ($userUid, $seconds, $target, $isToday) {
  31. ReadingDaily::createOrFirst(['user_uid' => $userUid, 'day' => $target->toDateString()]);
  32. $row = ReadingDaily::where('user_uid', $userUid)->where('day', $target->toDateString())
  33. ->lockForUpdate()->firstOrFail();
  34. $allowed = $seconds;
  35. if ($isToday && $row->last_report_at) {
  36. $elapsed = (int) $row->last_report_at->diffInSeconds(now(), true);
  37. $allowed = min($allowed, $elapsed + self::SLACK_SECONDS);
  38. }
  39. $allowed = max(0, min($allowed, 86400 - (int) $row->seconds));
  40. $row->seconds_reported = (int) $row->seconds_reported + $seconds;
  41. $row->seconds = (int) $row->seconds + $allowed;
  42. if ($isToday) {
  43. $row->last_report_at = now();
  44. }
  45. $row->save();
  46. return $row;
  47. });
  48. }
  49. }