ActionRepository.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. /**
  227. * @param Collection $actions
  228. * @return array
  229. */
  230. protected static function objectNamesGroupByType(Collection $actions): array
  231. {
  232. $groupActions = $actions->groupBy("object_type");
  233. $objectNames = [];
  234. foreach ($groupActions as $group => $items) {
  235. $objectType = ActionObjectType::tryFrom($group);
  236. $actionObjectBuilder= $objectType?->modelBuilder();
  237. if (! $actionObjectBuilder) {
  238. continue;
  239. }
  240. $objectNames[$group] = $actionObjectBuilder
  241. ->whereIn("id", $items->pluck("object_id")->unique()->toArray())
  242. ->pluck($objectType->nameField(), "id");
  243. }
  244. return $objectNames;
  245. }
  246. public static function actionWithHistory(ActionObjectType $actionObjectType, string $objectId): array
  247. {
  248. $actions = Action::query()
  249. ->with(['histories', 'createdBy'])
  250. ->where("object_type", $actionObjectType->value)
  251. ->where("object_id", $objectId)
  252. ->orderBy("created_at")
  253. ->get();
  254. $objectNames = self::objectNamesGroupByType($actions);
  255. self::eagerLoadingHistoryConverters($actionObjectType, $actions);
  256. $items = [];
  257. foreach ($actions as $action) {
  258. $item = self::actionFormat($action->toArray(), $objectNames);
  259. $item['histories'] = self::formatHistories($actionObjectType, $action->histories);
  260. $items[] = $item;
  261. }
  262. return $items;
  263. }
  264. public static function eagerLoadingHistoryConverters(ActionObjectType $actionObjectType, Collection $actions)
  265. {
  266. $detector = $actionObjectType->detectorClassName();
  267. $converters = [];
  268. foreach(call_user_func([$detector, "converters"]) as $key => $converter) {
  269. if (! $converter->isEagerLoading()) {
  270. continue;
  271. }
  272. $converters[$key] = $converter;
  273. }
  274. if (! $converters) {
  275. return;
  276. }
  277. $arrayFields = call_user_func([$detector, "arrayFields"]);
  278. $converterFields = array_keys($converters);
  279. $values = [];
  280. $pushValue = function (string $field, $fieldValue) use (&$values) {
  281. if (! $fieldValue) {
  282. return;
  283. }
  284. if (is_array($fieldValue)) {
  285. foreach ($fieldValue as $v) {
  286. if (in_array($v, $values[$field] ?? [])) {
  287. continue;
  288. }
  289. $values[$field][] = $v;
  290. }
  291. } else {
  292. if (! in_array($fieldValue, $values[$field] ?? [])) {
  293. $values[$field][] = $fieldValue;
  294. }
  295. }
  296. };
  297. foreach ($actions as $action) {
  298. foreach ($action->histories as $history) {
  299. if (! in_array($history->field, $converterFields)) {
  300. continue;
  301. }
  302. $old = in_array($history->field, $arrayFields) ? json_decode($history->old, true) : $history->old;
  303. $new = in_array($history->field, $arrayFields) ? json_decode($history->new, true) : $history->new;
  304. $pushValue($history->field, $old);
  305. $pushValue($history->field, $new);
  306. }
  307. }
  308. foreach ($values as $key => $value) {
  309. call_user_func([$converters[$key], "eagerLoad"], $value);
  310. }
  311. }
  312. public static function formatHistories(ActionObjectType $actionObjectType, Collection $histories): array
  313. {
  314. $detector = $actionObjectType->detectorClassName();
  315. $items = [];
  316. foreach ($histories as $history) {
  317. $labelKey = sprintf("fields.%s", $history->field);
  318. $item = [
  319. 'field' => $history->field,
  320. 'field_label' => app('translator')->has($labelKey) ? __($labelKey) : $history->field,
  321. 'new' => self::coverFieldValue($detector, $history->field ?? '', $history->new ?? ''),
  322. 'old' => self::coverFieldValue($detector, $history->field ?? '', $history->old ?? ''),
  323. 'diff' => (string)$history->diff,
  324. ];
  325. $items[] = $item;
  326. }
  327. return $items;
  328. }
  329. protected static function coverFieldValue(string $detector, string $field, string $value): mixed
  330. {
  331. if (! $detector) {
  332. return $value;
  333. }
  334. $converter = call_user_func([$detector, "converter"], $field);
  335. return $converter ? $converter->handle($value) : $value;
  336. }
  337. }