ActionRepository.php 15 KB

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