ActionRepository.php 10 KB

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