*/ use HasFactory; /** @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** @return BelongsTo */ public function folder(): BelongsTo { return $this->belongsTo(Folder::class); } /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'due_date' => 'date', 'completed_at' => 'datetime', 'status' => TodoStatus::class, ]; } /** * Scope the query to todos owned by the given user. * * @param Builder $query * @return Builder */ public function scopeForUser(Builder $query, User|int $user): Builder { return $query->where('user_id', $user instanceof User ? $user->id : $user); } /** * Scope the query to todos that have not been completed. * * @param Builder $query * @return Builder */ public function scopeIncomplete(Builder $query): Builder { return $query->whereNull('completed_at'); } /** * Scope the query to todos that have been completed. * * @param Builder $query * @return Builder */ public function scopeCompleted(Builder $query): Builder { return $query->whereNotNull('completed_at'); } /** * Scope the query to todos that still need attention: not completed * and not cancelled or deferred. * * @param Builder $query * @return Builder */ public function scopeActive(Builder $query): Builder { return $query->incomplete()->whereNotIn('status', [ TodoStatus::Cancelled->value, TodoStatus::Deferred->value, TodoStatus::Completed->value, ]); } /** * Scope the query to active todos whose due date has already passed. * * @param Builder $query * @return Builder */ public function scopeOverdue(Builder $query): Builder { return $query->active()->whereDate('due_date', '<', now()); } /** * Scope the query to active todos due today. * * @param Builder $query * @return Builder */ public function scopeDueToday(Builder $query): Builder { return $query->active()->whereDate('due_date', today()); } public function scopePriority(Builder $query): Builder { return $query ->orderByRaw('completed_at IS NOT NULL') ->orderByRaw('position IS NULL') ->orderBy('position') ->orderByDesc('id'); } /** * Get the position to assign to a new todo so it appears at the top of the * priority order for the given user. */ public static function nextPositionFor(User|int $user): int { $min = static::query()->forUser($user)->min('position'); return $min === null ? 1 : $min - 1; } /** * Get the number of days between creation and completion, or null when the * todo has not been completed. */ public function daysToComplete(): ?int { return $this->completed_at === null ? null : $this->created_at->diffInDays($this->completed_at); } }