EvaluationCampaignService.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\DefaultStatusEnum;
  4. use App\Enums\UserTypeEnum;
  5. use App\Models\Evaluation;
  6. use App\Models\EvaluationCampaign;
  7. use App\Models\User;
  8. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  9. use Illuminate\Support\Facades\Auth;
  10. use Illuminate\Support\Facades\DB;
  11. class EvaluationCampaignService
  12. {
  13. public function getAllPaginated(int $perPage = 12): LengthAwarePaginator
  14. {
  15. return EvaluationCampaign::with('createdBy')
  16. ->withCount('evaluations')
  17. ->withAvg('evaluations', 'rating')
  18. ->orderByRaw("CASE WHEN status = 'ACTIVE' THEN 0 ELSE 1 END")
  19. ->orderBy('created_at', 'desc')
  20. ->paginate($perPage);
  21. }
  22. public function findById(int $id): ?EvaluationCampaign
  23. {
  24. return EvaluationCampaign::with('createdBy')
  25. ->withCount('evaluations')
  26. ->withAvg('evaluations', 'rating')
  27. ->find($id);
  28. }
  29. /**
  30. * Toda campanha nasce ativa: a que estiver no ar é encerrada no mesmo instante.
  31. */
  32. public function create(array $data): EvaluationCampaign
  33. {
  34. return DB::transaction(function () use ($data) {
  35. $this->finishActiveCampaigns();
  36. $campaign = EvaluationCampaign::create([
  37. 'title' => $data['title'],
  38. 'description' => $data['description'] ?? null,
  39. 'target' => $data['target'],
  40. 'status' => DefaultStatusEnum::ACTIVE->value,
  41. 'started_at' => now(),
  42. 'created_by' => Auth::id(),
  43. ]);
  44. return $campaign->load('createdBy');
  45. });
  46. }
  47. /**
  48. * Apenas título e descrição — alvo e ciclo de vida não mudam depois da criação.
  49. */
  50. public function update(int $id, array $data): ?EvaluationCampaign
  51. {
  52. $campaign = EvaluationCampaign::find($id);
  53. if (!$campaign) {
  54. return null;
  55. }
  56. $campaign->update(array_intersect_key($data, array_flip(['title', 'description'])));
  57. return $campaign->fresh('createdBy');
  58. }
  59. public function delete(int $id): bool
  60. {
  61. $campaign = EvaluationCampaign::find($id);
  62. if (!$campaign) {
  63. return false;
  64. }
  65. return (bool) $campaign->delete();
  66. }
  67. /**
  68. * Encerra a campanha: registra o fim e tira do ar. Não há reabertura.
  69. *
  70. * @return array{error?: string, campaign?: EvaluationCampaign}
  71. */
  72. public function finish(int $id): array
  73. {
  74. $campaign = EvaluationCampaign::find($id);
  75. if (!$campaign) {
  76. return ['error' => 'not_found'];
  77. }
  78. if ($campaign->isFinished()) {
  79. return ['error' => 'already_finished'];
  80. }
  81. $campaign->update([
  82. 'status' => DefaultStatusEnum::INACTIVE->value,
  83. 'finished_at' => now(),
  84. ]);
  85. return ['campaign' => $campaign->fresh('createdBy')];
  86. }
  87. private function finishActiveCampaigns(): void
  88. {
  89. EvaluationCampaign::where('status', DefaultStatusEnum::ACTIVE->value)
  90. ->update([
  91. 'status' => DefaultStatusEnum::INACTIVE->value,
  92. 'finished_at' => now(),
  93. 'updated_at' => now(),
  94. ]);
  95. }
  96. public function getActiveCampaign(): ?EvaluationCampaign
  97. {
  98. return EvaluationCampaign::where('status', DefaultStatusEnum::ACTIVE->value)->first();
  99. }
  100. /**
  101. * Campanha que o usuário ainda precisa responder, ou null se não houver pendência.
  102. */
  103. public function getPendingForUser(User $user): ?EvaluationCampaign
  104. {
  105. $campaign = $this->getActiveCampaign();
  106. if (!$campaign) {
  107. return null;
  108. }
  109. if (!$campaign->target->accepts($user->type)) {
  110. return null;
  111. }
  112. $alreadyAnswered = Evaluation::where('evaluation_campaign_id', $campaign->id)
  113. ->where('user_id', $user->id)
  114. ->exists();
  115. return $alreadyAnswered ? null : $campaign;
  116. }
  117. /**
  118. * Registra a avaliação do usuário autenticado na campanha ativa.
  119. *
  120. * @return array{error?: string, evaluation?: Evaluation}
  121. */
  122. public function submit(User $user, int $campaignId, array $data): array
  123. {
  124. $campaign = EvaluationCampaign::find($campaignId);
  125. if (!$campaign) {
  126. return ['error' => 'not_found'];
  127. }
  128. if (!$campaign->isActive()) {
  129. return ['error' => 'inactive'];
  130. }
  131. if (!$campaign->target->accepts($user->type)) {
  132. return ['error' => 'not_eligible'];
  133. }
  134. $exists = Evaluation::where('evaluation_campaign_id', $campaign->id)
  135. ->where('user_id', $user->id)
  136. ->exists();
  137. if ($exists) {
  138. return ['error' => 'already_answered'];
  139. }
  140. $evaluation = Evaluation::create([
  141. 'evaluation_campaign_id' => $campaign->id,
  142. 'user_id' => $user->id,
  143. 'rating' => $data['rating'],
  144. 'comment' => $data['comment'] ?? null,
  145. ]);
  146. return ['evaluation' => $evaluation->load('user')];
  147. }
  148. /**
  149. * Avaliações de uma campanha, com filtros de origem, faixa de nota e busca por nome.
  150. */
  151. public function getEvaluationsPaginated(int $campaignId, array $filters = [], int $perPage = 12): LengthAwarePaginator
  152. {
  153. $query = Evaluation::with('user')
  154. ->where('evaluation_campaign_id', $campaignId);
  155. if (!empty($filters['source'])) {
  156. $query->whereHas('user', fn($q) => $q->where('type', $filters['source']));
  157. }
  158. if (!empty($filters['min_rating'])) {
  159. $query->where('rating', '>=', (int) $filters['min_rating']);
  160. }
  161. if (!empty($filters['max_rating'])) {
  162. $query->where('rating', '<=', (int) $filters['max_rating']);
  163. }
  164. if (!empty($filters['search'])) {
  165. $term = '%' . mb_strtolower($filters['search']) . '%';
  166. $query->where(function ($q) use ($term) {
  167. $q->whereHas('user', fn($u) => $u->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term]))
  168. ->orWhereRaw('UNACCENT(LOWER(comment)) LIKE UNACCENT(?)', [$term]);
  169. });
  170. }
  171. return $query->orderBy('created_at', 'desc')->paginate($perPage);
  172. }
  173. /**
  174. * Blocos de estatística da campanha: total, média, adesão, distribuição e quebra por origem.
  175. */
  176. public function getStats(int $campaignId): ?array
  177. {
  178. $campaign = EvaluationCampaign::find($campaignId);
  179. if (!$campaign) {
  180. return null;
  181. }
  182. $totals = Evaluation::where('evaluation_campaign_id', $campaignId)
  183. ->selectRaw('COUNT(*) as total, AVG(rating) as average')
  184. ->first();
  185. $total = (int) ($totals->total ?? 0);
  186. $average = $totals->average !== null ? round((float) $totals->average, 2) : null;
  187. $distributionRaw = Evaluation::where('evaluation_campaign_id', $campaignId)
  188. ->selectRaw('rating, COUNT(*) as total')
  189. ->groupBy('rating')
  190. ->pluck('total', 'rating');
  191. $distribution = [];
  192. for ($rating = 1; $rating <= 10; $rating++) {
  193. $distribution[] = [
  194. 'rating' => $rating,
  195. 'total' => (int) ($distributionRaw[$rating] ?? 0),
  196. ];
  197. }
  198. $bySourceRaw = Evaluation::where('evaluation_campaign_id', $campaignId)
  199. ->join('users', 'users.id', '=', 'evaluations.user_id')
  200. ->selectRaw('users.type as source, COUNT(*) as total, AVG(evaluations.rating) as average')
  201. ->groupBy('users.type')
  202. ->get()
  203. ->keyBy('source');
  204. $bySource = [];
  205. foreach ($campaign->target->userTypes() as $userType) {
  206. $row = $bySourceRaw->get($userType->value);
  207. $bySource[] = [
  208. 'source' => $userType->value,
  209. 'total' => (int) ($row->total ?? 0),
  210. 'average' => isset($row->average) ? round((float) $row->average, 2) : null,
  211. ];
  212. }
  213. $eligible = $this->countEligibleUsers($campaign);
  214. return [
  215. 'campaign_id' => $campaign->id,
  216. 'total' => $total,
  217. 'average' => $average,
  218. 'eligible_total' => $eligible,
  219. 'adherence' => $eligible > 0 ? round(($total / $eligible) * 100, 1) : 0.0,
  220. 'distribution' => $distribution,
  221. 'by_source' => $bySource,
  222. ];
  223. }
  224. private function countEligibleUsers(EvaluationCampaign $campaign): int
  225. {
  226. $types = array_map(fn(UserTypeEnum $type) => $type->value, $campaign->target->userTypes());
  227. return User::whereIn('type', $types)
  228. ->whereNull('excluded_at')
  229. ->count();
  230. }
  231. }