ProjectGanttService.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Services\Project;
  3. use App\Http\Resources\API\ProjectGanttResource;
  4. use App\Http\Resources\API\ProjectGroupViewTaskResource;
  5. use App\Models\Enums\ProjectStatus;
  6. use App\Models\Project;
  7. use App\Models\Requirement;
  8. use App\Models\Task;
  9. use App\Models\User;
  10. use Illuminate\Support\Collection;
  11. class ProjectGanttService
  12. {
  13. public function gantt(Project $project, string $group): array
  14. {
  15. $groupTasks = $this->getGroupTask($project, $group);
  16. $groups = $groupTasks->keys()->filter();
  17. $groupNamesKeyBy = $this->getGroupNamesKeyBy($groups, $group);
  18. $items = [];
  19. foreach(["", ...$groups] as $groupKey) {
  20. if (! isset($groupTasks[$groupKey])) {
  21. continue;
  22. }
  23. $group_label = $groupKey == "" ? ['id' => "", "name" => ""] : $groupNamesKeyBy[$groupKey];
  24. foreach ($groupTasks[$groupKey] as $tasks){
  25. if ($tasks->parent_id===0){ //若该任务为顶层任务,则取其任务名以及id,否则找该任务的父级id和父级name
  26. $tasks->group_label_id=$group_label['id'];
  27. $tasks->group_label_name=$group_label['name'];
  28. }else{
  29. $tasks->group_label_id=$tasks->parent_id;
  30. $tasks->group_label_name=$tasks->parent->name;
  31. }
  32. }
  33. $items[] = [
  34. // 'group' => $group,
  35. // 'group_label' => $groupKey == "" ? ['id' => "", "name" => ""] : $groupNamesKeyBy[$groupKey],
  36. ProjectGanttResource::collection($groupTasks[$groupKey]),
  37. ];
  38. };
  39. $result=[];
  40. foreach ($items as $item){
  41. foreach ($item as $it){
  42. foreach ($it as $i){
  43. $result[]= $i;
  44. }
  45. }
  46. }
  47. return $result;
  48. }
  49. protected function getGroupNamesKeyBy(Collection $groups, string $group): array
  50. {
  51. $groupsFormat = $groups->map(fn($group) => ['id' => $group, 'name' => $group]);
  52. $groupNames = match ($group) {
  53. "requirement_id" => Requirement::query()->whereIn("id", $groups)->selectRaw("id,title as name")->get(),
  54. "task_type" => $groupsFormat,
  55. "assign" => User::query()->whereIn("id", $groups)->get(['id', 'name']),
  56. };
  57. return $groupNames->keyBy("id")->toArray();
  58. }
  59. protected function getGroupTask(
  60. Project $project,
  61. string $group,
  62. ): \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|array
  63. {
  64. return Task::query()
  65. ->with(['assignTo', 'finishedBy'])
  66. ->where("project_id", $project->id)
  67. ->get()
  68. ->groupBy($group);
  69. }
  70. }