ActionRepository.php 14 KB

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