ProjectMembersController.php 2.49 KB
<?php


namespace App\Http\Container\AppSection\Controllers;


use App\Helpers\JsonResource;
use App\Http\Container\AppSection\Requests\ProjectMemberUpdateRequest;
use App\Models\Pivots\ProjectMemberPivot;
use App\Models\Pivots\UserProjectPivot;
use App\Models\User;
use Hikoon\LaravelApi\Support\ApiController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectMembersController extends ApiController
{

    public function index(Request $request): JsonResponse
    {
        $id   = $request->get('id');
        $size = $request->get('size', 20);
        $ids  = ProjectMemberPivot::query()
            ->where(['project_id' => $id])
            ->whereIn('status', [1, 3])
            ->orderByDesc('is_top')->orderByDesc('created_at')
            ->pluck('user_id')
            ->toArray();
        $data = User::query()->whereIn('id', $ids)
            ->with(['authTags:id,name', 'userTag:id,name,icon,frame'])
            ->select(['id', 'avatar', 'nick_name', 'identity', 'user_tag_id'])
            ->addSelect([
                'member_id' => ProjectMemberPivot::query()->select('id')->where('project_id', $id)->whereColumn('project_has_members.user_id', 'users.id')->latest()->limit(1),
                'is_top'    => ProjectMemberPivot::query()->select('is_top')->where('project_id', $id)->whereColumn('project_has_members.user_id', 'users.id')->latest()->limit(1)

            ])
            ->where('status', 1)
            ->orderByDesc('is_top')
            ->orderByRaw("FIELD(id, " . implode(',', $ids) . ")")
            ->paginate($size);
        foreach ($data as $item) {
            $item['is_master'] = UserProjectPivot::query()->where(['project_id' => $id, 'user_id' => Auth::id()])->exists();

        }
        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }


    public function update(ProjectMemberUpdateRequest $request): JsonResponse
    {
        $member = ProjectMemberPivot::query()->find($request->member);
        $member->update($request->safe()->toArray());
        return JsonResource::success(JsonResource::UPDATE_SUCCESS);
    }

    /**
     * @param \App\Models\UserDynamic $dynamic
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request): JsonResponse
    {
        $member = ProjectMemberPivot::query()->find($request->member);
        $member->delete();
        return JsonResource::success(JsonResource::DELETE_SUCCESS);
    }

}