ActionRepository.php 10 KB

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