ActionRepository.php 9.8 KB

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