ActionRepository.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. namespace App\Repositories;
  3. use App\Models\Action;
  4. use App\Models\Enums\ActionObjectType;
  5. use App\Models\Enums\ObjectAction;
  6. use App\Models\History;
  7. use App\Models\Project;
  8. use App\Models\Requirement;
  9. use App\Models\Task;
  10. use Carbon\Carbon;
  11. use Illuminate\Support\Collection;
  12. use Illuminate\Support\Facades\Auth;
  13. class ActionRepository
  14. {
  15. public static function create(
  16. int $objectId,
  17. ActionObjectType $objectType,
  18. ObjectAction $action,
  19. int|null $projectId = null,
  20. string $comment = null,
  21. array $extraFields = [],
  22. array $objectChanges = [],
  23. ): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder
  24. {
  25. $action = Action::query()->create([
  26. "object_id" => $objectId,
  27. "object_type" => $objectType->value,
  28. "action" => $action,
  29. "project_id" => $projectId,
  30. "comment" => $comment,
  31. "extra_fields" => $extraFields ?: null,
  32. "created_by" => Auth::id(),
  33. ]);
  34. if ($objectChanges) {
  35. History::query()->insert(array_map(fn($change) => [...$change, 'action_id' => $action->id], $objectChanges));
  36. }
  37. return $action;
  38. }
  39. public static function createByProject(
  40. Project $project,
  41. ObjectAction $action,
  42. string $comment = null,
  43. array $extraFields = [],
  44. array $objectChanges = [],
  45. ): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder
  46. {
  47. return self::create(
  48. $project->id,
  49. ActionObjectType::PROJECT,
  50. $action,
  51. $project->id,
  52. $comment,
  53. $extraFields,
  54. $objectChanges,
  55. );
  56. }
  57. public static function createRequirement(
  58. Requirement $requirement,
  59. ObjectAction $action,
  60. string $comment = null,
  61. array $extraFields = [],
  62. array $objectChanges = [],
  63. ): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder
  64. {
  65. return self::create(
  66. $requirement->id,
  67. ActionObjectType::REQUIREMENT,
  68. $action,
  69. null,
  70. $comment,
  71. $extraFields,
  72. $objectChanges,
  73. );
  74. }
  75. public static function createByTask(
  76. Task $task,
  77. ObjectAction $action,
  78. string $comment = null,
  79. array $extraFields = [],
  80. array $objectChanges = [],
  81. ): \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Builder
  82. {
  83. return self::create(
  84. $task->id,
  85. ActionObjectType::TASK,
  86. $action,
  87. $task->project_id,
  88. $comment,
  89. $extraFields,
  90. $objectChanges,
  91. );
  92. }
  93. public static function latestDynamic(Project $project)
  94. {
  95. $actions = Action::query()
  96. ->where("project_id", $project->id)
  97. ->with(['createdBy'])
  98. ->orderByDesc("created_at")
  99. ->limit(20)
  100. ->get();
  101. $objectNames = self::objectNamesGroupByType($actions);
  102. $items = [];
  103. foreach ($actions as $action) {
  104. $items[] = self::actionFormat($action->toArray(), $objectNames);
  105. }
  106. return $items;
  107. }
  108. public static function actionFormat(array $action, array $objectNames): array
  109. {
  110. $labelKey = sprintf("action-labels.label.%s", $action['action']);
  111. $objectLabelKey = sprintf("action-labels.object_type.%s", $action['object_type']);
  112. $cratedAt = Carbon::parse($action['created_at']);
  113. return [
  114. 'time' => $cratedAt->toTimeString(),
  115. 'created_at' => $cratedAt->toDateTimeString(),
  116. 'created_by' => [
  117. 'id' => $action['created_by']['id'],
  118. 'name' => $action['created_by']['name'],
  119. 'username' => $action['created_by']['username'],
  120. ],
  121. 'action_label' => app('translator')->has($labelKey) ? __($labelKey) : $action['action'],
  122. 'object_label' => app('translator')->has($objectLabelKey) ? __($objectLabelKey) : $action['object_type'],
  123. 'object_id' => $action['object_id'],
  124. 'object_type' => $action['object_type'],
  125. 'object_name' => data_get($objectNames, sprintf("%s.%d", $action['object_type'], $action['object_id'])),
  126. 'comment' => $action['comment'],
  127. ];
  128. }
  129. public static function dynamic(Project $project, array $filter = [])
  130. {
  131. $actions = Action::query()->filter($filter)
  132. ->where("project_id", $project->id)
  133. ->with(['createdBy'])
  134. ->selectRaw("*, date_format(created_at, '%Y-%m-%d') as created_date")
  135. ->orderBy("created_at")
  136. ->get();
  137. $objectNames = self::objectNamesGroupByType($actions);
  138. $items = $actions->groupBy("created_date")->toArray();
  139. krsort($items);
  140. $data = [];
  141. foreach ($items as $day => $actionItems) {
  142. $dayItems = [
  143. 'date' => $day,
  144. 'items' => []
  145. ];
  146. foreach ($actionItems as $actionItem) {
  147. $dayItems['items'][] = self::actionFormat($actionItem, $objectNames);
  148. }
  149. $data[] = $dayItems;
  150. }
  151. return $data;
  152. }
  153. /**
  154. * @param Collection $actions
  155. * @return array
  156. */
  157. protected static function objectNamesGroupByType(Collection $actions): array
  158. {
  159. $groupActions = $actions->groupBy("object_type");
  160. $objectNames = [];
  161. foreach ($groupActions as $group => $items) {
  162. $objectType = ActionObjectType::tryFrom($group);
  163. $actionObjectBuilder= $objectType?->modelBuilder();
  164. if (! $actionObjectBuilder) {
  165. continue;
  166. }
  167. $objectNames[$group] = $actionObjectBuilder
  168. ->whereIn("id", $items->pluck("object_id")->unique()->toArray())
  169. ->pluck($objectType->nameField(), "id");
  170. }
  171. return $objectNames;
  172. }
  173. public static function actionWithHistory(ActionObjectType $actionObjectType, string $objectId): array
  174. {
  175. $actions = Action::query()
  176. ->with(['histories', 'createdBy'])
  177. ->where("object_type", $actionObjectType->value)
  178. ->where("object_id", $objectId)
  179. ->orderBy("created_at")
  180. ->get();
  181. $objectNames = self::objectNamesGroupByType($actions);
  182. self::eagerLoadingHistoryConverters($actionObjectType, $actions);
  183. $items = [];
  184. foreach ($actions as $action) {
  185. $item = self::actionFormat($action->toArray(), $objectNames);
  186. $item['histories'] = self::formatHistories($actionObjectType, $action->histories);
  187. $items[] = $item;
  188. }
  189. return $items;
  190. }
  191. public static function eagerLoadingHistoryConverters(ActionObjectType $actionObjectType, Collection $actions)
  192. {
  193. $detector = $actionObjectType->detectorClassName();
  194. $converters = [];
  195. foreach(call_user_func([$detector, "converters"]) as $key => $converter) {
  196. if (! $converter->isEagerLoading()) {
  197. continue;
  198. }
  199. $converters[$key] = $converter;
  200. }
  201. if (! $converters) {
  202. return;
  203. }
  204. $arrayFields = call_user_func([$detector, "arrayFields"]);
  205. $converterFields = array_keys($converters);
  206. $values = [];
  207. $pushValue = function (string $field, $fieldValue) use (&$values) {
  208. if (! $fieldValue) {
  209. return;
  210. }
  211. if (is_array($fieldValue)) {
  212. foreach ($fieldValue as $v) {
  213. if (in_array($v, $values[$field] ?? [])) {
  214. continue;
  215. }
  216. $values[$field][] = $v;
  217. }
  218. } else {
  219. if (! in_array($fieldValue, $values[$field] ?? [])) {
  220. $values[$field][] = $fieldValue;
  221. }
  222. }
  223. };
  224. foreach ($actions as $action) {
  225. foreach ($action->histories as $history) {
  226. if (! in_array($history->field, $converterFields)) {
  227. continue;
  228. }
  229. $old = in_array($history->field, $arrayFields) ? json_decode($history->old, true) : $history->old;
  230. $new = in_array($history->field, $arrayFields) ? json_decode($history->new, true) : $history->new;
  231. $pushValue($history->field, $old);
  232. $pushValue($history->field, $new);
  233. }
  234. }
  235. foreach ($values as $key => $value) {
  236. call_user_func([$converters[$key], "eagerLoad"], $value);
  237. }
  238. }
  239. public static function formatHistories(ActionObjectType $actionObjectType, Collection $histories): array
  240. {
  241. $detector = $actionObjectType->detectorClassName();
  242. $items = [];
  243. foreach ($histories as $history) {
  244. $labelKey = sprintf("fields.%s", $history->field);
  245. $item = [
  246. 'field' => $history->field,
  247. 'field_label' => app('translator')->has($labelKey) ? __($labelKey) : $history->field,
  248. 'new' => self::coverFieldValue($detector, $history->field, $history->new),
  249. 'old' => self::coverFieldValue($detector, $history->field, $history->old),
  250. 'diff' => (string)$history->diff,
  251. ];
  252. $items[] = $item;
  253. }
  254. return $items;
  255. }
  256. protected static function coverFieldValue(string $detector, string $field, string $value): mixed
  257. {
  258. if (! $detector) {
  259. return $value;
  260. }
  261. $converter = call_user_func([$detector, "converter"], $field);
  262. return $converter ? $converter->handle($value) : $value;
  263. }
  264. }