add habit back
This commit is contained in:
56
app/Http/Controllers/HabitController.php
Normal file
56
app/Http/Controllers/HabitController.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Habit;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class HabitController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json(Habit::all()->toArray());
|
||||
}
|
||||
|
||||
public function get(int $id): JsonResponse
|
||||
{
|
||||
return response()->json(Habit::find($id)->toArray());
|
||||
}
|
||||
|
||||
public function create(Request $request): JsonResponse
|
||||
{
|
||||
$habit = Habit::create([
|
||||
'name' => $request->get('name'),
|
||||
'description' => $request->get('description'),
|
||||
'target_count' => $request->get('targetCount'),
|
||||
'current_count' => 0
|
||||
]);
|
||||
|
||||
return response()->json($habit->toArray());
|
||||
}
|
||||
|
||||
public function currentCountUpdate(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$habit = Habit::find($id);
|
||||
$completions = $habit->completions ?? [];
|
||||
$date = Carbon::now()->startOfDay()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
|
||||
|
||||
if (in_array($date, $completions)) {
|
||||
return response()->json(['message' => 'Привычка уже отмечена сегодня'], Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
$habit->current_count += 1;
|
||||
$completions[] = Carbon::now()->startOfDay()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
|
||||
$habit->completions = $completions;
|
||||
|
||||
if ($habit->current_count >= $habit->target_count) {
|
||||
$habit->is_completed = true;
|
||||
}
|
||||
$habit->save();
|
||||
|
||||
return response()->json($habit->toArray());
|
||||
}
|
||||
}
|
||||
14
app/Models/Habit.php
Normal file
14
app/Models/Habit.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Habit extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'completions' => 'array'
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user