ActionRepository.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 objectEmailActions(ActionObjectType $actionObjectType, string $objectId, int $lastActionId): array
  136. {
  137. $actions = Action::query()
  138. ->with(['createdBy'])
  139. ->where("object_type", $actionObjectType->value)
  140. ->where("object_id", $objectId)
  141. ->where("id", "<=", $lastActionId)
  142. ->orderByDesc("created_at")
  143. ->limit(5)
  144. ->get();
  145. return self::actionsFormat($actions);
  146. }
  147. protected static function actionsFormat(Collection $actions): array
  148. {
  149. $objectNames = self::objectNamesGroupByType($actions);
  150. $items = [];
  151. foreach ($actions as $action) {
  152. $items[] = self::actionFormat($action->toArray(), $objectNames);
  153. }
  154. return $items;
  155. }
  156. public static function actionFormat(array $action, array $objectNames): array
  157. {
  158. $labelKey = sprintf("action-labels.label.%s", $action['action']);
  159. $objectLabelKey = sprintf("action-labels.object_type.%s", $action['object_type']);
  160. $cratedAt = Carbon::parse($action['created_at'])->timezone('Asia/Shanghai');
  161. $imgService=new ImageUrlService();
  162. //存在评论时才会执行获取图片路径
  163. if(isset($action['comment'])){
  164. $action['comment']=$imgService->getImageUrl($action['comment']);
  165. }
  166. return [
  167. 'id' => $action['id'],
  168. 'time' => $cratedAt->toTimeString(),
  169. 'created_at' => $cratedAt->toDateTimeString(),
  170. 'created_by' => [
  171. 'id' => $action['created_by']['id'],
  172. 'name' => $action['created_by']['name'],
  173. 'username' => $action['created_by']['username'],
  174. ],
  175. 'action_label' => app('translator')->has($labelKey) ? __($labelKey) : $action['action'],
  176. 'object_label' => app('translator')->has($objectLabelKey) ? __($objectLabelKey) : $action['object_type'],
  177. 'object_id' => $action['object_id'],
  178. 'object_type' => $action['object_type'],
  179. 'object_name' => data_get($objectNames, sprintf("%s.%d", $action['object_type'], $action['object_id'])),
  180. 'comment' => $action['comment'],
  181. ];
  182. }
  183. public static function dynamic(Project $project, array $filter = [])
  184. {
  185. $actions = Action::query()->filter($filter)
  186. ->where("project_id", $project->id)
  187. ->with(['createdBy'])
  188. ->selectRaw("*, date_format(created_at, '%Y-%m-%d') as created_date")
  189. ->orderBy("created_at")
  190. ->get();
  191. $objectNames = self::objectNamesGroupByType($actions);
  192. $items = $actions->groupBy("created_date")->toArray();
  193. krsort($items);
  194. $data = [];
  195. foreach ($items as $day => $actionItems) {
  196. $dayItems = [
  197. 'date' => $day,
  198. 'items' => []
  199. ];
  200. foreach ($actionItems as $actionItem) {
  201. $dayItems['items'][] = self::actionFormat($actionItem, $objectNames);
  202. }
  203. $data[] = $dayItems;
  204. }
  205. return $data;
  206. }
  207. /**
  208. * @param Collection $actions
  209. * @return array
  210. */
  211. protected static function objectNamesGroupByType(Collection $actions): array
  212. {
  213. $groupActions = $actions->groupBy("object_type");
  214. $objectNames = [];
  215. foreach ($groupActions as $group => $items) {
  216. $objectType = ActionObjectType::tryFrom($group);
  217. $actionObjectBuilder= $objectType?->modelBuilder();
  218. if (! $actionObjectBuilder) {
  219. continue;
  220. }
  221. $objectNames[$group] = $actionObjectBuilder
  222. ->whereIn("id", $items->pluck("object_id")->unique()->toArray())
  223. ->pluck($objectType->nameField(), "id");
  224. }
  225. return $objectNames;
  226. }
  227. public static function actionWithHistory(ActionObjectType $actionObjectType, string $objectId): array
  228. {
  229. $actions = Action::query()
  230. ->with(['histories', 'createdBy'])
  231. ->where("object_type", $actionObjectType->value)
  232. ->where("object_id", $objectId)
  233. ->orderBy("created_at")
  234. ->get();
  235. $objectNames = self::objectNamesGroupByType($actions);
  236. self::eagerLoadingHistoryConverters($actionObjectType, $actions);
  237. $items = [];
  238. foreach ($actions as $action) {
  239. $item = self::actionFormat($action->toArray(), $objectNames);
  240. $item['histories'] = self::formatHistories($actionObjectType, $action->histories);
  241. $items[] = $item;
  242. }
  243. return $items;
  244. }
  245. public static function eagerLoadingHistoryConverters(ActionObjectType $actionObjectType, Collection $actions)
  246. {
  247. $detector = $actionObjectType->detectorClassName();
  248. $converters = [];
  249. foreach(call_user_func([$detector, "converters"]) as $key => $converter) {
  250. if (! $converter->isEagerLoading()) {
  251. continue;
  252. }
  253. $converters[$key] = $converter;
  254. }
  255. if (! $converters) {
  256. return;
  257. }
  258. $arrayFields = call_user_func([$detector, "arrayFields"]);
  259. $converterFields = array_keys($converters);
  260. $values = [];
  261. $pushValue = function (string $field, $fieldValue) use (&$values) {
  262. if (! $fieldValue) {
  263. return;
  264. }
  265. if (is_array($fieldValue)) {
  266. foreach ($fieldValue as $v) {
  267. if (in_array($v, $values[$field] ?? [])) {
  268. continue;
  269. }
  270. $values[$field][] = $v;
  271. }
  272. } else {
  273. if (! in_array($fieldValue, $values[$field] ?? [])) {
  274. $values[$field][] = $fieldValue;
  275. }
  276. }
  277. };
  278. foreach ($actions as $action) {
  279. foreach ($action->histories as $history) {
  280. if (! in_array($history->field, $converterFields)) {
  281. continue;
  282. }
  283. $old = in_array($history->field, $arrayFields) ? json_decode($history->old, true) : $history->old;
  284. $new = in_array($history->field, $arrayFields) ? json_decode($history->new, true) : $history->new;
  285. $pushValue($history->field, $old);
  286. $pushValue($history->field, $new);
  287. }
  288. }
  289. foreach ($values as $key => $value) {
  290. call_user_func([$converters[$key], "eagerLoad"], $value);
  291. }
  292. }
  293. public static function formatHistories(ActionObjectType $actionObjectType, Collection $histories): array
  294. {
  295. $detector = $actionObjectType->detectorClassName();
  296. $items = [];
  297. foreach ($histories as $history) {
  298. $labelKey = sprintf("fields.%s", $history->field);
  299. $item = [
  300. 'field' => $history->field,
  301. 'field_label' => app('translator')->has($labelKey) ? __($labelKey) : $history->field,
  302. 'new' => self::coverFieldValue($detector, $history->field ?? '', $history->new ?? ''),
  303. 'old' => self::coverFieldValue($detector, $history->field ?? '', $history->old ?? ''),
  304. 'diff' => (string)$history->diff,
  305. ];
  306. $items[] = $item;
  307. }
  308. return $items;
  309. }
  310. protected static function coverFieldValue(string $detector, string $field, string $value): mixed
  311. {
  312. if (! $detector) {
  313. return $value;
  314. }
  315. $converter = call_user_func([$detector, "converter"], $field);
  316. return $converter ? $converter->handle($value) : $value;
  317. }
  318. }