ActionRepository.php 9.9 KB

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