ActionRepository.php 11 KB

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