ActionRepository.php 15 KB

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