ActionRepository.php 13 KB

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