public function provinces($userToken, UserTokenHandler $tokenHandler) { $user = $tokenHandler->getUserFromToken($userToken, true); $localChallenge = Challenge::selectRaw('challenges.*')->join('pins', 'challenges.pin_id', '=', 'pins.id')->join('provinces', 'provinces.id', '=', 'pins.province_id')->where('provinces.id', $user['province_id'])->where('challenges.starts_at', '<=', $now = Carbon::now())->where('challenges.ends_at', '>=', $now)->first(); $totalOwnCount = Pin::where('province_id', $user['province_id'])->count(); $ownDoneCount = OwnVisit::selectRaw('count(distinct pin_id) as count')->where('user_id', $user['id'])->first()->count; $active = Visit::where('user_id', $user['id'])->whereNull('finished_at')->first(); $active = $active ? $active->province_id : null; $provinces = Province::selectRaw('provinces.*, count(distinct visit_pin.pin_id) as done_count, count(distinct pins.id) as total_count')->leftJoin('visits', function ($clause) use($user) { return $clause->on('visits.province_id', '=', 'provinces.id')->where('visits.user_id', '=', $user['id'])->whereNotNull('visits.finished_at'); })->leftJoin('visit_pin', 'visit_pin.visit_id', '=', 'visits.id')->leftJoin('pins', 'pins.province_id', '=', 'provinces.id')->groupBy('provinces.id')->get(); $provinces = $provinces->toArray(); foreach ($provinces as $key => $province) { if ($province['id'] == $user['province_id']) { $province['is_for_user'] = true; $province['total_count'] = $totalOwnCount; $province['done_count'] = $ownDoneCount; } else { $province['is_for_user'] = false; } $province['progress'] = $province['total_count'] === 0 ? 0 : $province['done_count'] / $province['total_count']; $provinces[$key] = $province; } return response()->json(['challenge' => $localChallenge->toArray(), 'active' => $active, 'provinces' => $provinces]); }
protected function createDailyChallenge() { $province = \Tajrish\Models\Province::where('name', 'تهران')->firstOrFail(); $pin = \Tajrish\Models\Pin::where('province_id', $province->id)->firstOrFail(); \Tajrish\Models\Challenge::create(['title' => 'بازدید از عمارت مسعودیه در جمعه', 'description' => 'با مشاهده عمارت مسعودیه در روز جمعه جایزه بگیرید.', 'pin_id' => $pin->id, 'starts_at' => \Carbon\Carbon::now(), 'ends_at' => \Carbon\Carbon::now()->addDay()]); }