ActionRepository.php 9.3 KB

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