Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ConfigurationPropertiesScan(basePackages = {
Expand All @@ -21,6 +22,7 @@
"com.aura"
})
@EnableCaching
@EnableScheduling
@EnableJpaRepositories(basePackages = {
"com.fitnessapp.backend.user.repository",
"com.fitnessapp.backend.recipe.repository",
Expand All @@ -31,6 +33,7 @@
"com.fitnessapp.backend.repository",
"com.fitnessapp.backend.goals.repository",
"com.fitnessapp.backend.weight.repository",
"com.fitnessapp.backend.squad.repository",
"com.aura.repository"
})
public class FitnessAppApplication {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ public enum ErrorCode {
MEAL_NOT_FOUND(2002, "Meal not found", HttpStatus.NOT_FOUND),
PROFILE_NOT_FOUND(2003, "User profile not found", HttpStatus.NOT_FOUND),

// Squad errors (2010-2019) — see com.fitnessapp.backend.squad
SQUAD_NOT_FOUND(2010, "Squad not found", HttpStatus.NOT_FOUND),
SQUAD_FULL(2011, "Squad has reached the 10-member limit", HttpStatus.CONFLICT),
SQUAD_LIMIT_REACHED(2012, "You are already in the maximum number of squads", HttpStatus.CONFLICT),
SQUAD_INVITE_CODE_INVALID(2013, "Invite code is invalid or expired", HttpStatus.NOT_FOUND),
SQUAD_ACCESS_DENIED(2014, "You are not a member of this squad", HttpStatus.FORBIDDEN),
SQUAD_ALREADY_MEMBER(2015, "You are already a member of this squad", HttpStatus.CONFLICT),
KUDOS_FORBIDDEN(2016, "You cannot give kudos to this meal", HttpStatus.FORBIDDEN),
KUDOS_SELF_FORBIDDEN(2017, "You cannot give kudos to your own meal", HttpStatus.BAD_REQUEST),

// AI/Vision errors (3xxx)
AI_SERVICE_UNAVAILABLE(3001, "AI service temporarily unavailable", HttpStatus.SERVICE_UNAVAILABLE),
AI_RECOGNITION_FAILED(3002, "Food recognition failed", HttpStatus.BAD_REQUEST),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.fitnessapp.backend.auth.AuthenticationException;
import com.fitnessapp.backend.nutrition.exception.FoodRecognitionException;
import com.fitnessapp.backend.recommendation.exception.RecommendationException;
import com.fitnessapp.backend.squad.SquadException;

import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -75,6 +76,20 @@ public ResponseEntity<ApiEnvelope<Void>> handleEmbeddingException(
return ResponseEntity.status(errorCode.getHttpStatus()).body(response);
}

// ========== Squad Exceptions ==========

@ExceptionHandler(SquadException.class)
public ResponseEntity<ApiEnvelope<Void>> handleSquadException(
SquadException ex,
HttpServletRequest request
) {
ErrorCode errorCode = ex.getErrorCode();
log.warn("Squad error [{}]: {}", errorCode.getCode(), ex.getMessage());

ApiEnvelope<Void> response = ApiEnvelope.error(errorCode, ex.getMessage(), request.getRequestURI());
return ResponseEntity.status(errorCode.getHttpStatus()).body(response);
}

// ========== Entity Exceptions ==========

@ExceptionHandler(EntityNotFoundException.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,24 @@ interface MealLogLeaderboardRow {
OffsetDateTime getLastLog();
}

// ========== Squads / leaderboard helpers ==========

long countByUserIdAndConsumedAtAfter(UUID userId, OffsetDateTime since);

@Query("SELECT COUNT(DISTINCT FUNCTION('DATE', m.consumedAt)) FROM MealLog m WHERE m.userId = :userId AND m.consumedAt >= :since")
long countDistinctDaysByUserSince(@Param("userId") UUID userId, @Param("since") OffsetDateTime since);

/** Returns true if at least one meal log exists for {@code userId} in the half-open window. */
@Query("""
SELECT COUNT(m) > 0 FROM MealLog m
WHERE m.userId = :userId
AND m.consumedAt >= :start
AND m.consumedAt < :end
""")
boolean existsLogInRange(@Param("userId") UUID userId,
@Param("start") OffsetDateTime start,
@Param("end") OffsetDateTime end);

interface DailyNutritionSummary {
LocalDate getDate();
Long getMealCount();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.fitnessapp.backend.squad;

import com.fitnessapp.backend.api.common.ErrorCode;
import lombok.Getter;

/**
* Domain exception for the Squads feature. Carries an {@link ErrorCode} so
* {@code GlobalExceptionHandler} can map it to a consistent {@code ApiEnvelope}
* response with the correct HTTP status.
*/
@Getter
public class SquadException extends RuntimeException {

private final ErrorCode errorCode;

public SquadException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}

public SquadException(ErrorCode errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.fitnessapp.backend.squad.controller;

import com.fitnessapp.backend.security.CurrentUser;
import com.fitnessapp.backend.squad.dto.KudosResponse;
import com.fitnessapp.backend.squad.service.KudosService;

import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/meal-logs/{mealLogId}/kudos")
@RequiredArgsConstructor
public class KudosController {

private final CurrentUser currentUser;
private final KudosService kudosService;

/** Toggle kudos. Body-less — server flips the existing state. */
@PostMapping
public ResponseEntity<KudosResponse> toggle(@PathVariable Long mealLogId) {
UUID userId = currentUser.requireUserId();
return ResponseEntity.ok(kudosService.toggle(userId, mealLogId));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.fitnessapp.backend.squad.controller;

import com.fitnessapp.backend.security.CurrentUser;
import com.fitnessapp.backend.squad.dto.CreateSquadRequest;
import com.fitnessapp.backend.squad.dto.JoinSquadRequest;
import com.fitnessapp.backend.squad.dto.LeaderboardEntry;
import com.fitnessapp.backend.squad.dto.SquadDetailResponse;
import com.fitnessapp.backend.squad.dto.SquadResponse;
import com.fitnessapp.backend.squad.service.SquadService;

import jakarta.validation.Valid;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/squads")
@Validated
@RequiredArgsConstructor
public class SquadController {

private final CurrentUser currentUser;
private final SquadService squadService;

@PostMapping
public ResponseEntity<SquadResponse> create(@Valid @RequestBody CreateSquadRequest request) {
UUID userId = currentUser.requireUserId();
SquadResponse response = squadService.create(userId, request.name(), request.emoji(), request.timezone());
return ResponseEntity.ok(response);
}

@PostMapping("/join")
public ResponseEntity<SquadResponse> join(@Valid @RequestBody JoinSquadRequest request) {
UUID userId = currentUser.requireUserId();
SquadResponse response = squadService.joinByCode(userId, request.inviteCode());
return ResponseEntity.ok(response);
}

@GetMapping
public ResponseEntity<List<SquadResponse>> list() {
UUID userId = currentUser.requireUserId();
return ResponseEntity.ok(squadService.listForUser(userId));
}

@GetMapping("/{squadId}")
public ResponseEntity<SquadDetailResponse> detail(@PathVariable UUID squadId) {
UUID userId = currentUser.requireUserId();
return ResponseEntity.ok(squadService.getDetail(userId, squadId));
}

@PostMapping("/{squadId}/leave")
public ResponseEntity<Void> leave(@PathVariable UUID squadId) {
UUID userId = currentUser.requireUserId();
squadService.leave(userId, squadId);
return ResponseEntity.noContent().build();
}

@DeleteMapping("/{squadId}/members/{targetUserId}")
public ResponseEntity<Void> removeMember(@PathVariable UUID squadId, @PathVariable UUID targetUserId) {
UUID userId = currentUser.requireUserId();
squadService.removeMember(userId, squadId, targetUserId);
return ResponseEntity.noContent().build();
}

@GetMapping("/{squadId}/leaderboard")
public ResponseEntity<List<LeaderboardEntry>> leaderboard(@PathVariable UUID squadId) {
UUID userId = currentUser.requireUserId();
return ResponseEntity.ok(squadService.leaderboard(userId, squadId));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.fitnessapp.backend.squad.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public record CreateSquadRequest(
@NotBlank @Size(max = 30) String name,
@NotBlank @Size(max = 8) String emoji,
@Size(max = 64) String timezone
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.fitnessapp.backend.squad.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public record JoinSquadRequest(
@NotBlank @Size(min = 6, max = 6) String inviteCode
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.fitnessapp.backend.squad.dto;

public record KudosResponse(
long mealLogId,
long kudosCount,
boolean kudoed
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.fitnessapp.backend.squad.dto;

import java.util.UUID;

public record LeaderboardEntry(
UUID userId,
int rank,
long mealsLogged,
long daysActive,
boolean warmingUp
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.fitnessapp.backend.squad.dto;

import java.util.List;

public record SquadDetailResponse(
SquadResponse squad,
List<SquadMemberSummary> members
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.fitnessapp.backend.squad.dto;

import com.fitnessapp.backend.squad.entity.Squad;
import com.fitnessapp.backend.squad.entity.SquadMember;
import java.util.List;

public final class SquadMapper {

private SquadMapper() {}

public static SquadResponse toResponse(Squad s, long memberCount) {
return new SquadResponse(
s.getId(),
s.getName(),
s.getEmoji(),
s.getInviteCode(),
s.getOwnerUserId(),
(int) memberCount,
s.getCurrentStreak() == null ? 0 : s.getCurrentStreak(),
s.getLongestStreak() == null ? 0 : s.getLongestStreak(),
s.getLastActiveDay(),
s.getTimezone(),
s.getCreatedAt()
);
}

public static SquadMemberSummary toMemberSummary(SquadMember m) {
return new SquadMemberSummary(m.getUserId(), m.getRole(), m.getJoinedAt());
}

public static List<SquadMemberSummary> toMemberSummaries(List<SquadMember> members) {
return members.stream().map(SquadMapper::toMemberSummary).toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.fitnessapp.backend.squad.dto;

import java.time.OffsetDateTime;
import java.util.UUID;

public record SquadMemberSummary(
UUID userId,
String role,
OffsetDateTime joinedAt
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.fitnessapp.backend.squad.dto;

import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.UUID;

public record SquadResponse(
UUID id,
String name,
String emoji,
String inviteCode,
UUID ownerUserId,
int memberCount,
int currentStreak,
int longestStreak,
LocalDate lastActiveDay,
String timezone,
OffsetDateTime createdAt
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.fitnessapp.backend.squad.entity;

import jakarta.persistence.*;
import java.time.OffsetDateTime;
import java.util.UUID;
import lombok.*;

@Entity
@Table(name = "meal_log_kudos")
@IdClass(MealLogKudosId.class)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MealLogKudos {

@Id
@Column(name = "meal_log_id", nullable = false)
private Long mealLogId;

@Id
@Column(name = "user_id", nullable = false, columnDefinition = "uuid")
private UUID userId;

@Column(name = "created_at", insertable = false, updatable = false)
private OffsetDateTime createdAt;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.fitnessapp.backend.squad.entity;

import java.io.Serializable;
import java.util.Objects;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
public class MealLogKudosId implements Serializable {
private Long mealLogId;
private UUID userId;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MealLogKudosId that)) return false;
return Objects.equals(mealLogId, that.mealLogId) && Objects.equals(userId, that.userId);
}

@Override
public int hashCode() {
return Objects.hash(mealLogId, userId);
}
}
Loading
Loading