diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..201f486f0d3274dcfd49ee6c6e4b9dcec3ac6903 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +.vs/ +bin/ +obj/ +*.user +*.lock.json +*.suo +*.userosscache +*.sln.docstates +out/ +[Dd]ebug/ +[Rr]elease/ +appsettings.Development.json +*.db-shm +*.db-wal +bridge_log.txt +gemini_profile_bridge/ +*.sqlite-shm +*.sqlite-wal +# Ignore SQLite database files to avoid checking them in +taskflow.db +/app/data/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f26fe95994fe9a1c89aa5728880a6e80287b7ab5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,63 @@ +# Stage 1: Build .NET 10 API +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +WORKDIR /src + +# Copy csproj files and restore dependencies +COPY ["FlowAPI/FlowAPI.csproj", "FlowAPI/"] +COPY ["FlowAPI.Application/FlowAPI.Application.csproj", "FlowAPI.Application/"] +COPY ["FlowAPI.Domain/FlowAPI.Domain.csproj", "FlowAPI.Domain/"] +COPY ["FlowAPI.Infrastructure/FlowAPI.Infrastructure.csproj", "FlowAPI.Infrastructure/"] +RUN dotnet restore "FlowAPI/FlowAPI.csproj" + +# Copy everything else and build +COPY . . +WORKDIR "/src/FlowAPI" +RUN dotnet publish "FlowAPI.csproj" -c Release -o /app/publish /p:UseAppHost=false + +# Stage 2: Runtime +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final +WORKDIR /app +EXPOSE 8080 +EXPOSE 8081 + +# Install Python, pip, and system dependencies for Camoufox (Playwright/Firefox) +RUN apt-get update && apt-get install -y \ + python3 \ + python3-pip \ + python3-venv \ + curl \ + libgtk-3-0 \ + libasound2 \ + libdbus-1-3 \ + libx11-xcb1 \ + libxcomposite1 \ + libxdamage1 \ + libxrandr2 \ + libxtst6 \ + libnss3 \ + libatk1.0-0 \ + libatk-bridge2.0-0 \ + libdrm2 \ + libgbm1 \ + libxkbcommon0 \ + libpango-1.0-0 \ + libcairo2 \ + && rm -rf /var/lib/apt/lists/* + +# Set up python virtual environment to install packages cleanly +RUN python3 -m venv /opt/venv +ENV PATH="/opt/venv/bin:$PATH" + +# Install camoufox python library and its dependencies +RUN pip3 install --no-cache-dir camoufox +# Pre-download Camoufox/Playwright browser engines so they are ready +RUN python3 -m camoufox fetch + +# Copy published .NET app +COPY --from=build /app/publish . + +# Explicitly copy the python bridge script to ensure it is in the run directory +COPY --from=build /src/FlowAPI/gemini_bridge.py . + +# Set entrypoint +ENTRYPOINT ["dotnet", "FlowAPI.dll"] diff --git a/FlowAPI.Application/DTOs/AI/AIDtos.cs b/FlowAPI.Application/DTOs/AI/AIDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..f9a84f97808fc9692e37204e7be4b629be49a0cc --- /dev/null +++ b/FlowAPI.Application/DTOs/AI/AIDtos.cs @@ -0,0 +1,36 @@ +using FlowAPI.Application.DTOs.TaskNode; +using FlowAPI.Application.DTOs.Edge; +using FlowAPI.Application.DTOs.Graph; + +namespace FlowAPI.Application.DTOs.AI +{ + public class GenerateAlternativeRequestDto + { + public Guid GraphId { get; set; } + public Guid FailedNodeId { get; set; } + } + + public class AIPathResponseDto + { + public List SuggestedNodes { get; set; } = new(); + public List SuggestedEdges { get; set; } = new(); + } + + public class GenerateGoalGraphRequestDto + { + public Guid UserId { get; set; } + public string Goal { get; set; } = string.Empty; + } + + public class AICanvasAssistRequestDto + { + public Guid GraphId { get; set; } + public string UserPrompt { get; set; } = string.Empty; + } + + public class AICanvasAssistResponseDto + { + public List NewNodes { get; set; } = new(); + public List NewEdges { get; set; } = new(); + } +} diff --git a/FlowAPI.Application/DTOs/AchievementDto.cs b/FlowAPI.Application/DTOs/AchievementDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..2b87fa0499e9907bd6253e066fff4abd4c86d587 --- /dev/null +++ b/FlowAPI.Application/DTOs/AchievementDto.cs @@ -0,0 +1,17 @@ +using FlowAPI.Domain.Enums; +using System; + +namespace FlowAPI.Application.DTOs +{ + public class AchievementDto + { + public Guid Id { get; set; } + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string IconUrl { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public AchievementType Type { get; set; } + public int TargetValue { get; set; } + public int RewardPoints { get; set; } + } +} diff --git a/FlowAPI.Application/DTOs/Edge/EdgeDtos.cs b/FlowAPI.Application/DTOs/Edge/EdgeDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..6c65ef2bf05cfc0541b4d3e71b480ca05fd27636 --- /dev/null +++ b/FlowAPI.Application/DTOs/Edge/EdgeDtos.cs @@ -0,0 +1,26 @@ +using FlowAPI.Domain.Enums; + +namespace FlowAPI.Application.DTOs.Edge +{ + public class CreateEdgeDto + { + public Guid GraphId { get; set; } + public Guid FromNodeId { get; set; } + public Guid ToNodeId { get; set; } + public EdgeCondition Condition { get; set; } = EdgeCondition.True; + } + + public class UpdateEdgeDto + { + public EdgeCondition? Condition { get; set; } + } + + public class EdgeResponseDto + { + public Guid Id { get; set; } + public Guid GraphId { get; set; } + public Guid FromNodeId { get; set; } + public Guid ToNodeId { get; set; } + public EdgeCondition Condition { get; set; } + } +} diff --git a/FlowAPI.Application/DTOs/Graph/GraphDtos.cs b/FlowAPI.Application/DTOs/Graph/GraphDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..4f391a16ef818fba2ca4e811a2cedd992a34c2de --- /dev/null +++ b/FlowAPI.Application/DTOs/Graph/GraphDtos.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; + +namespace FlowAPI.Application.DTOs.Graph +{ + public class CreateGraphDto + { + public Guid UserId { get; set; } + public string Title { get; set; } = string.Empty; + public string? Description { get; set; } + } + + public class UpdateGraphDto + { + public string? Title { get; set; } + public string? Description { get; set; } + } + + public class GraphResponseDto + { + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Title { get; set; } = string.Empty; + public string? Description { get; set; } + public DateTime CreatedAt { get; set; } + public bool IsShared { get; set; } = false; + public string Permission { get; set; } = "Owner"; // "Owner", "Read", "Edit" + } + + public class FullGraphResponseDto : GraphResponseDto + { + public List Nodes { get; set; } = new(); + public List Edges { get; set; } = new(); + } + + public class ShareGraphRequestDto + { + public string Email { get; set; } = string.Empty; + public string Permission { get; set; } = "Read"; // "Read" or "Edit" + } + + public class SharedUserResponseDto + { + public Guid Id { get; set; } + public Guid SharedWithUserId { get; set; } + public string Email { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public string Permission { get; set; } = "Read"; + } + + public class NodeDto + { + public Guid Id { get; set; } + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public string Type { get; set; } = "sketch"; + public int State { get; set; } + public string? Decision { get; set; } + } + + public class EdgeDto + { + public Guid Id { get; set; } + public Guid FromNodeId { get; set; } + public Guid ToNodeId { get; set; } + public string? Condition { get; set; } + } +} diff --git a/FlowAPI.Application/DTOs/Habit/HabitDtos.cs b/FlowAPI.Application/DTOs/Habit/HabitDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..ee508863041acce72652e681867023fefa86b052 --- /dev/null +++ b/FlowAPI.Application/DTOs/Habit/HabitDtos.cs @@ -0,0 +1,17 @@ +namespace FlowAPI.Application.DTOs.Habit +{ + public class CreateHabitRecordDto + { + public Guid UserId { get; set; } + public string HabitName { get; set; } = string.Empty; + } + + public class HabitRecordResponseDto + { + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string HabitName { get; set; } = string.Empty; + public DateTime CheckedDate { get; set; } + public int StreakCount { get; set; } + } +} diff --git a/FlowAPI.Application/DTOs/Sync/SyncDtos.cs b/FlowAPI.Application/DTOs/Sync/SyncDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..c8af9cbbb14b569d0eb239d9a793ebbdfe2dcf40 --- /dev/null +++ b/FlowAPI.Application/DTOs/Sync/SyncDtos.cs @@ -0,0 +1,27 @@ +using FlowAPI.Application.DTOs.TaskNode; +using FlowAPI.Application.DTOs.Edge; + +namespace FlowAPI.Application.DTOs.Sync +{ + public class SyncRequestDto + { + public List NewNodes { get; set; } = new(); + public List UpdatedNodes { get; set; } = new(); + public List DeletedNodeIds { get; set; } = new(); + + public List NewEdges { get; set; } = new(); + public List DeletedEdgeIds { get; set; } = new(); + } + + public class UpdateTaskNodeDtoWithId : UpdateTaskNodeDto + { + public Guid Id { get; set; } + } + + public class SyncResponseDto + { + public bool Success { get; set; } + public string Message { get; set; } = string.Empty; + public DateTime ServerTime { get; set; } = DateTime.UtcNow; + } +} diff --git a/FlowAPI.Application/DTOs/TaskNode/TaskNodeDtos.cs b/FlowAPI.Application/DTOs/TaskNode/TaskNodeDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..409303201dd62823077efce426838a91a6094b85 --- /dev/null +++ b/FlowAPI.Application/DTOs/TaskNode/TaskNodeDtos.cs @@ -0,0 +1,32 @@ +using FlowAPI.Domain.Enums; + +namespace FlowAPI.Application.DTOs.TaskNode +{ + public class CreateTaskNodeDto + { + public Guid GraphId { get; set; } + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public NodeState State { get; set; } = NodeState.Pending; + } + + public class UpdateTaskNodeDto + { + public string? Label { get; set; } + public double? PosX { get; set; } + public double? PosY { get; set; } + public NodeState? State { get; set; } + } + + public class TaskNodeResponseDto + { + public Guid Id { get; set; } + public Guid GraphId { get; set; } + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public NodeState State { get; set; } + public DateTime CreatedAt { get; set; } + } +} diff --git a/FlowAPI.Application/DTOs/User/UserDtos.cs b/FlowAPI.Application/DTOs/User/UserDtos.cs new file mode 100644 index 0000000000000000000000000000000000000000..60509fa558c019b16985e80714fbb60b0c23bfeb --- /dev/null +++ b/FlowAPI.Application/DTOs/User/UserDtos.cs @@ -0,0 +1,43 @@ +namespace FlowAPI.Application.DTOs.User +{ + public class CreateUserDto + { + public string Email { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + } + + public class UpdateUserDto + { + public string? DisplayName { get; set; } + public bool? IsPremium { get; set; } + public string? AvatarUrl { get; set; } + } + + public class LoginDto + { + public string Email { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + } + + public class UserResponseDto + { + public Guid Id { get; set; } + public string Email { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public bool IsPremium { get; set; } + public string? AvatarUrl { get; set; } + public DateTime CreatedAt { get; set; } + } + + public class AuthResponseDto + { + public UserResponseDto User { get; set; } = null!; + public string Token { get; set; } = string.Empty; + } + + public class GoogleLoginDto + { + public string IdToken { get; set; } = string.Empty; + } +} diff --git a/FlowAPI.Application/DTOs/UserAchievementDto.cs b/FlowAPI.Application/DTOs/UserAchievementDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..23cd4c88418c59b474a923f828639357b5c8dc04 --- /dev/null +++ b/FlowAPI.Application/DTOs/UserAchievementDto.cs @@ -0,0 +1,14 @@ +using System; + +namespace FlowAPI.Application.DTOs +{ + public class UserAchievementDto + { + public Guid Id { get; set; } + public Guid AchievementId { get; set; } + public AchievementDto Achievement { get; set; } = default!; + public int CurrentValue { get; set; } + public bool IsUnlocked { get; set; } + public DateTime? UnlockedAt { get; set; } + } +} diff --git a/FlowAPI.Application/FlowAPI.Application.csproj b/FlowAPI.Application/FlowAPI.Application.csproj new file mode 100644 index 0000000000000000000000000000000000000000..c5b160cce7945556e0c7f1691a782afc854535bc --- /dev/null +++ b/FlowAPI.Application/FlowAPI.Application.csproj @@ -0,0 +1,20 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + + diff --git a/FlowAPI.Application/Interfaces/IAIService.cs b/FlowAPI.Application/Interfaces/IAIService.cs new file mode 100644 index 0000000000000000000000000000000000000000..af1814cb55c51025a4f5a26a46352ade9a88cf5c --- /dev/null +++ b/FlowAPI.Application/Interfaces/IAIService.cs @@ -0,0 +1,12 @@ +using FlowAPI.Application.DTOs.AI; +using FlowAPI.Application.DTOs.Graph; + +namespace FlowAPI.Application.Interfaces +{ + public interface IAIService + { + Task GenerateAlternativePathAsync(GenerateAlternativeRequestDto request); + Task GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request); + Task CanvasAssistAsync(AICanvasAssistRequestDto request); + } +} diff --git a/FlowAPI.Application/Interfaces/IAchievementRepository.cs b/FlowAPI.Application/Interfaces/IAchievementRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..c815a59b37b2362ae1fd4a8ccbdfdf4418be24fa --- /dev/null +++ b/FlowAPI.Application/Interfaces/IAchievementRepository.cs @@ -0,0 +1,13 @@ +using FlowAPI.Domain.Entities; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Interfaces +{ + public interface IAchievementRepository : IGenericRepository + { + Task> GetByTriggerEventAsync(string eventName); + Task> GetByTitlesAsync(IEnumerable titles); + Task AddRangeAsync(IEnumerable achievements); + } +} diff --git a/FlowAPI.Application/Interfaces/IAchievementService.cs b/FlowAPI.Application/Interfaces/IAchievementService.cs new file mode 100644 index 0000000000000000000000000000000000000000..547a42037ce89c7cc5c189181d380b37217ae080 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IAchievementService.cs @@ -0,0 +1,14 @@ +using FlowAPI.Application.DTOs; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Interfaces +{ + public interface IAchievementService + { + Task> GetUserAchievementsAsync(Guid userId); + Task SeedAchievementsAsync(); + Task ProcessEventAsync(Guid userId, string eventName, int amount = 1); + } +} diff --git a/FlowAPI.Application/Interfaces/IEdgeRepository.cs b/FlowAPI.Application/Interfaces/IEdgeRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..6561116745bf4abc7a524f4a1709197ae11144d8 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IEdgeRepository.cs @@ -0,0 +1,9 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface IEdgeRepository : IGenericRepository + { + Task> GetAllByGraphIdAsync(Guid graphId); + } +} diff --git a/FlowAPI.Application/Interfaces/IEdgeService.cs b/FlowAPI.Application/Interfaces/IEdgeService.cs new file mode 100644 index 0000000000000000000000000000000000000000..510fb63f748c490166ab15f6cff8b61286daa438 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IEdgeService.cs @@ -0,0 +1,12 @@ +using FlowAPI.Application.DTOs.Edge; + +namespace FlowAPI.Application.Interfaces +{ + public interface IEdgeService + { + Task> GetAllByGraphIdAsync(Guid graphId); + Task GetByIdAsync(Guid id); + Task CreateAsync(CreateEdgeDto dto); + Task DeleteAsync(Guid id); + } +} diff --git a/FlowAPI.Application/Interfaces/IGeminiBridgeManager.cs b/FlowAPI.Application/Interfaces/IGeminiBridgeManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..69eb230b98c96746e450df5a056bff1f1b0eaa0a --- /dev/null +++ b/FlowAPI.Application/Interfaces/IGeminiBridgeManager.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; + +namespace FlowAPI.Application.Interfaces +{ + public interface IGeminiBridgeManager + { + Task SendPromptAsync(string prompt, bool isNewChat, int timeoutSeconds = 120); + } +} diff --git a/FlowAPI.Application/Interfaces/IGenericRepository.cs b/FlowAPI.Application/Interfaces/IGenericRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..7a7519b657baf65eb2312538494bec828d70e211 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IGenericRepository.cs @@ -0,0 +1,11 @@ +namespace FlowAPI.Application.Interfaces +{ + public interface IGenericRepository where T : class + { + Task> GetAllAsync(); + Task GetByIdAsync(Guid id); + Task CreateAsync(T entity); + Task UpdateAsync(T entity); + Task DeleteAsync(Guid id); + } +} diff --git a/FlowAPI.Application/Interfaces/IGraphRepository.cs b/FlowAPI.Application/Interfaces/IGraphRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..0a88e9c66759b4eb3156dfb1872a747b7e736691 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IGraphRepository.cs @@ -0,0 +1,12 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface IGraphRepository : IGenericRepository + { + Task> GetAllByUserIdAsync(Guid userId); + Task GetByIdWithDetailsAsync(Guid id); + Task ClearDetailsAsync(Guid id); + Task UpsertFullGraphAsync(Guid graphId, IEnumerable nodes, IEnumerable edges); + } +} diff --git a/FlowAPI.Application/Interfaces/IGraphService.cs b/FlowAPI.Application/Interfaces/IGraphService.cs new file mode 100644 index 0000000000000000000000000000000000000000..2b799c3d023fa2f06c5223b99b73f4d46bf2e9ca --- /dev/null +++ b/FlowAPI.Application/Interfaces/IGraphService.cs @@ -0,0 +1,19 @@ +using FlowAPI.Application.DTOs.Graph; + +namespace FlowAPI.Application.Interfaces +{ + public interface IGraphService + { + Task> GetAllByUserIdAsync(Guid userId); + Task GetByIdAsync(Guid id, Guid currentUserId); + Task GetFullByIdAsync(Guid id, Guid currentUserId); + Task CreateAsync(CreateGraphDto dto, Guid currentUserId); + Task UpdateAsync(Guid id, UpdateGraphDto dto, Guid currentUserId); + Task DeleteAsync(Guid id, Guid currentUserId); + Task SaveFullGraphAsync(Guid id, FullGraphResponseDto dto, Guid currentUserId); + + Task ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto); + Task> GetSharedUsersAsync(Guid graphId, Guid ownerId); + Task RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId); + } +} diff --git a/FlowAPI.Application/Interfaces/IHabitRecordRepository.cs b/FlowAPI.Application/Interfaces/IHabitRecordRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..362517a7b957d0cf5c6312fef37ecaef6ffc6119 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IHabitRecordRepository.cs @@ -0,0 +1,10 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface IHabitRecordRepository : IGenericRepository + { + Task> GetAllByUserIdAsync(Guid userId); + Task GetTodayRecordAsync(Guid userId, string habitName); + } +} diff --git a/FlowAPI.Application/Interfaces/IHabitService.cs b/FlowAPI.Application/Interfaces/IHabitService.cs new file mode 100644 index 0000000000000000000000000000000000000000..64357fb9e58ae020243e338f0eedcb7bf5f4c7c9 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IHabitService.cs @@ -0,0 +1,11 @@ +using FlowAPI.Application.DTOs.Habit; + +namespace FlowAPI.Application.Interfaces +{ + public interface IHabitService + { + Task> GetAllByUserIdAsync(Guid userId); + Task RecordHabitAsync(CreateHabitRecordDto dto); + Task GetStreakAsync(Guid userId, string habitName); + } +} diff --git a/FlowAPI.Application/Interfaces/IPaymentService.cs b/FlowAPI.Application/Interfaces/IPaymentService.cs new file mode 100644 index 0000000000000000000000000000000000000000..b7dbc4c3f445982c225bb1ec56a525dc677302a9 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IPaymentService.cs @@ -0,0 +1,8 @@ +namespace FlowAPI.Application.Interfaces +{ + public interface IPaymentService + { + Task CreateCheckoutSessionAsync(Guid userId); + Task HandleWebhookAsync(string payload, string signature); + } +} diff --git a/FlowAPI.Application/Interfaces/ISharedGraphRepository.cs b/FlowAPI.Application/Interfaces/ISharedGraphRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..35cd2b670da588939cdf29a05e175cafa1f0e450 --- /dev/null +++ b/FlowAPI.Application/Interfaces/ISharedGraphRepository.cs @@ -0,0 +1,14 @@ +using FlowAPI.Domain.Entities; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Interfaces +{ + public interface ISharedGraphRepository : IGenericRepository + { + Task> GetSharedGraphsByUserIdAsync(Guid userId); + Task GetShareAsync(Guid graphId, Guid sharedWithUserId); + Task> GetSharesForGraphAsync(Guid graphId); + } +} diff --git a/FlowAPI.Application/Interfaces/ISyncService.cs b/FlowAPI.Application/Interfaces/ISyncService.cs new file mode 100644 index 0000000000000000000000000000000000000000..e2adc396ebf818bedae32160df47718a123bceb6 --- /dev/null +++ b/FlowAPI.Application/Interfaces/ISyncService.cs @@ -0,0 +1,9 @@ +using FlowAPI.Application.DTOs.Sync; + +namespace FlowAPI.Application.Interfaces +{ + public interface ISyncService + { + Task SyncChangesAsync(Guid userId, SyncRequestDto request); + } +} diff --git a/FlowAPI.Application/Interfaces/ITaskNodeRepository.cs b/FlowAPI.Application/Interfaces/ITaskNodeRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..37dce1d0d7b35b28c384fcbcf78796281fea8237 --- /dev/null +++ b/FlowAPI.Application/Interfaces/ITaskNodeRepository.cs @@ -0,0 +1,9 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface ITaskNodeRepository : IGenericRepository + { + Task> GetAllByGraphIdAsync(Guid graphId); + } +} diff --git a/FlowAPI.Application/Interfaces/ITaskNodeService.cs b/FlowAPI.Application/Interfaces/ITaskNodeService.cs new file mode 100644 index 0000000000000000000000000000000000000000..1b836b3614ec0b06cfbe8fd7536606d6f557156d --- /dev/null +++ b/FlowAPI.Application/Interfaces/ITaskNodeService.cs @@ -0,0 +1,13 @@ +using FlowAPI.Application.DTOs.TaskNode; + +namespace FlowAPI.Application.Interfaces +{ + public interface ITaskNodeService + { + Task> GetAllByGraphIdAsync(Guid graphId); + Task GetByIdAsync(Guid id); + Task CreateAsync(CreateTaskNodeDto dto); + Task UpdateAsync(Guid id, UpdateTaskNodeDto dto); + Task DeleteAsync(Guid id); + } +} diff --git a/FlowAPI.Application/Interfaces/ITokenService.cs b/FlowAPI.Application/Interfaces/ITokenService.cs new file mode 100644 index 0000000000000000000000000000000000000000..ec95f67f02c5a859747a6d01c6506ec0c1542deb --- /dev/null +++ b/FlowAPI.Application/Interfaces/ITokenService.cs @@ -0,0 +1,9 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface ITokenService + { + string CreateToken(User user); + } +} diff --git a/FlowAPI.Application/Interfaces/IUserAchievementRepository.cs b/FlowAPI.Application/Interfaces/IUserAchievementRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..da94ec58378c78443b5c49894b1589e87a136ace --- /dev/null +++ b/FlowAPI.Application/Interfaces/IUserAchievementRepository.cs @@ -0,0 +1,13 @@ +using FlowAPI.Domain.Entities; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Interfaces +{ + public interface IUserAchievementRepository : IGenericRepository + { + Task> GetByUserIdAsync(Guid userId); + Task> GetByUserAndAchievementIdsAsync(Guid userId, IEnumerable achievementIds); + } +} diff --git a/FlowAPI.Application/Interfaces/IUserRepository.cs b/FlowAPI.Application/Interfaces/IUserRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..b39eca3c84a8989eeeb1ea0a04ef1746a1f80a0e --- /dev/null +++ b/FlowAPI.Application/Interfaces/IUserRepository.cs @@ -0,0 +1,9 @@ +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Interfaces +{ + public interface IUserRepository : IGenericRepository + { + Task GetByEmailAsync(string email); + } +} diff --git a/FlowAPI.Application/Interfaces/IUserService.cs b/FlowAPI.Application/Interfaces/IUserService.cs new file mode 100644 index 0000000000000000000000000000000000000000..1241ac7edaaaad9f90c68e329c55b76e476f42d3 --- /dev/null +++ b/FlowAPI.Application/Interfaces/IUserService.cs @@ -0,0 +1,15 @@ +using FlowAPI.Application.DTOs.User; + +namespace FlowAPI.Application.Interfaces +{ + public interface IUserService + { + Task> GetAllAsync(); + Task GetByIdAsync(Guid id); + Task RegisterAsync(CreateUserDto dto); + Task LoginAsync(LoginDto dto); + Task GoogleLoginAsync(GoogleLoginDto dto); + Task UpdateAsync(Guid id, UpdateUserDto dto); + Task DeleteAsync(Guid id); + } +} diff --git a/FlowAPI.Application/Services/AIService.cs b/FlowAPI.Application/Services/AIService.cs new file mode 100644 index 0000000000000000000000000000000000000000..fb8cb5905b7d343e35650f1755ef4f55ef301f99 --- /dev/null +++ b/FlowAPI.Application/Services/AIService.cs @@ -0,0 +1,740 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Encodings.Web; +using System.Text.Unicode; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using FlowAPI.Application.DTOs.AI; +using FlowAPI.Application.DTOs.Graph; +using FlowAPI.Application.Interfaces; +using Microsoft.Extensions.Configuration; + +namespace FlowAPI.Application.Services +{ + public class AIService : IAIService + { + private readonly IUserRepository _userRepo; + private readonly IGraphRepository _graphRepo; + private readonly IConfiguration _config; + private readonly IGraphService _graphService; + private readonly IGeminiBridgeManager _bridgeManager; + + public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager) + { + _userRepo = userRepo; + _graphRepo = graphRepo; + _config = config; + _graphService = graphService; + _bridgeManager = bridgeManager; + } + + public async Task GenerateAlternativePathAsync(GenerateAlternativeRequestDto request) + { + // 1. Fetch graph to get user context + var graph = await _graphRepo.GetByIdAsync(request.GraphId); + if (graph == null) throw new Exception("Graph not found."); + + // 2. Check Premium Status (REQ-03) - Bypassed for regular users for now + var user = await _userRepo.GetByIdAsync(graph.UserId); + if (user == null) + { + throw new Exception("User not found."); + } + + // 3. Prepare AI Prompt + string prompt = $"Given a goal graph '{graph.Title}', the node {request.FailedNodeId} is blocked. " + + "Generate an alternative sequence of 3-5 steps to bypass this obstacle."; + + return new AIPathResponseDto + { + SuggestedNodes = new() + { + new() { Id = Guid.NewGuid(), Label = "AI: Search for alternative resources", PosX = 100, PosY = 100 }, + new() { Id = Guid.NewGuid(), Label = "AI: Contact external consultant", PosX = 200, PosY = 150 } + } + }; + } + + public async Task GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request) + { + var serializeOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) }; + // 1. Check User Premium Status or just allow AI generation + var user = await _userRepo.GetByIdAsync(request.UserId); + if (user == null) throw new Exception("User not found."); + + // 2. Formulate Prompt for Gemini + string promptText = $"You are an expert strategist and goal decomposition AI. Your task is to break down the user's goal into a sequential, logical tree or path of actionable tasks in Ukrainian.\n\n" + + $"User Goal: \"{request.Goal}\"\n\n" + + $"Create a structured, detailed roadmap of 6 to 12 sequential tasks (nodes) and their directed connections (edges) that lead the user to their goal.\n\n" + + $"Guidelines:\n" + + $"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" + + $"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" + + $"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" + + $"- Use \"condition\" nodes appropriately and dynamically when the path requires making a choice, evaluating options, or taking a different approach depending on criteria (e.g. \"Чи є досвід у програмуванні?\" or \"Вибір платформи\").\n" + + $"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" + + $"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" + + $" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" + + $" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" + + $" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" + + $" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" + + $"- For coordinates, lay out the nodes visually flowing from top to bottom. Increase 'posY' by approximately 200-240 units for each sequential step. Vary 'posX' (e.g., between 200 and 700) if there are parallel branches or decision paths.\n" + + $"- Every node must have a unique string 'id' (like \"node_1\", \"node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" + + $"- All nodes must be reachable via edges starting from the initial steps.\n\n" + + $"Provide the output strictly in a valid JSON format following this schema, with no additional explanation, no markdown text outside the JSON, and no other content:\n" + + $"{{\n" + + $" \"title\": \"Коротка та приваблива назва дорожньої карти\",\n" + + $" \"description\": \"Короткий опис стратегії\",\n" + + $" \"nodes\": [\n" + + $" {{ \"id\": \"node_1\", \"label\": \"Детальний перший крок\", \"posX\": 450, \"posY\": 100, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"node_2\", \"label\": \"Оберіть платформу для розробки\", \"posX\": 450, \"posY\": 300, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-web\", \"label\": \"Web\" }}, {{ \"id\": \"opt-mobile\", \"label\": \"Mobile\" }}, {{ \"id\": \"opt-desktop\", \"label\": \"Desktop\" }} ] }},\n" + + $" {{ \"id\": \"node_3\", \"label\": \"Освоєння HTML, CSS та JavaScript\", \"posX\": 200, \"posY\": 520, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"node_4\", \"label\": \"Вивчення Swift або Kotlin\", \"posX\": 450, \"posY\": 520, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"node_5\", \"label\": \"Вивчення C# та .NET для настільних вікон\", \"posX\": 700, \"posY\": 520, \"type\": \"sketch\" }}\n" + + $" ],\n" + + $" \"edges\": [\n" + + $" {{ \"from\": \"node_1\", \"to\": \"node_2\", \"condition\": \"True\" }},\n" + + $" {{ \"from\": \"node_2\", \"to\": \"node_3\", \"condition\": \"True\" }},\n" + + $" {{ \"from\": \"node_2\", \"to\": \"node_4\", \"condition\": \"False\" }},\n" + + $" {{ \"from\": \"node_2\", \"to\": \"node_5\", \"condition\": \"Blocked\" }}\n" + + $" ]\n" + + $"}}"; + + // 3. Send Prompt via Persistent Bridge + string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120); + + // 7. Parse Bridge Message + using var jsonDoc = JsonDocument.Parse(rawResponseJson); + var root = jsonDoc.RootElement; + if (root.GetProperty("status").GetString() != "success") + { + string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed"; + throw new Exception("AI bridge returned error: " + errMsg); + } + + string aiContent = root.GetProperty("content").GetString() ?? string.Empty; + string cleanJson = CleanJson(aiContent); + + if (string.IsNullOrWhiteSpace(cleanJson)) + { + throw new Exception("The AI bridge returned empty content. Please try generating again."); + } + + // 8. Deserialize AI Roadmap Structure + AIGoalGraphResponse? parsedData; + try + { + parsedData = JsonSerializer.Deserialize(cleanJson, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + } + catch (JsonException ex) + { + string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent; + throw new Exception($"Failed to parse AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex); + } + + if (parsedData == null || parsedData.Nodes == null || parsedData.Nodes.Count == 0) + { + throw new Exception("The AI response did not contain a valid nodes list."); + } + + // 9. Map temporary String IDs to Database GUIDs + var guidMap = new Dictionary(); + var nodeDtos = new List(); + + for (int i = 0; i < parsedData.Nodes.Count; i++) + { + var aiNode = parsedData.Nodes[i]; + var newGuid = Guid.NewGuid(); + guidMap[aiNode.Id] = newGuid; + + // Coordinate layout will be handled by the layout engine later + double finalX = aiNode.PosX; + double finalY = aiNode.PosY; + + string? decisionJson = null; + if (aiNode.Type == "condition") + { + var optionsList = new List(); + if (aiNode.Options != null && aiNode.Options.Count > 0) + { + foreach (var opt in aiNode.Options) + { + optionsList.Add(new { id = opt.Id, label = opt.Label }); + } + } + else + { + optionsList.Add(new { id = "opt-yes", label = "Так" }); + optionsList.Add(new { id = "opt-no", label = "Ні" }); + } + + decisionJson = JsonSerializer.Serialize(new + { + options = optionsList, + selected = new string[] { }, + multiSelect = false + }, serializeOptions); + } + + nodeDtos.Add(new NodeDto + { + Id = newGuid, + Label = aiNode.Label, + PosX = finalX, + PosY = finalY, + Type = aiNode.Type ?? "sketch", + State = 0, + Decision = decisionJson + }); + } + + var edgeDtos = new List(); + if (parsedData.Edges != null) + { + foreach (var aiEdge in parsedData.Edges) + { + if (guidMap.TryGetValue(aiEdge.From, out var fromGuid) && + guidMap.TryGetValue(aiEdge.To, out var toGuid)) + { + edgeDtos.Add(new EdgeDto + { + Id = Guid.NewGuid(), + FromNodeId = fromGuid, + ToNodeId = toGuid, + Condition = aiEdge.Condition ?? "True" + }); + } + } + } + + // 10. Apply Automated Beautiful Layout + ApplyBeautifulLayout(nodeDtos, edgeDtos); + + // 11. Persist using existing GraphService + var createDto = new CreateGraphDto + { + UserId = request.UserId, + Title = string.IsNullOrWhiteSpace(parsedData.Title) ? request.Goal : parsedData.Title, + Description = string.IsNullOrWhiteSpace(parsedData.Description) ? "AI generated roadmap" : parsedData.Description + }; + + var createdGraph = await _graphService.CreateAsync(createDto, request.UserId); + + var fullGraphDto = new FullGraphResponseDto + { + Id = createdGraph.Id, + UserId = createdGraph.UserId, + Title = createdGraph.Title, + Description = createdGraph.Description, + CreatedAt = createdGraph.CreatedAt, + Nodes = nodeDtos, + Edges = edgeDtos + }; + + bool saveSuccess = await _graphService.SaveFullGraphAsync(createdGraph.Id, fullGraphDto, request.UserId); + if (!saveSuccess) + { + throw new Exception("Graph was created, but failed to save the sequential roadmap steps."); + } + + return fullGraphDto; + } + + public async Task CanvasAssistAsync(AICanvasAssistRequestDto request) + { + // 1. Fetch graph with all details + var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); + if (graph == null) throw new Exception("Graph not found."); + + // 2. Prepare serialization of active nodes and edges + var currentNodesList = graph.Nodes.Select(n => new { + id = n.Id.ToString(), + label = n.Label, + posX = n.PosX, + posY = n.PosY, + type = n.Type, + state = n.State.ToString() + }).ToList(); + + var currentEdgesList = graph.Edges.Select(e => new { + id = e.Id.ToString(), + from = e.FromNodeId.ToString(), + to = e.ToNodeId.ToString(), + condition = e.Condition.ToString() + }).ToList(); + + var serializeOptions = new JsonSerializerOptions + { + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) + }; + + // 4. Formulate Prompt for Gemini + string promptText = $"You are an expert strategist and goal decomposition AI.\n" + + $"The user has an active strategy roadmap titled \"{graph.Title}\" with the description \"{graph.Description}\" in Ukrainian.\n\n" + + $"Current Canvas Structure (in Ukrainian):\n" + + $"- Nodes: {JsonSerializer.Serialize(currentNodesList, serializeOptions)}\n" + + $"- Edges: {JsonSerializer.Serialize(currentEdgesList, serializeOptions)}\n\n" + + $"User Request: \"{request.UserPrompt}\"\n\n" + + $"Analyze the current roadmap, and satisfy the user's request. Suggest adding new steps, alternative/branching paths, or decision conditions.\n" + + $"Create a list of NEW nodes and edges that should be added/merged into the canvas to satisfy the request.\n\n" + + $"Guidelines:\n" + + $"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" + + $"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" + + $"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" + + $"- Use \"condition\" nodes appropriately and dynamically when the user request or alternative path requires a choice, criteria evaluation, or conditional gate.\n" + + $"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" + + $"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" + + $" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" + + $" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" + + $" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" + + $" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" + + $"- For coordinates of new nodes, calculate 'posX' and 'posY' relative to nearby nodes so they flow nicely. Use values that don't directly overlap existing coordinates.\n" + + $"- Every new node must have a unique string 'id' starting with \"new_node_\" (like \"new_node_1\", \"new_node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" + + $"- You can also use existing node IDs (from the current structure) in the 'from' and 'to' fields of the new edges to link the new nodes into the existing flow!\n" + + $"- All new edges should connect new nodes to each other, or to existing nodes.\n\n" + + $"Provide the output strictly in a valid JSON format following this schema, with no explanation, no markdown text outside the JSON, and no other content:\n" + + $"{{\n" + + $" \"newNodes\": [\n" + + $" {{ \"id\": \"new_node_1\", \"label\": \"Детальний новий крок для розширення\", \"posX\": 450, \"posY\": 300, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"new_node_2\", \"label\": \"Нова умова вибору середовища\", \"posX\": 450, \"posY\": 520, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-react\", \"label\": \"React\" }}, {{ \"id\": \"opt-vue\", \"label\": \"Vue\" }}, {{ \"id\": \"opt-angular\", \"label\": \"Angular\" }} ] }},\n" + + $" {{ \"id\": \"new_node_3\", \"label\": \"Вивчення React hooks та JSX\", \"posX\": 200, \"posY\": 740, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"new_node_4\", \"label\": \"Вивчення Composition API у Vue\", \"posX\": 450, \"posY\": 740, \"type\": \"sketch\" }},\n" + + $" {{ \"id\": \"new_node_5\", \"label\": \"Вивчення TypeScript та RxJS в Angular\", \"posX\": 700, \"posY\": 740, \"type\": \"sketch\" }}\n" + + $" ],\n" + + $" \"newEdges\": [\n" + + $" {{ \"from\": \"existing_node_id_here\", \"to\": \"new_node_1\" }},\n" + + $" {{ \"from\": \"new_node_1\", \"to\": \"new_node_2\" }},\n" + + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_3\", \"condition\": \"True\" }},\n" + + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_4\", \"condition\": \"False\" }},\n" + + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_5\", \"condition\": \"Blocked\" }}\n" + + $" ]\n" + + $"}}"; + + // 3. Send Prompt via Persistent Bridge + string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120); + if (string.IsNullOrEmpty(rawResponseJson)) + { + throw new Exception("Did not receive a valid response block from the Gemini Bridge."); + } + + // Parse Bridge Message + using var jsonDoc = JsonDocument.Parse(rawResponseJson); + var root = jsonDoc.RootElement; + + if (root.GetProperty("status").GetString() != "success") + { + string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed"; + throw new Exception("AI bridge returned error: " + errMsg); + } + + string aiContent = root.GetProperty("content").GetString() ?? string.Empty; + string cleanJson = CleanJson(aiContent); + + if (string.IsNullOrWhiteSpace(cleanJson)) + { + throw new Exception("The AI bridge returned empty canvas assist content. Please try generating again."); + } + + // Deserialize AI Assist Response Structure + AICanvasAssistResponseInternal? parsedData; + try + { + parsedData = JsonSerializer.Deserialize(cleanJson, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + } + catch (JsonException ex) + { + string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent; + throw new Exception($"Failed to parse Canvas Assist AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex); + } + + if (parsedData == null || parsedData.NewNodes == null) + { + throw new Exception("The AI response did not contain a valid newNodes list."); + } + + // Map temporary IDs to database GUIDs + var guidMap = new Dictionary(); + var newNodesEntities = new List(); + var nodeDtos = new List(); + + for (int i = 0; i < parsedData.NewNodes.Count; i++) + { + var aiNode = parsedData.NewNodes[i]; + var newGuid = Guid.NewGuid(); + guidMap[aiNode.Id] = newGuid; + + string? decisionJson = null; + if (aiNode.Type == "condition") + { + var optionsList = new List(); + if (aiNode.Options != null && aiNode.Options.Count > 0) + { + foreach (var opt in aiNode.Options) + { + optionsList.Add(new { id = opt.Id, label = opt.Label }); + } + } + else + { + optionsList.Add(new { id = "opt-yes", label = "Так" }); + optionsList.Add(new { id = "opt-no", label = "Ні" }); + } + + decisionJson = JsonSerializer.Serialize(new + { + options = optionsList, + selected = new string[] { }, + multiSelect = false + }, serializeOptions); + } + + var nodeEntity = new FlowAPI.Domain.Entities.TaskNode + { + Id = newGuid, + GraphId = request.GraphId, + Label = aiNode.Label, + PosX = aiNode.PosX, + PosY = aiNode.PosY, + Type = aiNode.Type ?? "sketch", + State = FlowAPI.Domain.Enums.NodeState.Pending, + Decision = decisionJson, + CreatedAt = DateTime.UtcNow + }; + newNodesEntities.Add(nodeEntity); + + nodeDtos.Add(new NodeDto + { + Id = newGuid, + Label = aiNode.Label, + PosX = aiNode.PosX, + PosY = aiNode.PosY, + Type = aiNode.Type ?? "sketch", + State = 0, + Decision = decisionJson + }); + } + + var newEdgesEntities = new List(); + var edgeDtos = new List(); + + if (parsedData.NewEdges != null) + { + foreach (var aiEdge in parsedData.NewEdges) + { + Guid fromGuid; + if (Guid.TryParse(aiEdge.From, out var fromParsed)) + { + fromGuid = fromParsed; + } + else if (guidMap.TryGetValue(aiEdge.From, out var mappedFrom)) + { + fromGuid = mappedFrom; + } + else + { + continue; + } + + Guid toGuid; + if (Guid.TryParse(aiEdge.To, out var toParsed)) + { + toGuid = toParsed; + } + else if (guidMap.TryGetValue(aiEdge.To, out var mappedTo)) + { + toGuid = mappedTo; + } + else + { + continue; + } + + var edgeGuid = Guid.NewGuid(); + var edgeEntity = new FlowAPI.Domain.Entities.Edge + { + Id = edgeGuid, + GraphId = request.GraphId, + FromNodeId = fromGuid, + ToNodeId = toGuid, + Condition = Enum.TryParse(aiEdge.Condition, true, out var conditionEnum) ? conditionEnum : FlowAPI.Domain.Enums.EdgeCondition.True + }; + newEdgesEntities.Add(edgeEntity); + + edgeDtos.Add(new EdgeDto + { + Id = edgeGuid, + FromNodeId = fromGuid, + ToNodeId = toGuid, + Condition = aiEdge.Condition ?? "True" + }); + } + } + + // Apply Automated Beautiful Layout to the entire combined graph + var allNodes = graph.Nodes.Concat(newNodesEntities).ToList(); + var allEdges = graph.Edges.Concat(newEdgesEntities).ToList(); + + ApplyBeautifulLayout(allNodes, allEdges); + + // Update the DTOs with the beautifully laid out coordinates so the frontend places them perfectly + foreach (var dto in nodeDtos) + { + var entity = allNodes.FirstOrDefault(n => n.Id == dto.Id); + if (entity != null) + { + dto.PosX = entity.PosX; + dto.PosY = entity.PosY; + } + } + + // Persist directly using repository + bool saveSuccess = await _graphRepo.UpsertFullGraphAsync(request.GraphId, allNodes, allEdges); + if (!saveSuccess) + { + throw new Exception("Failed to persist newly suggested AI canvas elements to database."); + } + + return new AICanvasAssistResponseDto + { + NewNodes = nodeDtos, + NewEdges = edgeDtos + }; + } + + private string CleanJson(string text) + { + text = text.Trim(); + if (text.StartsWith("```")) + { + var lines = text.Split('\n'); + var cleanLines = lines.Where(line => !line.Trim().StartsWith("```")).ToArray(); + text = string.Join("\n", cleanLines).Trim(); + } + return text; + } + + private void ApplyBeautifulLayout(List nodes, List edges) + { + if (nodes == null || nodes.Count == 0) return; + + var inDegree = new Dictionary(); + var adj = new Dictionary>(); + + foreach (var node in nodes) + { + inDegree[node.Id] = 0; + adj[node.Id] = new List(); + } + + foreach (var edge in edges) + { + if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId)) + { + inDegree[edge.ToNodeId]++; + adj[edge.FromNodeId].Add(edge.ToNodeId); + } + } + + var layers = new Dictionary(); + foreach (var node in nodes) { layers[node.Id] = 0; } + + var queue = new Queue(); + foreach (var node in nodes) + { + if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); } + } + + if (queue.Count == 0 && nodes.Count > 0) + { + queue.Enqueue(nodes[0].Id); + } + + var processed = new HashSet(); + while (queue.Count > 0) + { + var curr = queue.Dequeue(); + processed.Add(curr); + + int currentLayer = layers[curr]; + foreach (var neighbor in adj[curr]) + { + layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1); + if (!processed.Contains(neighbor) && !queue.Contains(neighbor)) + { + queue.Enqueue(neighbor); + } + } + } + + var nodesByLayer = new Dictionary>(); + foreach (var node in nodes) + { + int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; + if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List(); } + nodesByLayer[layer].Add(node); + } + + double marginY = 100; + double spacingY = 220; + double spacingX = 350; + double centerX = 450; + + var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList(); + foreach (var layer in sortedLayers) + { + var layerNodes = nodesByLayer[layer]; + int count = layerNodes.Count; + for (int i = 0; i < count; i++) + { + var node = layerNodes[i]; + node.PosY = marginY + layer * spacingY; + node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX; + } + } + } + + private void ApplyBeautifulLayout(List nodes, List edges) + { + if (nodes == null || nodes.Count == 0) return; + + var inDegree = new Dictionary(); + var adj = new Dictionary>(); + + foreach (var node in nodes) + { + inDegree[node.Id] = 0; + adj[node.Id] = new List(); + } + + foreach (var edge in edges) + { + if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId)) + { + inDegree[edge.ToNodeId]++; + adj[edge.FromNodeId].Add(edge.ToNodeId); + } + } + + var layers = new Dictionary(); + foreach (var node in nodes) { layers[node.Id] = 0; } + + var queue = new Queue(); + foreach (var node in nodes) + { + if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); } + } + + if (queue.Count == 0 && nodes.Count > 0) + { + queue.Enqueue(nodes[0].Id); + } + + var processed = new HashSet(); + while (queue.Count > 0) + { + var curr = queue.Dequeue(); + processed.Add(curr); + + int currentLayer = layers[curr]; + foreach (var neighbor in adj[curr]) + { + layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1); + if (!processed.Contains(neighbor) && !queue.Contains(neighbor)) + { + queue.Enqueue(neighbor); + } + } + } + + var nodesByLayer = new Dictionary>(); + foreach (var node in nodes) + { + int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; + if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List(); } + nodesByLayer[layer].Add(node); + } + + double marginY = 100; + double spacingY = 220; + double spacingX = 350; + double centerX = 450; + + var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList(); + foreach (var layer in sortedLayers) + { + var layerNodes = nodesByLayer[layer]; + int count = layerNodes.Count; + for (int i = 0; i < count; i++) + { + var node = layerNodes[i]; + node.PosY = marginY + layer * spacingY; + node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX; + } + } + } + + private class AIGoalGraphResponse + { + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public List Nodes { get; set; } = new(); + public List Edges { get; set; } = new(); + } + + private class AIOptionDto + { + public string Id { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + } + + private class AINodeDto + { + public string Id { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public string? Type { get; set; } + public List? Options { get; set; } + } + + private class AIEdgeDto + { + public string From { get; set; } = string.Empty; + public string To { get; set; } = string.Empty; + public string? Condition { get; set; } + } + + private class AICanvasAssistResponseInternal + { + public List NewNodes { get; set; } = new(); + public List NewEdges { get; set; } = new(); + } + + private class AINewNodeInternalDto + { + public string Id { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public string? Type { get; set; } + public List? Options { get; set; } + } + + private class AINewEdgeInternalDto + { + public string From { get; set; } = string.Empty; + public string To { get; set; } = string.Empty; + public string? Condition { get; set; } + } + } +} diff --git a/FlowAPI.Application/Services/AchievementService.cs b/FlowAPI.Application/Services/AchievementService.cs new file mode 100644 index 0000000000000000000000000000000000000000..a2fb0fef9b872278507a9489fff4fdfa9de010d5 --- /dev/null +++ b/FlowAPI.Application/Services/AchievementService.cs @@ -0,0 +1,161 @@ +using FlowAPI.Application.DTOs; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Domain.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Services +{ + public class AchievementService : IAchievementService + { + private readonly IAchievementRepository _achievementRepo; + private readonly IUserAchievementRepository _userAchievementRepo; + private readonly IUserRepository _userRepo; + + public AchievementService(IAchievementRepository achievementRepo, IUserAchievementRepository userAchievementRepo, IUserRepository userRepo) + { + _achievementRepo = achievementRepo; + _userAchievementRepo = userAchievementRepo; + _userRepo = userRepo; + } + + public async Task> GetUserAchievementsAsync(Guid userId) + { + var allAchievements = await _achievementRepo.GetAllAsync(); + var userAchievements = await _userAchievementRepo.GetByUserIdAsync(userId); + + var user = await _userRepo.GetByIdAsync(userId); + var isAvatarUploaded = user != null && !string.IsNullOrEmpty(user.AvatarUrl); + + var result = new List(); + + foreach (var achievement in allAchievements) + { + var userRecord = userAchievements.FirstOrDefault(ua => ua.AchievementId == achievement.Id); + + // Retroactively unlock Self Portrait if user already has an avatar set but no record or locked record in DB + if (achievement.Title == "Self Portrait" && isAvatarUploaded) + { + if (userRecord == null) + { + var newUa = new UserAchievement + { + UserId = userId, + AchievementId = achievement.Id, + CurrentValue = 1, + IsUnlocked = true, + UnlockedAt = DateTime.UtcNow + }; + userRecord = await _userAchievementRepo.CreateAsync(newUa); + } + else if (!userRecord.IsUnlocked) + { + userRecord.CurrentValue = 1; + userRecord.IsUnlocked = true; + userRecord.UnlockedAt = DateTime.UtcNow; + userRecord = await _userAchievementRepo.UpdateAsync(userRecord); + } + } + + result.Add(new UserAchievementDto + { + Id = userRecord?.Id ?? Guid.Empty, + AchievementId = achievement.Id, + CurrentValue = userRecord?.CurrentValue ?? 0, + IsUnlocked = userRecord?.IsUnlocked ?? false, + UnlockedAt = userRecord?.UnlockedAt, + Achievement = new AchievementDto + { + Id = achievement.Id, + Title = achievement.Title, + Description = achievement.Description, + IconUrl = achievement.IconUrl, + Category = achievement.Category, + Type = achievement.Type, + TargetValue = achievement.TargetValue, + RewardPoints = achievement.RewardPoints + } + }); + } + + return result; + } + + public async Task ProcessEventAsync(Guid userId, string eventName, int amount = 1) + { + // 1. Find achievements triggered by this event + var triggeredAchievements = await _achievementRepo.GetByTriggerEventAsync(eventName); + + if (!triggeredAchievements.Any()) return; + + // 2. Fetch user's current progress for these achievements + var achievementIds = triggeredAchievements.Select(a => a.Id).ToList(); + var userAchievements = await _userAchievementRepo.GetByUserAndAchievementIdsAsync(userId, achievementIds); + + foreach (var achievement in triggeredAchievements) + { + var ua = userAchievements.FirstOrDefault(u => u.AchievementId == achievement.Id); + + // If user doesn't have a tracking record yet, create it + if (ua == null) + { + ua = new UserAchievement + { + UserId = userId, + AchievementId = achievement.Id, + CurrentValue = 0, + IsUnlocked = false + }; + ua = await _userAchievementRepo.CreateAsync(ua); + } + + // Skip if already unlocked + if (ua.IsUnlocked) continue; + + // Update progress + if (achievement.Type == AchievementType.Accumulative || achievement.Type == AchievementType.SingleAction) + { + ua.CurrentValue += amount; + } + + // Check for unlock + if (ua.CurrentValue >= achievement.TargetValue) + { + ua.CurrentValue = achievement.TargetValue; + ua.IsUnlocked = true; + ua.UnlockedAt = DateTime.UtcNow; + } + + await _userAchievementRepo.UpdateAsync(ua); + } + } + + public async Task SeedAchievementsAsync() + { + var seedData = new List + { + new Achievement { Title = "Blank Canvas", Description = "Create your first project (Graph).", Category = "Projects", Type = AchievementType.SingleAction, TargetValue = 1, RewardPoints = 10, TriggerEventName = "GraphCreated" }, + new Achievement { Title = "Connecting the Dots", Description = "Create 10 connections (Edges) between tasks.", Category = "Tasks", Type = AchievementType.Accumulative, TargetValue = 10, RewardPoints = 50, TriggerEventName = "EdgeCreated" }, + new Achievement { Title = "Sketch Master", Description = "Create 100 task nodes overall.", Category = "Tasks", Type = AchievementType.Accumulative, TargetValue = 100, RewardPoints = 100, TriggerEventName = "NodeCreated" }, + new Achievement { Title = "Daily Doodler", Description = "Track habits 7 times.", Category = "Habits", Type = AchievementType.Accumulative, TargetValue = 7, RewardPoints = 70, TriggerEventName = "HabitTracked" }, + new Achievement { Title = "Decision Maker", Description = "Complete 50 tasks.", Category = "Tasks", Type = AchievementType.Accumulative, TargetValue = 50, RewardPoints = 50, TriggerEventName = "TaskCompleted" }, + new Achievement { Title = "Clear Desk", Description = "Delete 5 projects.", Category = "System", Type = AchievementType.Accumulative, TargetValue = 5, RewardPoints = 20, TriggerEventName = "GraphDeleted" }, + new Achievement { Title = "First Milestone", Description = "Complete your first task.", Category = "Tasks", Type = AchievementType.SingleAction, TargetValue = 1, RewardPoints = 15, TriggerEventName = "TaskCompleted" }, + new Achievement { Title = "Self Portrait", Description = "Upload your profile avatar.", Category = "System", Type = AchievementType.SingleAction, TargetValue = 1, RewardPoints = 15, TriggerEventName = "AvatarUploaded" } + }; + + var existing = await _achievementRepo.GetByTitlesAsync(seedData.Select(s => s.Title)); + var existingTitles = existing.Select(e => e.Title).ToList(); + + var toAdd = seedData.Where(s => !existingTitles.Contains(s.Title)).ToList(); + + if (toAdd.Any()) + { + await _achievementRepo.AddRangeAsync(toAdd); + } + } + } +} diff --git a/FlowAPI.Application/Services/EdgeService.cs b/FlowAPI.Application/Services/EdgeService.cs new file mode 100644 index 0000000000000000000000000000000000000000..0e49b474db5de347f0925d6bcba36a2f7ef6507b --- /dev/null +++ b/FlowAPI.Application/Services/EdgeService.cs @@ -0,0 +1,57 @@ +using FlowAPI.Application.DTOs.Edge; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Services +{ + public class EdgeService : IEdgeService + { + private readonly IEdgeRepository _repo; + + public EdgeService(IEdgeRepository repo) + { + _repo = repo; + } + + public async Task> GetAllByGraphIdAsync(Guid graphId) + { + var edges = await _repo.GetAllByGraphIdAsync(graphId); + return edges.Select(MapToDto); + } + + public async Task GetByIdAsync(Guid id) + { + var edge = await _repo.GetByIdAsync(id); + return edge is null ? null : MapToDto(edge); + } + + public async Task CreateAsync(CreateEdgeDto dto) + { + var edge = new Edge + { + Id = Guid.NewGuid(), + GraphId = dto.GraphId, + FromNodeId = dto.FromNodeId, + ToNodeId = dto.ToNodeId, + Condition = dto.Condition + }; + + var created = await _repo.CreateAsync(edge); + return MapToDto(created); + } + + public async Task DeleteAsync(Guid id) + { + return await _repo.DeleteAsync(id); + } + + private static EdgeResponseDto MapToDto(Edge edge) => new() + { + Id = edge.Id, + GraphId = edge.GraphId, + FromNodeId = edge.FromNodeId, + ToNodeId = edge.ToNodeId, + Condition = edge.Condition + }; + } +} diff --git a/FlowAPI.Application/Services/GeminiBridgeManager.cs b/FlowAPI.Application/Services/GeminiBridgeManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..1b2851fa45c828c81a45640f8ffb58a50f6892ba --- /dev/null +++ b/FlowAPI.Application/Services/GeminiBridgeManager.cs @@ -0,0 +1,203 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text.Json; +using System.Text.Encodings.Web; +using System.Text.Unicode; +using System.Threading; +using System.Threading.Tasks; +using FlowAPI.Application.Interfaces; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace FlowAPI.Application.Services +{ + public class GeminiBridgeManager : IGeminiBridgeManager, IDisposable + { + private readonly ILogger _logger; + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); + private Process? _process; + private bool _isReady = false; + private readonly JsonSerializerOptions _serializeOptions; + + public GeminiBridgeManager(ILogger logger, IHostApplicationLifetime appLifetime) + { + _logger = logger; + _serializeOptions = new JsonSerializerOptions + { + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) + }; + + appLifetime.ApplicationStopping.Register(() => + { + _logger.LogInformation("Application stopping, closing Gemini Bridge."); + Dispose(); + }); + } + + private async Task EnsureProcessStartedAsync() + { + if (_process != null && !_process.HasExited && _isReady) + return; + + _logger.LogInformation("Starting persistent Gemini Bridge process..."); + + string scriptPath = Path.Combine(AppContext.BaseDirectory, "gemini_bridge.py"); + if (!File.Exists(scriptPath)) + { + scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "gemini_bridge.py"); + } + if (!File.Exists(scriptPath)) + { + scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "gemini_bridge.py"); + } + + if (!File.Exists(scriptPath)) + { + throw new FileNotFoundException("Could not locate gemini_bridge.py in application folders."); + } + + var startInfo = new ProcessStartInfo + { + FileName = "python", + Arguments = $"\"{scriptPath}\" --headless", + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = Path.GetDirectoryName(scriptPath) + }; + + _process = new Process { StartInfo = startInfo }; + _process.Start(); + + // Fire and forget error logging + _ = Task.Run(async () => + { + while (_process != null && !_process.HasExited && !_process.StandardError.EndOfStream) + { + var errLine = await _process.StandardError.ReadLineAsync(); + if (!string.IsNullOrEmpty(errLine)) + { + _logger.LogWarning($"[GeminiBridge Python]: {errLine}"); + } + } + }); + + // Wait for bridge to declare itself "ready" + var readyTimeout = Task.Delay(TimeSpan.FromSeconds(45)); + var readReadyTask = Task.Run(async () => + { + while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream) + { + var l = await _process.StandardOutput.ReadLineAsync(); + if (l != null && l.Contains("\"type\": \"ready\"")) + { + return true; + } + } + return false; + }); + + var completedTask = await Task.WhenAny(readReadyTask, readyTimeout); + if (completedTask == readyTimeout || !await readReadyTask) + { + try { _process.Kill(); } catch { } + _process = null; + throw new Exception("Timeout or failure waiting for persistent Gemini Browser Bridge to initialize."); + } + + _isReady = true; + _logger.LogInformation("Persistent Gemini Bridge initialized successfully."); + } + + public async Task SendPromptAsync(string promptText, bool isNewChat, int timeoutSeconds = 120) + { + await _semaphore.WaitAsync(); + try + { + await EnsureProcessStartedAsync(); + + if (_process == null || _process.HasExited) + throw new Exception("Gemini Bridge process is not running."); + + var promptObj = new + { + type = "prompt", + id = Guid.NewGuid().ToString(), + new_chat = isNewChat, + content = promptText + }; + + string promptRequestJson = JsonSerializer.Serialize(promptObj, _serializeOptions); + + // Send Prompt to standard input + await _process.StandardInput.WriteLineAsync(promptRequestJson); + await _process.StandardInput.FlushAsync(); + + // Await Gemini final response + var responseTimeout = Task.Delay(TimeSpan.FromSeconds(timeoutSeconds)); + var readResponseTask = Task.Run(async () => + { + while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream) + { + var l = await _process.StandardOutput.ReadLineAsync(); + if (l != null && l.Contains("\"type\": \"response\"") && l.Contains($"\"id\": \"{promptObj.id}\"")) + { + return l; + } + } + return null; + }); + + var responseCompletedTask = await Task.WhenAny(readResponseTask, responseTimeout); + if (responseCompletedTask == responseTimeout) + { + // If timeout occurs, we should probably kill the process to avoid desync + try { _process.Kill(); } catch { } + _process = null; + _isReady = false; + throw new Exception("Timeout waiting for AI response from Gemini Bridge."); + } + + string? rawResponseJson = await readResponseTask; + + if (string.IsNullOrEmpty(rawResponseJson)) + { + throw new Exception("Did not receive a valid response block from the Gemini Bridge."); + } + + return rawResponseJson; + } + finally + { + _semaphore.Release(); + } + } + + public void Dispose() + { + if (_process != null) + { + try + { + if (!_process.HasExited) + { + _process.StandardInput.WriteLine("{\"type\": \"exit\"}"); + _process.StandardInput.Flush(); + Thread.Sleep(500); // Give it a moment to exit gracefully + if (!_process.HasExited) + { + _process.Kill(); + } + } + } + catch { } + _process.Dispose(); + _process = null; + } + _semaphore.Dispose(); + } + } +} diff --git a/FlowAPI.Application/Services/GraphService.cs b/FlowAPI.Application/Services/GraphService.cs new file mode 100644 index 0000000000000000000000000000000000000000..afbc927c956f7890cd99f506c34994fa0c92c50e --- /dev/null +++ b/FlowAPI.Application/Services/GraphService.cs @@ -0,0 +1,320 @@ +using FlowAPI.Application.DTOs.Graph; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace FlowAPI.Application.Services +{ + public class GraphService : IGraphService + { + private readonly IGraphRepository _repo; + private readonly ITaskNodeRepository _nodeRepo; + private readonly IEdgeRepository _edgeRepo; + private readonly IAchievementService _achievementService; + private readonly ISharedGraphRepository _sharedGraphRepo; + private readonly IUserRepository _userRepo; + + public GraphService( + IGraphRepository repo, + ITaskNodeRepository nodeRepo, + IEdgeRepository edgeRepo, + IAchievementService achievementService, + ISharedGraphRepository sharedGraphRepo, + IUserRepository userRepo) + { + _repo = repo; + _nodeRepo = nodeRepo; + _edgeRepo = edgeRepo; + _achievementService = achievementService; + _sharedGraphRepo = sharedGraphRepo; + _userRepo = userRepo; + } + + public async Task> GetAllByUserIdAsync(Guid userId) + { + // Owned graphs + var ownedGraphs = await _repo.GetAllByUserIdAsync(userId); + var ownedDtos = ownedGraphs.Select(g => + { + var dto = MapToDto(g); + dto.IsShared = false; + dto.Permission = "Owner"; + return dto; + }).ToList(); + + // Shared graphs + var sharedShares = await _sharedGraphRepo.GetSharedGraphsByUserIdAsync(userId); + + var sharedDtos = sharedShares.Select(s => + { + var dto = MapToDto(s.Graph); + dto.IsShared = true; + dto.Permission = s.Permission; + return dto; + }).ToList(); + + return ownedDtos.Concat(sharedDtos); + } + + public async Task GetByIdAsync(Guid id, Guid currentUserId) + { + var graph = await _repo.GetByIdAsync(id); + if (graph is null) return null; + + if (graph.UserId == currentUserId) + { + var dto = MapToDto(graph); + dto.IsShared = false; + dto.Permission = "Owner"; + return dto; + } + + var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId); + if (shared is not null) + { + var dto = MapToDto(graph); + dto.IsShared = true; + dto.Permission = shared.Permission; + return dto; + } + + return null; + } + + public async Task GetFullByIdAsync(Guid id, Guid currentUserId) + { + var graph = await _repo.GetByIdWithDetailsAsync(id); + if (graph is null) return null; + + string permission = "Owner"; + bool isShared = false; + + if (graph.UserId != currentUserId) + { + var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId); + if (shared is null) return null; + permission = shared.Permission; + isShared = true; + } + + return new FullGraphResponseDto + { + Id = graph.Id, + UserId = graph.UserId, + Title = graph.Title, + Description = graph.Description, + CreatedAt = graph.CreatedAt, + IsShared = isShared, + Permission = permission, + Nodes = graph.Nodes.Select(n => new NodeDto + { + Id = n.Id, + Label = n.Label, + PosX = n.PosX, + PosY = n.PosY, + Type = n.Type, + State = (int)n.State, + Decision = n.Decision + }).ToList(), + Edges = graph.Edges.Select(e => new EdgeDto + { + Id = e.Id, + FromNodeId = e.FromNodeId, + ToNodeId = e.ToNodeId, + Condition = e.Condition.ToString() + }).ToList() + }; + } + + public async Task CreateAsync(CreateGraphDto dto, Guid currentUserId) + { + var graph = new Graph + { + Id = Guid.NewGuid(), + UserId = currentUserId, // Secure: always force authenticated user ID + Title = dto.Title, + Description = dto.Description, + CreatedAt = DateTime.UtcNow + }; + + var created = await _repo.CreateAsync(graph); + + await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated"); + + var result = MapToDto(created); + result.IsShared = false; + result.Permission = "Owner"; + return result; + } + + public async Task UpdateAsync(Guid id, UpdateGraphDto dto, Guid currentUserId) + { + var graph = await _repo.GetByIdAsync(id); + if (graph is null) return null; + + // Secure: only allowed for owner or edit shared users + if (graph.UserId != currentUserId) + { + var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId); + if (shared is null || shared.Permission != "Edit") return null; + } + + if (dto.Title is not null) graph.Title = dto.Title; + if (dto.Description is not null) graph.Description = dto.Description; + + var updated = await _repo.UpdateAsync(graph); + var result = MapToDto(updated); + if (graph.UserId != currentUserId) + { + result.IsShared = true; + result.Permission = "Edit"; + } + return result; + } + + public async Task DeleteAsync(Guid id, Guid currentUserId) + { + var graph = await _repo.GetByIdAsync(id); + if (graph == null) return false; + + // Secure: only owner can delete the graph + if (graph.UserId != currentUserId) return false; + + var deleted = await _repo.DeleteAsync(id); + if (deleted) + { + await _achievementService.ProcessEventAsync(graph.UserId, "GraphDeleted"); + } + return deleted; + } + + public async Task SaveFullGraphAsync(Guid id, FullGraphResponseDto dto, Guid currentUserId) + { + var graph = await _repo.GetByIdWithDetailsAsync(id); + if (graph is null) return false; + + // Secure: only allowed for owner or shared users with Edit permission + if (graph.UserId != currentUserId) + { + var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId); + if (shared is null || shared.Permission != "Edit") return false; + } + + // Map DTOs to Domain Entities + var mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode + { + Id = nodeDto.Id == Guid.Empty ? Guid.NewGuid() : nodeDto.Id, + GraphId = id, + Label = nodeDto.Label, + PosX = nodeDto.PosX, + PosY = nodeDto.PosY, + Type = nodeDto.Type, + Decision = nodeDto.Decision, + State = (FlowAPI.Domain.Enums.NodeState)nodeDto.State + }).ToList(); + + var mappedEdges = dto.Edges.Select(edgeDto => new Edge + { + FromNodeId = edgeDto.FromNodeId, + ToNodeId = edgeDto.ToNodeId, + Condition = Enum.TryParse(edgeDto.Condition, true, out var cond) ? cond : FlowAPI.Domain.Enums.EdgeCondition.True + }).ToList(); + + // Calculate deltas for achievements + var oldNodes = graph.Nodes ?? new List(); + var oldEdges = graph.Edges ?? new List(); + + int newlyCreatedNodes = mappedNodes.Count(n => !oldNodes.Any(o => o.Id == n.Id)); + int newlyCreatedEdges = mappedEdges.Count(e => !oldEdges.Any(o => o.Id == e.Id)); + + int newlyCompletedNodes = mappedNodes.Count(n => + n.State == FlowAPI.Domain.Enums.NodeState.Done && + (!oldNodes.Any(o => o.Id == n.Id) || oldNodes.First(o => o.Id == n.Id).State != FlowAPI.Domain.Enums.NodeState.Done) + ); + + // Perform robust Upsert + var success = await _repo.UpsertFullGraphAsync(id, mappedNodes, mappedEdges); + if (!success) return false; + + // Trigger Achievements based on deltas + if (newlyCreatedNodes > 0) await _achievementService.ProcessEventAsync(graph.UserId, "NodeCreated", newlyCreatedNodes); + if (newlyCreatedEdges > 0) await _achievementService.ProcessEventAsync(graph.UserId, "EdgeCreated", newlyCreatedEdges); + if (newlyCompletedNodes > 0) await _achievementService.ProcessEventAsync(graph.UserId, "TaskCompleted", newlyCompletedNodes); + + return true; + } + + public async Task ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto) + { + var graph = await _repo.GetByIdAsync(graphId); + if (graph is null || graph.UserId != ownerId) return null; + + var targetUser = await _userRepo.GetByEmailAsync(dto.Email.ToLower().Trim()); + if (targetUser is null || targetUser.Id == ownerId) return null; + + var existing = await _sharedGraphRepo.GetShareAsync(graphId, targetUser.Id); + if (existing is not null) + { + existing.Permission = dto.Permission; + await _sharedGraphRepo.UpdateAsync(existing); + } + else + { + var share = new SharedGraph + { + Id = Guid.NewGuid(), + GraphId = graphId, + SharedWithUserId = targetUser.Id, + Permission = dto.Permission, + CreatedAt = DateTime.UtcNow + }; + await _sharedGraphRepo.CreateAsync(share); + } + + var res = MapToDto(graph); + res.IsShared = true; + res.Permission = dto.Permission; + return res; + } + + public async Task> GetSharedUsersAsync(Guid graphId, Guid ownerId) + { + var graph = await _repo.GetByIdAsync(graphId); + if (graph is null || graph.UserId != ownerId) return Enumerable.Empty(); + + var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId); + + return shares.Select(s => new SharedUserResponseDto + { + Id = s.Id, + SharedWithUserId = s.SharedWithUserId, + Email = s.SharedWithUser?.Email ?? string.Empty, + DisplayName = s.SharedWithUser?.DisplayName ?? string.Empty, + Permission = s.Permission + }); + } + + public async Task RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId) + { + var graph = await _repo.GetByIdAsync(graphId); + if (graph is null || graph.UserId != ownerId) return false; + + var share = await _sharedGraphRepo.GetByIdAsync(shareId); + if (share is null || share.GraphId != graphId) return false; + + return await _sharedGraphRepo.DeleteAsync(shareId); + } + + private static GraphResponseDto MapToDto(Graph graph) => new() + { + Id = graph.Id, + UserId = graph.UserId, + Title = graph.Title, + Description = graph.Description, + CreatedAt = graph.CreatedAt + }; + } +} diff --git a/FlowAPI.Application/Services/HabitService.cs b/FlowAPI.Application/Services/HabitService.cs new file mode 100644 index 0000000000000000000000000000000000000000..227c01ac451edf60d726309318e790f39b91e32d --- /dev/null +++ b/FlowAPI.Application/Services/HabitService.cs @@ -0,0 +1,85 @@ +using FlowAPI.Application.DTOs.Habit; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Services +{ + public class HabitService : IHabitService + { + private readonly IHabitRecordRepository _repo; + private readonly IAchievementService _achievementService; + + public HabitService(IHabitRecordRepository repo, IAchievementService achievementService) + { + _repo = repo; + _achievementService = achievementService; + } + + public async Task> GetAllByUserIdAsync(Guid userId) + { + var records = await _repo.GetAllByUserIdAsync(userId); + return records.Select(MapToDto); + } + + public async Task RecordHabitAsync(CreateHabitRecordDto dto) + { + var existing = await _repo.GetTodayRecordAsync(dto.UserId, dto.HabitName); + if (existing is not null) return MapToDto(existing); + + var record = new HabitRecord + { + Id = Guid.NewGuid(), + UserId = dto.UserId, + HabitName = dto.HabitName, + CheckedDate = DateTime.UtcNow + }; + + var created = await _repo.CreateAsync(record); + + await _achievementService.ProcessEventAsync(dto.UserId, "HabitTracked"); + + return MapToDto(created); + } + + public async Task GetStreakAsync(Guid userId, string habitName) + { + var records = await _repo.GetAllByUserIdAsync(userId); + var habitRecords = records + .Where(r => r.HabitName == habitName) + .OrderByDescending(r => r.CheckedDate) + .ToList(); + + if (!habitRecords.Any()) return 0; + + int streak = 0; + DateTime expectedDate = DateTime.UtcNow.Date; + + foreach (var record in habitRecords) + { + if (record.CheckedDate.Date == expectedDate) + { + streak++; + expectedDate = expectedDate.AddDays(-1); + } + else if (record.CheckedDate.Date > expectedDate) + { + continue; + } + else + { + break; + } + } + + return streak; + } + + private static HabitRecordResponseDto MapToDto(HabitRecord record) => new() + { + Id = record.Id, + UserId = record.UserId, + HabitName = record.HabitName, + CheckedDate = record.CheckedDate + }; + } +} diff --git a/FlowAPI.Application/Services/PaymentService.cs b/FlowAPI.Application/Services/PaymentService.cs new file mode 100644 index 0000000000000000000000000000000000000000..b6b6d33539b8233520862a627a77a54f8adc513d --- /dev/null +++ b/FlowAPI.Application/Services/PaymentService.cs @@ -0,0 +1,61 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using Microsoft.Extensions.Configuration; + +namespace FlowAPI.Application.Services +{ + public class PaymentService : IPaymentService + { + private readonly IUserRepository _userRepo; + private readonly IConfiguration _config; + + public PaymentService(IUserRepository userRepo, IConfiguration config) + { + _userRepo = userRepo; + _config = config; + } + + public async Task CreateCheckoutSessionAsync(Guid userId) + { + // Implementation with Stripe.net: + // var options = new SessionCreateOptions { ... }; + // var service = new SessionService(); + // var session = await service.CreateAsync(options); + // return session.Url; + + return "https://checkout.stripe.com/pay/cs_test_placeholder_" + userId; + } + + public async Task HandleWebhookAsync(string payload, string signature) + { + try + { + // In real app, we'd verify the signature: + // var stripeEvent = EventUtility.ConstructEvent(payload, signature, _config["Stripe:WebhookSecret"]); + + // if (stripeEvent.Type == Events.CheckoutSessionCompleted) + // { + // var session = stripeEvent.Data.Object as Session; + // var userId = Guid.Parse(session.ClientReferenceId); + // await UpgradeUserToPremium(userId); + // } + + return true; + } + catch + { + return false; + } + } + + private async Task UpgradeUserToPremium(Guid userId) + { + var user = await _userRepo.GetByIdAsync(userId); + if (user != null) + { + user.IsPremium = true; + await _userRepo.UpdateAsync(user); + } + } + } +} diff --git a/FlowAPI.Application/Services/SyncService.cs b/FlowAPI.Application/Services/SyncService.cs new file mode 100644 index 0000000000000000000000000000000000000000..c22eb7bb04beaf6059e8fff0930de8dd2cb622a7 --- /dev/null +++ b/FlowAPI.Application/Services/SyncService.cs @@ -0,0 +1,95 @@ +using FlowAPI.Application.DTOs.Sync; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Services +{ + public class SyncService : ISyncService + { + private readonly ITaskNodeRepository _nodeRepo; + private readonly IEdgeRepository _edgeRepo; + + public SyncService(ITaskNodeRepository nodeRepo, IEdgeRepository edgeRepo) + { + _nodeRepo = nodeRepo; + _edgeRepo = edgeRepo; + } + + public async Task SyncChangesAsync(Guid userId, SyncRequestDto request) + { + try + { + // 1. Process Node Deletions + foreach (var id in request.DeletedNodeIds) + { + await _nodeRepo.DeleteAsync(id); + } + + // 2. Process Edge Deletions + foreach (var id in request.DeletedEdgeIds) + { + await _edgeRepo.DeleteAsync(id); + } + + // 3. Process New Nodes + foreach (var dto in request.NewNodes) + { + var node = new TaskNode + { + Id = Guid.NewGuid(), + GraphId = dto.GraphId, + Label = dto.Label, + PosX = dto.PosX, + PosY = dto.PosY, + State = dto.State + }; + await _nodeRepo.CreateAsync(node); + } + + // 4. Process Updated Nodes + foreach (var dto in request.UpdatedNodes) + { + var node = await _nodeRepo.GetByIdAsync(dto.Id); + if (node != null) + { + if (dto.Label != null) node.Label = dto.Label; + if (dto.PosX.HasValue) node.PosX = dto.PosX.Value; + if (dto.PosY.HasValue) node.PosY = dto.PosY.Value; + if (dto.State.HasValue) node.State = dto.State.Value; + await _nodeRepo.UpdateAsync(node); + } + } + + // 5. Process New Edges + foreach (var dto in request.NewEdges) + { + var edge = new Edge + { + Id = Guid.NewGuid(), + GraphId = dto.GraphId, + FromNodeId = dto.FromNodeId, + ToNodeId = dto.ToNodeId, + Condition = dto.Condition + }; + await _edgeRepo.CreateAsync(edge); + } + + return new SyncResponseDto + { + Success = true, + Message = "Synchronization completed successfully.", + ServerTime = DateTime.UtcNow + }; + } + catch (Exception ex) + { + return new SyncResponseDto + { + Success = false, + Message = $"Sync failed: {ex.Message}", + ServerTime = DateTime.UtcNow + }; + } + } + } +} diff --git a/FlowAPI.Application/Services/TaskNodeService.cs b/FlowAPI.Application/Services/TaskNodeService.cs new file mode 100644 index 0000000000000000000000000000000000000000..0e3a7ac5e21058759f25473db7b8706c6d8e47fb --- /dev/null +++ b/FlowAPI.Application/Services/TaskNodeService.cs @@ -0,0 +1,80 @@ +using FlowAPI.Application.DTOs.TaskNode; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; + +namespace FlowAPI.Application.Services +{ + public class TaskNodeService : ITaskNodeService + { + private readonly ITaskNodeRepository _repo; + + public TaskNodeService(ITaskNodeRepository repo) + { + _repo = repo; + } + + public async Task> GetAllByGraphIdAsync(Guid graphId) + { + var nodes = await _repo.GetAllByGraphIdAsync(graphId); + return nodes.Select(MapToDto); + } + + public async Task GetByIdAsync(Guid id) + { + var node = await _repo.GetByIdAsync(id); + return node is null ? null : MapToDto(node); + } + + public async Task CreateAsync(CreateTaskNodeDto dto) + { + if (dto.Label.Length > 30) + throw new ArgumentException("Label cannot exceed 30 characters."); + + var node = new TaskNode + { + Id = Guid.NewGuid(), + GraphId = dto.GraphId, + Label = dto.Label, + PosX = dto.PosX, + PosY = dto.PosY, + State = dto.State + }; + + var created = await _repo.CreateAsync(node); + return MapToDto(created); + } + + public async Task UpdateAsync(Guid id, UpdateTaskNodeDto dto) + { + var node = await _repo.GetByIdAsync(id); + if (node is null) return null; + + if (dto.Label is not null) + { + if (dto.Label.Length > 30) throw new ArgumentException("Label cannot exceed 30 characters."); + node.Label = dto.Label; + } + if (dto.PosX.HasValue) node.PosX = dto.PosX.Value; + if (dto.PosY.HasValue) node.PosY = dto.PosY.Value; + if (dto.State.HasValue) node.State = dto.State.Value; + + var updated = await _repo.UpdateAsync(node); + return MapToDto(updated); + } + + public async Task DeleteAsync(Guid id) + { + return await _repo.DeleteAsync(id); + } + + private static TaskNodeResponseDto MapToDto(TaskNode node) => new() + { + Id = node.Id, + GraphId = node.GraphId, + Label = node.Label, + PosX = node.PosX, + PosY = node.PosY, + State = node.State + }; + } +} diff --git a/FlowAPI.Application/Services/TokenService.cs b/FlowAPI.Application/Services/TokenService.cs new file mode 100644 index 0000000000000000000000000000000000000000..0eb60cb4fa4195c3f189ad3f7bd1e3007fc8d0e7 --- /dev/null +++ b/FlowAPI.Application/Services/TokenService.cs @@ -0,0 +1,49 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; + +namespace FlowAPI.Application.Services +{ + public class TokenService : ITokenService + { + private readonly SymmetricSecurityKey _key; + private readonly IConfiguration _config; + + public TokenService(IConfiguration config) + { + _config = config; + var secretKey = _config["Jwt:Key"] ?? throw new ArgumentNullException("Jwt:Key is missing in configuration."); + _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); + } + + public string CreateToken(User user) + { + var claims = new List + { + new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()), + new Claim(JwtRegisteredClaimNames.Email, user.Email), + new Claim("displayName", user.DisplayName) + }; + + var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256Signature); + + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(claims), + Expires = DateTime.Now.AddDays(double.Parse(_config["Jwt:ExpiryDays"] ?? "14")), + SigningCredentials = creds, + Issuer = _config["Jwt:Issuer"], + Audience = _config["Jwt:Audience"] + }; + + var tokenHandler = new JwtSecurityTokenHandler(); + var token = tokenHandler.CreateToken(tokenDescriptor); + + return tokenHandler.WriteToken(token); + } + } +} diff --git a/FlowAPI.Application/Services/UserService.cs b/FlowAPI.Application/Services/UserService.cs new file mode 100644 index 0000000000000000000000000000000000000000..87fcd9a227fcc560ce32d3e2ab48664c2560012f --- /dev/null +++ b/FlowAPI.Application/Services/UserService.cs @@ -0,0 +1,146 @@ +using System.Security.Cryptography; +using System.Text; +using FlowAPI.Application.DTOs.User; +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using Microsoft.Extensions.Configuration; + +namespace FlowAPI.Application.Services +{ + public class UserService : IUserService + { + private readonly IUserRepository _repo; + private readonly ITokenService _tokenService; + private readonly IConfiguration _config; + private readonly IAchievementService _achievementService; + + public UserService(IUserRepository repo, ITokenService tokenService, IConfiguration config, IAchievementService achievementService) + { + _repo = repo; + _tokenService = tokenService; + _config = config; + _achievementService = achievementService; + } + + public async Task> GetAllAsync() + { + var users = await _repo.GetAllAsync(); + return users.Select(MapToDto); + } + + public async Task GetByIdAsync(Guid id) + { + var user = await _repo.GetByIdAsync(id); + return user is null ? null : MapToDto(user); + } + + public async Task RegisterAsync(CreateUserDto dto) + { + var existing = await _repo.GetByEmailAsync(dto.Email); + if (existing is not null) + throw new InvalidOperationException("User with this email already exists."); + + var user = new User + { + Id = Guid.NewGuid(), + Email = dto.Email, + PasswordHash = HashPassword(dto.Password), + DisplayName = dto.DisplayName, + CreatedAt = DateTime.UtcNow + }; + + var created = await _repo.CreateAsync(user); + return new AuthResponseDto + { + User = MapToDto(created), + Token = _tokenService.CreateToken(created) + }; + } + + public async Task LoginAsync(LoginDto dto) + { + var user = await _repo.GetByEmailAsync(dto.Email); + if (user is null || string.IsNullOrEmpty(user.PasswordHash) || user.PasswordHash != HashPassword(dto.Password)) + return null; + + return new AuthResponseDto + { + User = MapToDto(user), + Token = _tokenService.CreateToken(user) + }; + } + + public async Task GoogleLoginAsync(GoogleLoginDto dto) + { + var settings = new Google.Apis.Auth.GoogleJsonWebSignature.ValidationSettings + { + Audience = new List { _config["Google:ClientId"]! } + }; + + var payload = await Google.Apis.Auth.GoogleJsonWebSignature.ValidateAsync(dto.IdToken, settings); + + var user = await _repo.GetByEmailAsync(payload.Email); + + if (user == null) + { + user = new User + { + Id = Guid.NewGuid(), + Email = payload.Email, + DisplayName = payload.Name, + CreatedAt = DateTime.UtcNow, + PasswordHash = "" // No password for Google users + }; + user = await _repo.CreateAsync(user); + } + + return new AuthResponseDto + { + User = MapToDto(user), + Token = _tokenService.CreateToken(user) + }; + } + + public async Task UpdateAsync(Guid id, UpdateUserDto dto) + { + var user = await _repo.GetByIdAsync(id); + if (user is null) return null; + + bool isAvatarUpdated = dto.AvatarUrl is not null && user.AvatarUrl != dto.AvatarUrl; + + if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName; + if (dto.IsPremium.HasValue) user.IsPremium = dto.IsPremium.Value; + if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl; + + var updated = await _repo.UpdateAsync(user); + + if (isAvatarUpdated) + { + await _achievementService.ProcessEventAsync(id, "AvatarUploaded"); + } + + return MapToDto(updated); + } + + public async Task DeleteAsync(Guid id) + { + return await _repo.DeleteAsync(id); + } + + private static string HashPassword(string password) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(password)); + return Convert.ToBase64String(bytes); + } + + private static UserResponseDto MapToDto(User user) => new() + { + Id = user.Id, + Email = user.Email, + DisplayName = user.DisplayName, + IsPremium = user.IsPremium, + AvatarUrl = user.AvatarUrl, + CreatedAt = user.CreatedAt + }; + } +} diff --git a/FlowAPI.Domain/Entities/Achievement.cs b/FlowAPI.Domain/Entities/Achievement.cs new file mode 100644 index 0000000000000000000000000000000000000000..48640d203b4df6e2f8b9e1719c885d5d07bbe174 --- /dev/null +++ b/FlowAPI.Domain/Entities/Achievement.cs @@ -0,0 +1,23 @@ +using System; +using FlowAPI.Domain.Enums; + +namespace FlowAPI.Domain.Entities +{ + public class Achievement + { + public Guid Id { get; set; } + + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string IconUrl { get; set; } = string.Empty; + + public string Category { get; set; } = string.Empty; + public AchievementType Type { get; set; } + public int TargetValue { get; set; } + public int RewardPoints { get; set; } + + // This tells the backend what event triggers this achievement + // e.g. "NodeCreated", "HabitCompleted", "EdgeCreated", "GraphDeleted" + public string TriggerEventName { get; set; } = string.Empty; + } +} diff --git a/FlowAPI.Domain/Entities/Edge.cs b/FlowAPI.Domain/Entities/Edge.cs new file mode 100644 index 0000000000000000000000000000000000000000..bfb98326f1a30b56a28412913f636c4405734790 --- /dev/null +++ b/FlowAPI.Domain/Entities/Edge.cs @@ -0,0 +1,18 @@ +using FlowAPI.Domain.Enums; + +namespace FlowAPI.Domain.Entities +{ + public class Edge + { + public Guid Id { get; set; } + public Guid GraphId { get; set; } + public Guid FromNodeId { get; set; } + public Guid ToNodeId { get; set; } + public EdgeCondition Condition { get; set; } = EdgeCondition.True; + + // Navigation properties + public Graph Graph { get; set; } = null!; + public TaskNode FromNode { get; set; } = null!; + public TaskNode ToNode { get; set; } = null!; + } +} diff --git a/FlowAPI.Domain/Entities/Graph.cs b/FlowAPI.Domain/Entities/Graph.cs new file mode 100644 index 0000000000000000000000000000000000000000..c6ebf1f4693ef80d05f07304aa40dd3409aba357 --- /dev/null +++ b/FlowAPI.Domain/Entities/Graph.cs @@ -0,0 +1,18 @@ +namespace FlowAPI.Domain.Entities +{ + public class Graph + { + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Title { get; set; } = string.Empty; + public string? Description { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + // Navigation properties + public User User { get; set; } = null!; + public ICollection Nodes { get; set; } = new List(); + public ICollection Edges { get; set; } = new List(); + public ICollection SharedGraphs { get; set; } = new List(); + } +} diff --git a/FlowAPI.Domain/Entities/HabitRecord.cs b/FlowAPI.Domain/Entities/HabitRecord.cs new file mode 100644 index 0000000000000000000000000000000000000000..ff98bc0bbb0a913cd2bf1a652d0fb2c983afd683 --- /dev/null +++ b/FlowAPI.Domain/Entities/HabitRecord.cs @@ -0,0 +1,14 @@ +namespace FlowAPI.Domain.Entities +{ + public class HabitRecord + { + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string HabitName { get; set; } = string.Empty; + public DateTime CheckedDate { get; set; } + public int StreakCount { get; set; } + + // Navigation properties + public User User { get; set; } = null!; + } +} diff --git a/FlowAPI.Domain/Entities/SharedGraph.cs b/FlowAPI.Domain/Entities/SharedGraph.cs new file mode 100644 index 0000000000000000000000000000000000000000..7754e0897da91e2dc93b569e17bee8c08cdd6c10 --- /dev/null +++ b/FlowAPI.Domain/Entities/SharedGraph.cs @@ -0,0 +1,17 @@ +using System; + +namespace FlowAPI.Domain.Entities +{ + public class SharedGraph + { + public Guid Id { get; set; } + public Guid GraphId { get; set; } + public Guid SharedWithUserId { get; set; } + public string Permission { get; set; } = "Read"; // "Read" or "Edit" + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + // Navigation properties + public Graph Graph { get; set; } = null!; + public User SharedWithUser { get; set; } = null!; + } +} diff --git a/FlowAPI.Domain/Entities/TaskNode.cs b/FlowAPI.Domain/Entities/TaskNode.cs new file mode 100644 index 0000000000000000000000000000000000000000..582d13e8ec8d52af5a171b75e7e928f2c3214310 --- /dev/null +++ b/FlowAPI.Domain/Entities/TaskNode.cs @@ -0,0 +1,22 @@ +using FlowAPI.Domain.Enums; + +namespace FlowAPI.Domain.Entities +{ + public class TaskNode + { + public Guid Id { get; set; } + public Guid GraphId { get; set; } + public string Label { get; set; } = string.Empty; + public double PosX { get; set; } + public double PosY { get; set; } + public string Type { get; set; } = "sketch"; + public string? Decision { get; set; } + public NodeState State { get; set; } = NodeState.Pending; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + // Navigation properties + public Graph Graph { get; set; } = null!; + public ICollection OutgoingEdges { get; set; } = new List(); + public ICollection IncomingEdges { get; set; } = new List(); + } +} diff --git a/FlowAPI.Domain/Entities/User.cs b/FlowAPI.Domain/Entities/User.cs new file mode 100644 index 0000000000000000000000000000000000000000..94cf93f2d58b38ebcf01bbec3218d7f2256c89ad --- /dev/null +++ b/FlowAPI.Domain/Entities/User.cs @@ -0,0 +1,19 @@ +namespace FlowAPI.Domain.Entities +{ + public class User + { + public Guid Id { get; set; } + public string Email { get; set; } = string.Empty; + public string PasswordHash { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public bool IsPremium { get; set; } + public string? AvatarUrl { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + // Navigation properties + public ICollection Graphs { get; set; } = new List(); + public ICollection HabitRecords { get; set; } = new List(); + public ICollection UserAchievements { get; set; } = new List(); + public ICollection SharedGraphs { get; set; } = new List(); + } +} diff --git a/FlowAPI.Domain/Entities/UserAchievement.cs b/FlowAPI.Domain/Entities/UserAchievement.cs new file mode 100644 index 0000000000000000000000000000000000000000..608b8589427f8d884d02705abed63dd131e8587d --- /dev/null +++ b/FlowAPI.Domain/Entities/UserAchievement.cs @@ -0,0 +1,19 @@ +using System; + +namespace FlowAPI.Domain.Entities +{ + public class UserAchievement + { + public Guid Id { get; set; } + + public Guid UserId { get; set; } + public User? User { get; set; } + + public Guid AchievementId { get; set; } + public Achievement? Achievement { get; set; } + + public int CurrentValue { get; set; } + public bool IsUnlocked { get; set; } + public DateTime? UnlockedAt { get; set; } + } +} diff --git a/FlowAPI.Domain/Enums/AchievementType.cs b/FlowAPI.Domain/Enums/AchievementType.cs new file mode 100644 index 0000000000000000000000000000000000000000..7b8f86f63e5137644b78bff06d7ea15a1869bcac --- /dev/null +++ b/FlowAPI.Domain/Enums/AchievementType.cs @@ -0,0 +1,8 @@ +namespace FlowAPI.Domain.Enums +{ + public enum AchievementType + { + SingleAction, + Accumulative + } +} diff --git a/FlowAPI.Domain/Enums/EdgeCondition.cs b/FlowAPI.Domain/Enums/EdgeCondition.cs new file mode 100644 index 0000000000000000000000000000000000000000..a6524b3db50ce68ed5a367fd3a457f170031435d --- /dev/null +++ b/FlowAPI.Domain/Enums/EdgeCondition.cs @@ -0,0 +1,11 @@ +namespace FlowAPI.Domain.Enums +{ + public enum EdgeCondition + { + True, + False, + Blocked, + SubgoalLeft, + SubgoalRight + } +} diff --git a/FlowAPI.Domain/Enums/NodeState.cs b/FlowAPI.Domain/Enums/NodeState.cs new file mode 100644 index 0000000000000000000000000000000000000000..6a472cfd746f3bcc5a31ef2e1be0c07ef5322b8c --- /dev/null +++ b/FlowAPI.Domain/Enums/NodeState.cs @@ -0,0 +1,9 @@ +namespace FlowAPI.Domain.Enums +{ + public enum NodeState + { + Pending, + Blocked, + Done + } +} diff --git a/FlowAPI.Domain/FlowAPI.Domain.csproj b/FlowAPI.Domain/FlowAPI.Domain.csproj new file mode 100644 index 0000000000000000000000000000000000000000..93f5ab4b4be59c29a8e94839f2f895d1a70183cd --- /dev/null +++ b/FlowAPI.Domain/FlowAPI.Domain.csproj @@ -0,0 +1,9 @@ + + + + net10.0 + enable + enable + + + diff --git a/FlowAPI.Infrastructure/Data/AppDbContext.cs b/FlowAPI.Infrastructure/Data/AppDbContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..2db8051381c70e2e5cb629bf99993bdbad6f09a2 --- /dev/null +++ b/FlowAPI.Infrastructure/Data/AppDbContext.cs @@ -0,0 +1,143 @@ +using FlowAPI.Domain.Entities; +using FlowAPI.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Data +{ + public class AppDbContext : DbContext + { + public AppDbContext(DbContextOptions options) : base(options) { } + + public DbSet Users => Set(); + public DbSet Graphs => Set(); + public DbSet TaskNodes => Set(); + public DbSet Edges => Set(); + public DbSet HabitRecords => Set(); + public DbSet Achievements => Set(); + public DbSet UserAchievements => Set(); + public DbSet SharedGraphs => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + // User + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.HasIndex(e => e.Email).IsUnique(); + entity.Property(e => e.Email).IsRequired().HasMaxLength(256); + entity.Property(e => e.PasswordHash).IsRequired(); + entity.Property(e => e.DisplayName).HasMaxLength(100); + }); + + // Graph + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Title).IsRequired().HasMaxLength(200); + entity.Property(e => e.Description).HasMaxLength(1000); + + entity.HasOne(e => e.User) + .WithMany(u => u.Graphs) + .HasForeignKey(e => e.UserId) + .OnDelete(DeleteBehavior.Cascade); + }); + + // TaskNode + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Label).IsRequired().HasMaxLength(30); + entity.Property(e => e.State) + .HasConversion() + .HasDefaultValue(NodeState.Pending); + entity.Property(e => e.Type).HasMaxLength(50).HasDefaultValue("sketch"); + entity.Property(e => e.Decision).HasMaxLength(50); + + entity.HasOne(e => e.Graph) + .WithMany(g => g.Nodes) + .HasForeignKey(e => e.GraphId) + .OnDelete(DeleteBehavior.Cascade); + }); + + // Edge + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Condition).HasMaxLength(50); + + entity.HasOne(e => e.Graph) + .WithMany(g => g.Edges) + .HasForeignKey(e => e.GraphId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasOne(e => e.FromNode) + .WithMany(n => n.OutgoingEdges) + .HasForeignKey(e => e.FromNodeId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasOne(e => e.ToNode) + .WithMany(n => n.IncomingEdges) + .HasForeignKey(e => e.ToNodeId) + .OnDelete(DeleteBehavior.Cascade); + }); + + // HabitRecord + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.HabitName).IsRequired().HasMaxLength(100); + + entity.HasOne(e => e.User) + .WithMany(u => u.HabitRecords) + .HasForeignKey(e => e.UserId) + .OnDelete(DeleteBehavior.Cascade); + }); + + // Achievement + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Title).IsRequired().HasMaxLength(200); + entity.Property(e => e.Category).HasMaxLength(100); + entity.Property(e => e.TriggerEventName).HasMaxLength(100); + }); + + // UserAchievement + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + + entity.HasOne(e => e.User) + .WithMany(u => u.UserAchievements) + .HasForeignKey(e => e.UserId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasOne(e => e.Achievement) + .WithMany() + .HasForeignKey(e => e.AchievementId) + .OnDelete(DeleteBehavior.Cascade); + }); + + // SharedGraph + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Permission).IsRequired().HasMaxLength(50).HasDefaultValue("Read"); + + entity.HasOne(e => e.Graph) + .WithMany(g => g.SharedGraphs) + .HasForeignKey(e => e.GraphId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasOne(e => e.SharedWithUser) + .WithMany(u => u.SharedGraphs) + .HasForeignKey(e => e.SharedWithUserId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasIndex(e => new { e.GraphId, e.SharedWithUserId }).IsUnique(); + }); + } + } +} diff --git a/FlowAPI.Infrastructure/FlowAPI.Infrastructure.csproj b/FlowAPI.Infrastructure/FlowAPI.Infrastructure.csproj new file mode 100644 index 0000000000000000000000000000000000000000..20a7270c6e901e8aebcb64b3fa01328ea1bc794f --- /dev/null +++ b/FlowAPI.Infrastructure/FlowAPI.Infrastructure.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.Designer.cs b/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..b6c36c659cad4a71a3f796e63d2c0bce3283e187 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.Designer.cs @@ -0,0 +1,275 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260516181908_InitialWithDecision")] + partial class InitialWithDecision + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.cs b/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b132c1a9786961905c401d32b886c5982d3859b --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260516181908_InitialWithDecision.cs @@ -0,0 +1,187 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + /// + public partial class InitialWithDecision : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Email = table.Column(type: "TEXT", maxLength: 256, nullable: false), + PasswordHash = table.Column(type: "TEXT", nullable: false), + DisplayName = table.Column(type: "TEXT", maxLength: 100, nullable: false), + IsPremium = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Graphs", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Graphs", x => x.Id); + table.ForeignKey( + name: "FK_Graphs_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "HabitRecords", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + HabitName = table.Column(type: "TEXT", maxLength: 100, nullable: false), + CheckedDate = table.Column(type: "TEXT", nullable: false), + StreakCount = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_HabitRecords", x => x.Id); + table.ForeignKey( + name: "FK_HabitRecords_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TaskNodes", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + GraphId = table.Column(type: "TEXT", nullable: false), + Label = table.Column(type: "TEXT", maxLength: 30, nullable: false), + PosX = table.Column(type: "REAL", nullable: false), + PosY = table.Column(type: "REAL", nullable: false), + Type = table.Column(type: "TEXT", maxLength: 50, nullable: false, defaultValue: "sketch"), + Decision = table.Column(type: "TEXT", maxLength: 50, nullable: true), + State = table.Column(type: "TEXT", nullable: false, defaultValue: "Pending"), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TaskNodes", x => x.Id); + table.ForeignKey( + name: "FK_TaskNodes_Graphs_GraphId", + column: x => x.GraphId, + principalTable: "Graphs", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Edges", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + GraphId = table.Column(type: "TEXT", nullable: false), + FromNodeId = table.Column(type: "TEXT", nullable: false), + ToNodeId = table.Column(type: "TEXT", nullable: false), + Condition = table.Column(type: "INTEGER", maxLength: 50, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Edges", x => x.Id); + table.ForeignKey( + name: "FK_Edges_Graphs_GraphId", + column: x => x.GraphId, + principalTable: "Graphs", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Edges_TaskNodes_FromNodeId", + column: x => x.FromNodeId, + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_Edges_TaskNodes_ToNodeId", + column: x => x.ToNodeId, + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "IX_Edges_FromNodeId", + table: "Edges", + column: "FromNodeId"); + + migrationBuilder.CreateIndex( + name: "IX_Edges_GraphId", + table: "Edges", + column: "GraphId"); + + migrationBuilder.CreateIndex( + name: "IX_Edges_ToNodeId", + table: "Edges", + column: "ToNodeId"); + + migrationBuilder.CreateIndex( + name: "IX_Graphs_UserId", + table: "Graphs", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_HabitRecords_UserId", + table: "HabitRecords", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_TaskNodes_GraphId", + table: "TaskNodes", + column: "GraphId"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Email", + table: "Users", + column: "Email", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Edges"); + + migrationBuilder.DropTable( + name: "HabitRecords"); + + migrationBuilder.DropTable( + name: "TaskNodes"); + + migrationBuilder.DropTable( + name: "Graphs"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.Designer.cs b/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..ef87bf25bc4af710900746a71bad2aa1b56fcec4 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.Designer.cs @@ -0,0 +1,275 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260516202912_AddCascadeDeleteForEdges")] + partial class AddCascadeDeleteForEdges + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.cs b/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.cs new file mode 100644 index 0000000000000000000000000000000000000000..03c7e6050c85de43f1c11d0174e1593afc52b101 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260516202912_AddCascadeDeleteForEdges.cs @@ -0,0 +1,66 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + /// + public partial class AddCascadeDeleteForEdges : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Edges_TaskNodes_FromNodeId", + table: "Edges"); + + migrationBuilder.DropForeignKey( + name: "FK_Edges_TaskNodes_ToNodeId", + table: "Edges"); + + migrationBuilder.AddForeignKey( + name: "FK_Edges_TaskNodes_FromNodeId", + table: "Edges", + column: "FromNodeId", + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_Edges_TaskNodes_ToNodeId", + table: "Edges", + column: "ToNodeId", + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Edges_TaskNodes_FromNodeId", + table: "Edges"); + + migrationBuilder.DropForeignKey( + name: "FK_Edges_TaskNodes_ToNodeId", + table: "Edges"); + + migrationBuilder.AddForeignKey( + name: "FK_Edges_TaskNodes_FromNodeId", + table: "Edges", + column: "FromNodeId", + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Edges_TaskNodes_ToNodeId", + table: "Edges", + column: "ToNodeId", + principalTable: "TaskNodes", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.Designer.cs b/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..5c249faf592c63ba0f3888330777c9a86c0ce0d8 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.Designer.cs @@ -0,0 +1,369 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260517135820_Achievements")] + partial class Achievements + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Achievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IconUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RewardPoints") + .HasColumnType("INTEGER"); + + b.Property("TargetValue") + .HasColumnType("INTEGER"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("TriggerEventName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("Achievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AchievementId") + .HasColumnType("TEXT"); + + b.Property("CurrentValue") + .HasColumnType("INTEGER"); + + b.Property("IsUnlocked") + .HasColumnType("INTEGER"); + + b.Property("UnlockedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AchievementId"); + + b.HasIndex("UserId"); + + b.ToTable("UserAchievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.HasOne("FlowAPI.Domain.Entities.Achievement", "Achievement") + .WithMany() + .HasForeignKey("AchievementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("UserAchievements") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Achievement"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + + b.Navigation("UserAchievements"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.cs b/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.cs new file mode 100644 index 0000000000000000000000000000000000000000..38bdec4baa95d071d1ca2b7b476a01909ffa6c57 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260517135820_Achievements.cs @@ -0,0 +1,82 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + /// + public partial class Achievements : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Achievements", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Description = table.Column(type: "TEXT", nullable: false), + IconUrl = table.Column(type: "TEXT", nullable: false), + Category = table.Column(type: "TEXT", maxLength: 100, nullable: false), + Type = table.Column(type: "INTEGER", nullable: false), + TargetValue = table.Column(type: "INTEGER", nullable: false), + RewardPoints = table.Column(type: "INTEGER", nullable: false), + TriggerEventName = table.Column(type: "TEXT", maxLength: 100, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Achievements", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "UserAchievements", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + AchievementId = table.Column(type: "TEXT", nullable: false), + CurrentValue = table.Column(type: "INTEGER", nullable: false), + IsUnlocked = table.Column(type: "INTEGER", nullable: false), + UnlockedAt = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserAchievements", x => x.Id); + table.ForeignKey( + name: "FK_UserAchievements_Achievements_AchievementId", + column: x => x.AchievementId, + principalTable: "Achievements", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserAchievements_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserAchievements_AchievementId", + table: "UserAchievements", + column: "AchievementId"); + + migrationBuilder.CreateIndex( + name: "IX_UserAchievements_UserId", + table: "UserAchievements", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserAchievements"); + + migrationBuilder.DropTable( + name: "Achievements"); + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.Designer.cs b/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..ce712f52ca665635e3c47f8d3e414a10f887655b --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.Designer.cs @@ -0,0 +1,372 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260517154225_AddAvatarUrl")] + partial class AddAvatarUrl + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Achievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IconUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RewardPoints") + .HasColumnType("INTEGER"); + + b.Property("TargetValue") + .HasColumnType("INTEGER"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("TriggerEventName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("Achievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AvatarUrl") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AchievementId") + .HasColumnType("TEXT"); + + b.Property("CurrentValue") + .HasColumnType("INTEGER"); + + b.Property("IsUnlocked") + .HasColumnType("INTEGER"); + + b.Property("UnlockedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AchievementId"); + + b.HasIndex("UserId"); + + b.ToTable("UserAchievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.HasOne("FlowAPI.Domain.Entities.Achievement", "Achievement") + .WithMany() + .HasForeignKey("AchievementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("UserAchievements") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Achievement"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + + b.Navigation("UserAchievements"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.cs b/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.cs new file mode 100644 index 0000000000000000000000000000000000000000..a612b4d10c8bc563d5aa2b5607344b4cdc5bf789 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260517154225_AddAvatarUrl.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + /// + public partial class AddAvatarUrl : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AvatarUrl", + table: "Users", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "AvatarUrl", + table: "Users"); + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.Designer.cs b/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..56dd95e8632d3e40dfe84b13ff34fc47f2b7a86b --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.Designer.cs @@ -0,0 +1,427 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260518170308_AddSharedGraphs")] + partial class AddSharedGraphs + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Achievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IconUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RewardPoints") + .HasColumnType("INTEGER"); + + b.Property("TargetValue") + .HasColumnType("INTEGER"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("TriggerEventName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("Achievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Permission") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("Read"); + + b.Property("SharedWithUserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("SharedWithUserId"); + + b.HasIndex("GraphId", "SharedWithUserId") + .IsUnique(); + + b.ToTable("SharedGraphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AvatarUrl") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AchievementId") + .HasColumnType("TEXT"); + + b.Property("CurrentValue") + .HasColumnType("INTEGER"); + + b.Property("IsUnlocked") + .HasColumnType("INTEGER"); + + b.Property("UnlockedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AchievementId"); + + b.HasIndex("UserId"); + + b.ToTable("UserAchievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("SharedGraphs") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "SharedWithUser") + .WithMany("SharedGraphs") + .HasForeignKey("SharedWithUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + + b.Navigation("SharedWithUser"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.HasOne("FlowAPI.Domain.Entities.Achievement", "Achievement") + .WithMany() + .HasForeignKey("AchievementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("UserAchievements") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Achievement"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + + b.Navigation("SharedGraphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + + b.Navigation("SharedGraphs"); + + b.Navigation("UserAchievements"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.cs b/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed90e476d3480673f38d424b66137d55b7efdb9e --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/20260518170308_AddSharedGraphs.cs @@ -0,0 +1,60 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + /// + public partial class AddSharedGraphs : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "SharedGraphs", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + GraphId = table.Column(type: "TEXT", nullable: false), + SharedWithUserId = table.Column(type: "TEXT", nullable: false), + Permission = table.Column(type: "TEXT", maxLength: 50, nullable: false, defaultValue: "Read"), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_SharedGraphs", x => x.Id); + table.ForeignKey( + name: "FK_SharedGraphs_Graphs_GraphId", + column: x => x.GraphId, + principalTable: "Graphs", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_SharedGraphs_Users_SharedWithUserId", + column: x => x.SharedWithUserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_SharedGraphs_GraphId_SharedWithUserId", + table: "SharedGraphs", + columns: new[] { "GraphId", "SharedWithUserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_SharedGraphs_SharedWithUserId", + table: "SharedGraphs", + column: "SharedWithUserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SharedGraphs"); + } + } +} diff --git a/FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000000000000000000000000000000000000..f55f53123de1e33a43ec6f33c069a457b7fa1109 --- /dev/null +++ b/FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -0,0 +1,424 @@ +// +using System; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FlowAPI.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + partial class AppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.8"); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Achievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IconUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RewardPoints") + .HasColumnType("INTEGER"); + + b.Property("TargetValue") + .HasColumnType("INTEGER"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("TriggerEventName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("Achievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Condition") + .HasMaxLength(50) + .HasColumnType("INTEGER"); + + b.Property("FromNodeId") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("ToNodeId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("FromNodeId"); + + b.HasIndex("GraphId"); + + b.HasIndex("ToNodeId"); + + b.ToTable("Edges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Graphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CheckedDate") + .HasColumnType("TEXT"); + + b.Property("HabitName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("StreakCount") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("HabitRecords"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Permission") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("Read"); + + b.Property("SharedWithUserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("SharedWithUserId"); + + b.HasIndex("GraphId", "SharedWithUserId") + .IsUnique(); + + b.ToTable("SharedGraphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Decision") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.Property("GraphId") + .HasColumnType("TEXT"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("TEXT"); + + b.Property("PosX") + .HasColumnType("REAL"); + + b.Property("PosY") + .HasColumnType("REAL"); + + b.Property("State") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasDefaultValue("Pending"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasDefaultValue("sketch"); + + b.HasKey("Id"); + + b.HasIndex("GraphId"); + + b.ToTable("TaskNodes"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AvatarUrl") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsPremium") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AchievementId") + .HasColumnType("TEXT"); + + b.Property("CurrentValue") + .HasColumnType("INTEGER"); + + b.Property("IsUnlocked") + .HasColumnType("INTEGER"); + + b.Property("UnlockedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AchievementId"); + + b.HasIndex("UserId"); + + b.ToTable("UserAchievements"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => + { + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode") + .WithMany("OutgoingEdges") + .HasForeignKey("FromNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Edges") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode") + .WithMany("IncomingEdges") + .HasForeignKey("ToNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("FromNode"); + + b.Navigation("Graph"); + + b.Navigation("ToNode"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("Graphs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => + { + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("HabitRecords") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("SharedGraphs") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "SharedWithUser") + .WithMany("SharedGraphs") + .HasForeignKey("SharedWithUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + + b.Navigation("SharedWithUser"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph") + .WithMany("Nodes") + .HasForeignKey("GraphId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Graph"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => + { + b.HasOne("FlowAPI.Domain.Entities.Achievement", "Achievement") + .WithMany() + .HasForeignKey("AchievementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FlowAPI.Domain.Entities.User", "User") + .WithMany("UserAchievements") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Achievement"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b => + { + b.Navigation("Edges"); + + b.Navigation("Nodes"); + + b.Navigation("SharedGraphs"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b => + { + b.Navigation("IncomingEdges"); + + b.Navigation("OutgoingEdges"); + }); + + modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => + { + b.Navigation("Graphs"); + + b.Navigation("HabitRecords"); + + b.Navigation("SharedGraphs"); + + b.Navigation("UserAchievements"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/AchievementRepository.cs b/FlowAPI.Infrastructure/Repositories/AchievementRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..5a09db4823b13464a684d6987326b2b2ac18bfef --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/AchievementRepository.cs @@ -0,0 +1,33 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class AchievementRepository : GenericRepository, IAchievementRepository + { + public AchievementRepository(AppDbContext context) : base(context) + { + } + + public async Task> GetByTriggerEventAsync(string eventName) + { + return await _dbSet.Where(a => a.TriggerEventName == eventName).ToListAsync(); + } + + public async Task> GetByTitlesAsync(IEnumerable titles) + { + return await _dbSet.Where(a => titles.Contains(a.Title)).ToListAsync(); + } + + public async Task AddRangeAsync(IEnumerable achievements) + { + await _dbSet.AddRangeAsync(achievements); + await _context.SaveChangesAsync(); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/EdgeRepository.cs b/FlowAPI.Infrastructure/Repositories/EdgeRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..d6f3c2c5537caad55aadc89bd15b1c15b4251cc0 --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/EdgeRepository.cs @@ -0,0 +1,20 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class EdgeRepository : GenericRepository, IEdgeRepository + { + public EdgeRepository(AppDbContext context) : base(context) { } + + public async Task> GetAllByGraphIdAsync(Guid graphId) + { + return await _dbSet + .Where(e => e.GraphId == graphId) + .AsNoTracking() + .ToListAsync(); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/GenericRepository.cs b/FlowAPI.Infrastructure/Repositories/GenericRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..edca0c85f44e61603097349deed62ed8bc0f86ea --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/GenericRepository.cs @@ -0,0 +1,52 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class GenericRepository : IGenericRepository where T : class + { + protected readonly AppDbContext _context; + protected readonly DbSet _dbSet; + + public GenericRepository(AppDbContext context) + { + _context = context; + _dbSet = context.Set(); + } + + public virtual async Task> GetAllAsync() + { + return await _dbSet.AsNoTracking().ToListAsync(); + } + + public virtual async Task GetByIdAsync(Guid id) + { + return await _dbSet.FindAsync(id); + } + + public virtual async Task CreateAsync(T entity) + { + _dbSet.Add(entity); + await _context.SaveChangesAsync(); + return entity; + } + + public virtual async Task UpdateAsync(T entity) + { + _dbSet.Update(entity); + await _context.SaveChangesAsync(); + return entity; + } + + public virtual async Task DeleteAsync(Guid id) + { + var entity = await _dbSet.FindAsync(id); + if (entity is null) return false; + + _dbSet.Remove(entity); + await _context.SaveChangesAsync(); + return true; + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/GraphRepository.cs b/FlowAPI.Infrastructure/Repositories/GraphRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..4e36f0c83b2b713898e276a21e50508e019369d7 --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/GraphRepository.cs @@ -0,0 +1,134 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class GraphRepository : GenericRepository, IGraphRepository + { + public GraphRepository(AppDbContext context) : base(context) { } + + public async Task> GetAllByUserIdAsync(Guid userId) + { + return await _dbSet + .Where(g => g.UserId == userId) + .Include(g => g.Nodes) + .Include(g => g.Edges) + .AsNoTracking() + .ToListAsync(); + } + + public async Task GetByIdWithDetailsAsync(Guid id) + { + return await _dbSet + .Include(g => g.Nodes) + .Include(g => g.Edges) + .FirstOrDefaultAsync(g => g.Id == id); + } + + public async Task ClearDetailsAsync(Guid id) + { + var graph = await _dbSet + .Include(g => g.Nodes) + .Include(g => g.Edges) + .FirstOrDefaultAsync(g => g.Id == id); + + if (graph != null) + { + if (graph.Edges.Any()) + { + _context.Edges.RemoveRange(graph.Edges); + } + if (graph.Nodes.Any()) + { + _context.TaskNodes.RemoveRange(graph.Nodes); + } + await _context.SaveChangesAsync(); + } + } + + public async Task UpsertFullGraphAsync(Guid graphId, IEnumerable nodes, IEnumerable edges) + { + var graph = await _dbSet + .Include(g => g.Nodes) + .Include(g => g.Edges) + .FirstOrDefaultAsync(g => g.Id == graphId); + + if (graph == null) return false; + + var existingNodes = graph.Nodes.ToList(); + var incomingNodes = nodes.ToList(); + var existingEdges = graph.Edges.ToList(); + var incomingEdges = edges.ToList(); + + // 1. Identify nodes and edges to delete + var nodesToDelete = existingNodes.Where(e => !incomingNodes.Any(i => i.Id == e.Id)).ToList(); + var deletedNodeIds = nodesToDelete.Select(n => n.Id).ToHashSet(); + + var edgesToDelete = existingEdges + .Where(e => !incomingEdges.Any(i => i.FromNodeId == e.FromNodeId && i.ToNodeId == e.ToNodeId) + || deletedNodeIds.Contains(e.FromNodeId) + || deletedNodeIds.Contains(e.ToNodeId)) + .ToList(); + + // 2. Perform deletes sequentially to satisfy SQLite FK constraints + if (edgesToDelete.Any()) + { + _context.Edges.RemoveRange(edgesToDelete); + await _context.SaveChangesAsync(); + } + + if (nodesToDelete.Any()) + { + _context.TaskNodes.RemoveRange(nodesToDelete); + await _context.SaveChangesAsync(); + } + + // 3. Update or Create Nodes + foreach (var node in incomingNodes) + { + var existingNode = existingNodes.FirstOrDefault(e => e.Id == node.Id); + if (existingNode != null) + { + existingNode.Label = node.Label; + existingNode.PosX = node.PosX; + existingNode.PosY = node.PosY; + existingNode.Type = node.Type; + existingNode.Decision = node.Decision; + existingNode.State = node.State; + } + else + { + node.GraphId = graphId; + _context.TaskNodes.Add(node); + } + } + + // 4. Update or Create Edges + foreach (var edge in incomingEdges) + { + // Only create edge if it wasn't deleted in step 2 (i.e. not connected to a deleted node) + if (deletedNodeIds.Contains(edge.FromNodeId) || deletedNodeIds.Contains(edge.ToNodeId)) + { + continue; + } + + var existingEdge = existingEdges.FirstOrDefault(e => e.FromNodeId == edge.FromNodeId && e.ToNodeId == edge.ToNodeId); + if (existingEdge != null) + { + existingEdge.Condition = edge.Condition; + } + else + { + edge.Id = Guid.NewGuid(); + edge.GraphId = graphId; + _context.Edges.Add(edge); + } + } + + await _context.SaveChangesAsync(); + return true; + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/HabitRecordRepository.cs b/FlowAPI.Infrastructure/Repositories/HabitRecordRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..c1912949cdf027cc954872cc64404e2526dd5644 --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/HabitRecordRepository.cs @@ -0,0 +1,31 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class HabitRecordRepository : GenericRepository, IHabitRecordRepository + { + public HabitRecordRepository(AppDbContext context) : base(context) { } + + public async Task> GetAllByUserIdAsync(Guid userId) + { + return await _dbSet + .Where(r => r.UserId == userId) + .OrderByDescending(r => r.CheckedDate) + .AsNoTracking() + .ToListAsync(); + } + + public async Task GetTodayRecordAsync(Guid userId, string habitName) + { + var today = DateTime.UtcNow.Date; + return await _dbSet + .FirstOrDefaultAsync(r => + r.UserId == userId && + r.HabitName == habitName && + r.CheckedDate.Date == today); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/SharedGraphRepository.cs b/FlowAPI.Infrastructure/Repositories/SharedGraphRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..280f4c47f388ea751d1a6e075449f028b1c59ed1 --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/SharedGraphRepository.cs @@ -0,0 +1,38 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class SharedGraphRepository : GenericRepository, ISharedGraphRepository + { + public SharedGraphRepository(AppDbContext context) : base(context) { } + + public async Task> GetSharedGraphsByUserIdAsync(Guid userId) + { + return await _dbSet + .Include(s => s.Graph) + .Where(s => s.SharedWithUserId == userId) + .ToListAsync(); + } + + public async Task GetShareAsync(Guid graphId, Guid sharedWithUserId) + { + return await _dbSet + .FirstOrDefaultAsync(s => s.GraphId == graphId && s.SharedWithUserId == sharedWithUserId); + } + + public async Task> GetSharesForGraphAsync(Guid graphId) + { + return await _dbSet + .Include(s => s.SharedWithUser) + .Where(s => s.GraphId == graphId) + .ToListAsync(); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/TaskNodeRepository.cs b/FlowAPI.Infrastructure/Repositories/TaskNodeRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc660e7c4ba4d2e3c4eeefbaf26ff6e18a72fd35 --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/TaskNodeRepository.cs @@ -0,0 +1,20 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class TaskNodeRepository : GenericRepository, ITaskNodeRepository + { + public TaskNodeRepository(AppDbContext context) : base(context) { } + + public async Task> GetAllByGraphIdAsync(Guid graphId) + { + return await _dbSet + .Where(n => n.GraphId == graphId) + .AsNoTracking() + .ToListAsync(); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/UserAchievementRepository.cs b/FlowAPI.Infrastructure/Repositories/UserAchievementRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..31fcd4e0200258489b9d9227bd62407c5d5a053f --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/UserAchievementRepository.cs @@ -0,0 +1,33 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class UserAchievementRepository : GenericRepository, IUserAchievementRepository + { + public UserAchievementRepository(AppDbContext context) : base(context) + { + } + + public async Task> GetByUserIdAsync(Guid userId) + { + return await _dbSet + .Include(ua => ua.Achievement) + .Where(ua => ua.UserId == userId) + .ToListAsync(); + } + + public async Task> GetByUserAndAchievementIdsAsync(Guid userId, IEnumerable achievementIds) + { + return await _dbSet + .Where(ua => ua.UserId == userId && achievementIds.Contains(ua.AchievementId)) + .ToListAsync(); + } + } +} diff --git a/FlowAPI.Infrastructure/Repositories/UserRepository.cs b/FlowAPI.Infrastructure/Repositories/UserRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..be24983b6fe37d64dac4f7815164e37d8b31a0be --- /dev/null +++ b/FlowAPI.Infrastructure/Repositories/UserRepository.cs @@ -0,0 +1,17 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Domain.Entities; +using FlowAPI.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI.Infrastructure.Repositories +{ + public class UserRepository : GenericRepository, IUserRepository + { + public UserRepository(AppDbContext context) : base(context) { } + + public async Task GetByEmailAsync(string email) + { + return await _dbSet.FirstOrDefaultAsync(u => u.Email == email); + } + } +} diff --git a/FlowAPI.slnx b/FlowAPI.slnx new file mode 100644 index 0000000000000000000000000000000000000000..f55b54509a4f8a82277214c2ca94053337c143f9 --- /dev/null +++ b/FlowAPI.slnx @@ -0,0 +1,6 @@ + + + + + + diff --git a/FlowAPI/Controllers/AIController.cs b/FlowAPI/Controllers/AIController.cs new file mode 100644 index 0000000000000000000000000000000000000000..348336752de2f3fb80c74889db2b916176356a03 --- /dev/null +++ b/FlowAPI/Controllers/AIController.cs @@ -0,0 +1,65 @@ +using FlowAPI.Application.DTOs.AI; +using FlowAPI.Application.DTOs.Graph; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class AIController : ControllerBase + { + private readonly IAIService _aiService; + + public AIController(IAIService aiService) + { + _aiService = aiService; + } + + [HttpPost("generate-alternative")] + public async Task> GenerateAlternative([FromBody] GenerateAlternativeRequestDto request) + { + try + { + var response = await _aiService.GenerateAlternativePathAsync(request); + return Ok(response); + } + catch (UnauthorizedAccessException) + { + return StatusCode(403, new { message = "Premium subscription required for AI generation." }); + } + catch (Exception ex) + { + return BadRequest(new { message = ex.Message }); + } + } + + [HttpPost("generate-goal")] + public async Task> GenerateGoal([FromBody] GenerateGoalGraphRequestDto request) + { + try + { + var response = await _aiService.GenerateGoalGraphAsync(request); + return Ok(response); + } + catch (Exception ex) + { + return BadRequest(new { message = ex.Message }); + } + } + + [HttpPost("assist")] + public async Task> CanvasAssist([FromBody] AICanvasAssistRequestDto request) + { + try + { + var response = await _aiService.CanvasAssistAsync(request); + return Ok(response); + } + catch (Exception ex) + { + return BadRequest(new { message = ex.Message }); + } + } + } +} diff --git a/FlowAPI/Controllers/AchievementsController.cs b/FlowAPI/Controllers/AchievementsController.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b717c24f28fc5b23297d515b18e26c283898f0e --- /dev/null +++ b/FlowAPI/Controllers/AchievementsController.cs @@ -0,0 +1,57 @@ +using FlowAPI.Application.DTOs; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + [Authorize] + public class AchievementsController : ControllerBase + { + private readonly IAchievementService _achievementService; + + public AchievementsController(IAchievementService achievementService) + { + _achievementService = achievementService; + } + + [HttpGet("progress")] + public async Task>> GetUserProgress() + { + var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (!Guid.TryParse(userIdStr, out var userId)) + return Unauthorized(); + + var progress = await _achievementService.GetUserAchievementsAsync(userId); + return Ok(progress); + } + + [HttpPost("seed")] + [AllowAnonymous] // Allowing anonymous for easy dev setup. Can be secured later. + public async Task SeedAchievements() + { + await _achievementService.SeedAchievementsAsync(); + return Ok(new { message = "Achievements seeded successfully." }); + } + + [HttpPost("trigger")] + public async Task TriggerEvent([FromBody] TriggerEventRequest request) + { + var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (!Guid.TryParse(userIdStr, out var userId)) + return Unauthorized(); + + await _achievementService.ProcessEventAsync(userId, request.EventName, request.Amount); + return Ok(new { message = "Event processed." }); + } + } + + public class TriggerEventRequest + { + public string EventName { get; set; } = string.Empty; + public int Amount { get; set; } = 1; + } +} diff --git a/FlowAPI/Controllers/EdgesController.cs b/FlowAPI/Controllers/EdgesController.cs new file mode 100644 index 0000000000000000000000000000000000000000..417b4ce0e030687658c313b16552b3fcd9268bc1 --- /dev/null +++ b/FlowAPI/Controllers/EdgesController.cs @@ -0,0 +1,55 @@ +using FlowAPI.Application.DTOs.Edge; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class EdgesController : ControllerBase + { + private readonly IEdgeService _service; + + public EdgesController(IEdgeService service) + { + _service = service; + } + + [HttpGet("graph/{graphId:guid}")] + public async Task>> GetAllByGraphId(Guid graphId) + { + var edges = await _service.GetAllByGraphIdAsync(graphId); + return Ok(edges); + } + + [HttpGet("{id:guid}")] + public async Task> GetById(Guid id) + { + var edge = await _service.GetByIdAsync(id); + if (edge is null) return NotFound(); + return Ok(edge); + } + + [HttpPost] + public async Task> Create([FromBody] CreateEdgeDto dto) + { + try + { + var edge = await _service.CreateAsync(dto); + return CreatedAtAction(nameof(GetById), new { id = edge.Id }, edge); + } + catch (ArgumentException ex) + { + return BadRequest(new { message = ex.Message }); + } + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + var result = await _service.DeleteAsync(id); + if (!result) return NotFound(); + return NoContent(); + } + } +} diff --git a/FlowAPI/Controllers/GraphsController.cs b/FlowAPI/Controllers/GraphsController.cs new file mode 100644 index 0000000000000000000000000000000000000000..3e29c65b7e4ca6eeb274621ddd2f3079b9e37ade --- /dev/null +++ b/FlowAPI/Controllers/GraphsController.cs @@ -0,0 +1,131 @@ +using FlowAPI.Application.DTOs.Graph; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Authorize] + [Route("api/[controller]")] + public class GraphsController : ControllerBase + { + private readonly IGraphService _service; + + public GraphsController(IGraphService service) + { + _service = service; + } + + private Guid CurrentUserId + { + get + { + var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userIdStr, out var userId) ? userId : Guid.Empty; + } + } + + [HttpGet("user/{userId:guid}")] + public async Task>> GetAllByUserId(Guid userId) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + if (userId != CurrentUserId) return Forbid(); + + var graphs = await _service.GetAllByUserIdAsync(userId); + return Ok(graphs); + } + + [HttpGet("{id:guid}")] + public async Task> GetById(Guid id) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var graph = await _service.GetByIdAsync(id, CurrentUserId); + if (graph is null) return NotFound(); + return Ok(graph); + } + + [HttpGet("{id:guid}/full")] + public async Task> GetFullById(Guid id) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var graph = await _service.GetFullByIdAsync(id, CurrentUserId); + if (graph is null) return NotFound(); + return Ok(graph); + } + + [HttpPost] + public async Task> Create([FromBody] CreateGraphDto dto) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var graph = await _service.CreateAsync(dto, CurrentUserId); + return CreatedAtAction(nameof(GetById), new { id = graph.Id }, graph); + } + + [HttpPut("{id:guid}")] + public async Task> Update(Guid id, [FromBody] UpdateGraphDto dto) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var graph = await _service.UpdateAsync(id, dto, CurrentUserId); + if (graph is null) return NotFound(); + return Ok(graph); + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var result = await _service.DeleteAsync(id, CurrentUserId); + if (!result) return NotFound(); + return NoContent(); + } + + [HttpPost("{id:guid}/full")] + public async Task SaveFull(Guid id, [FromBody] FullGraphResponseDto dto) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var result = await _service.SaveFullGraphAsync(id, dto, CurrentUserId); + if (!result) return NotFound(); + return Ok(); + } + + [HttpPost("{id:guid}/share")] + public async Task> Share(Guid id, [FromBody] ShareGraphRequestDto dto) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var result = await _service.ShareGraphAsync(id, CurrentUserId, dto); + if (result is null) return BadRequest("Не вдалося поділитися дошкою. Перевірте email або права."); + return Ok(result); + } + + [HttpGet("{id:guid}/shares")] + public async Task>> GetShares(Guid id) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var result = await _service.GetSharedUsersAsync(id, CurrentUserId); + return Ok(result); + } + + [HttpDelete("{id:guid}/shares/{shareId:guid}")] + public async Task RevokeShare(Guid id, Guid shareId) + { + if (CurrentUserId == Guid.Empty) return Unauthorized(); + + var result = await _service.RevokeShareAsync(id, CurrentUserId, shareId); + if (!result) return NotFound(); + return NoContent(); + } + } +} diff --git a/FlowAPI/Controllers/HabitsController.cs b/FlowAPI/Controllers/HabitsController.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed816d61f137d6f76942e7016c5b96a9ab5af4b5 --- /dev/null +++ b/FlowAPI/Controllers/HabitsController.cs @@ -0,0 +1,39 @@ +using FlowAPI.Application.DTOs.Habit; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class HabitsController : ControllerBase + { + private readonly IHabitService _service; + + public HabitsController(IHabitService service) + { + _service = service; + } + + [HttpGet("user/{userId:guid}")] + public async Task>> GetAllByUserId(Guid userId) + { + var habits = await _service.GetAllByUserIdAsync(userId); + return Ok(habits); + } + + [HttpPost("record")] + public async Task> Record([FromBody] CreateHabitRecordDto dto) + { + var record = await _service.RecordHabitAsync(dto); + return Ok(record); + } + + [HttpGet("streak/{userId:guid}/{habitName}")] + public async Task> GetStreak(Guid userId, string habitName) + { + var streak = await _service.GetStreakAsync(userId, habitName); + return Ok(streak); + } + } +} diff --git a/FlowAPI/Controllers/PaymentsController.cs b/FlowAPI/Controllers/PaymentsController.cs new file mode 100644 index 0000000000000000000000000000000000000000..d2b0321427251f6ecc984f357862f9009219cc47 --- /dev/null +++ b/FlowAPI/Controllers/PaymentsController.cs @@ -0,0 +1,35 @@ +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class PaymentsController : ControllerBase + { + private readonly IPaymentService _paymentService; + + public PaymentsController(IPaymentService paymentService) + { + _paymentService = paymentService; + } + + [HttpPost("create-checkout-session/{userId:guid}")] + public async Task> CreateCheckoutSession(Guid userId) + { + var url = await _paymentService.CreateCheckoutSessionAsync(userId); + return Ok(new { checkoutUrl = url }); + } + + [HttpPost("webhook")] + public async Task Webhook() + { + var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); + var signature = Request.Headers["Stripe-Signature"]; + + var result = await _paymentService.HandleWebhookAsync(json, signature!); + if (result) return Ok(); + return BadRequest(); + } + } +} diff --git a/FlowAPI/Controllers/SyncController.cs b/FlowAPI/Controllers/SyncController.cs new file mode 100644 index 0000000000000000000000000000000000000000..ba6fa6c1af342622e5bf6bf53cf5c5bfce94c6b0 --- /dev/null +++ b/FlowAPI/Controllers/SyncController.cs @@ -0,0 +1,201 @@ +using FlowAPI.Application.DTOs.Sync; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class SyncController : ControllerBase + { + private readonly ISyncService _syncService; + + // In-memory store for WebRTC: ProjectId -> List of signals + private static readonly ConcurrentDictionary> Signals = new(); + + // In-memory store for WebRTC: ProjectId -> (UserId -> Presence Info) + private static readonly ConcurrentDictionary> Presence = new(); + + public SyncController(ISyncService syncService) + { + _syncService = syncService; + } + + private Guid CurrentUserId + { + get + { + var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userIdStr, out var userId) ? userId : Guid.Empty; + } + } + + private string CurrentUserEmail => User.FindFirst(ClaimTypes.Email)?.Value ?? "unknown@user.com"; + private string CurrentUserName => User.FindFirst("name")?.Value ?? User.FindFirst(ClaimTypes.Name)?.Value ?? "Collaborator"; + + [HttpPost("{userId:guid}")] + public async Task> Sync(Guid userId, [FromBody] SyncRequestDto request) + { + var response = await _syncService.SyncChangesAsync(userId, request); + return Ok(response); + } + + // --- WebRTC Real-time Presence --- + [Authorize] + [HttpPost("{projectId}/presence")] + public IActionResult RegisterPresence(string projectId) + { + var userId = CurrentUserId; + if (userId == Guid.Empty) return Unauthorized(); + + var projectPresence = Presence.GetOrAdd(projectId, _ => new ConcurrentDictionary()); + + var info = new WebRTCPresence + { + UserId = userId.ToString(), + Email = CurrentUserEmail, + Name = CurrentUserName, + LastSeen = DateTime.UtcNow + }; + + projectPresence[userId.ToString()] = info; + + // Prune expired presence (older than 10 seconds) + var now = DateTime.UtcNow; + foreach (var key in projectPresence.Keys) + { + if (projectPresence.TryGetValue(key, out var presenceInfo) && (now - presenceInfo.LastSeen).TotalSeconds > 10) + { + projectPresence.TryRemove(key, out _); + } + } + + return Ok(new { success = true }); + } + + [Authorize] + [HttpGet("{projectId}/presence")] + public IActionResult GetPresence(string projectId) + { + var userId = CurrentUserId; + if (userId == Guid.Empty) return Unauthorized(); + + if (!Presence.TryGetValue(projectId, out var projectPresence)) + { + return Ok(Array.Empty()); + } + + // Prune expired presence and return active users + var now = DateTime.UtcNow; + var activeUsers = new List(); + + foreach (var item in projectPresence.Values) + { + if ((now - item.LastSeen).TotalSeconds <= 10) + { + activeUsers.Add(item); + } + else + { + projectPresence.TryRemove(item.UserId, out _); + } + } + + return Ok(activeUsers); + } + + // --- WebRTC Real-time Signaling --- + [Authorize] + [HttpPost("{projectId}/signal")] + public IActionResult SendSignal(string projectId, [FromBody] WebRTCSignalDto dto) + { + var userId = CurrentUserId; + if (userId == Guid.Empty) return Unauthorized(); + + var message = new WebRTCSignal + { + SenderId = userId.ToString(), + ReceiverId = dto.ReceiverId, + Type = dto.Type, + Data = dto.Data, + Timestamp = DateTime.UtcNow + }; + + var queue = Signals.GetOrAdd(projectId, _ => new ConcurrentQueue()); + queue.Enqueue(message); + + // Cap the queue at 100 entries per project + while (queue.Count > 100) + { + queue.TryDequeue(out _); + } + + return Ok(new { success = true }); + } + + [Authorize] + [HttpGet("{projectId}/signal")] + public IActionResult GetSignals(string projectId) + { + var userId = CurrentUserId; + if (userId == Guid.Empty) return Unauthorized(); + + var queue = Signals.GetOrAdd(projectId, _ => new ConcurrentQueue()); + + var mySignals = new List(); + var tempQueue = new List(); + + while (queue.TryDequeue(out var msg)) + { + // If it is for me and is not older than 1 minute + if (msg.ReceiverId == userId.ToString() && (DateTime.UtcNow - msg.Timestamp).TotalSeconds < 60) + { + mySignals.Add(msg); + } + else if ((DateTime.UtcNow - msg.Timestamp).TotalSeconds < 60) + { + // Requeue other people's fresh messages + tempQueue.Add(msg); + } + } + + foreach (var msg in tempQueue) + { + queue.Enqueue(msg); + } + + return Ok(mySignals); + } + } + + public class WebRTCSignalDto + { + public string ReceiverId { get; set; } + public string Type { get; set; } // "offer", "answer", "candidate" + public string Data { get; set; } + } + + public class WebRTCSignal + { + public string SenderId { get; set; } + public string ReceiverId { get; set; } + public string Type { get; set; } + public string Data { get; set; } + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + } + + public class WebRTCPresence + { + public string UserId { get; set; } + public string Email { get; set; } + public string Name { get; set; } + public DateTime LastSeen { get; set; } = DateTime.UtcNow; + } +} diff --git a/FlowAPI/Controllers/TaskNodesController.cs b/FlowAPI/Controllers/TaskNodesController.cs new file mode 100644 index 0000000000000000000000000000000000000000..bf0cc7a00730d8485e3a4df7a9ac5af6937155ac --- /dev/null +++ b/FlowAPI/Controllers/TaskNodesController.cs @@ -0,0 +1,63 @@ +using FlowAPI.Application.DTOs.TaskNode; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class TaskNodesController : ControllerBase + { + private readonly ITaskNodeService _service; + + public TaskNodesController(ITaskNodeService service) + { + _service = service; + } + + [HttpGet("graph/{graphId:guid}")] + public async Task>> GetAllByGraphId(Guid graphId) + { + var nodes = await _service.GetAllByGraphIdAsync(graphId); + return Ok(nodes); + } + + [HttpGet("{id:guid}")] + public async Task> GetById(Guid id) + { + var node = await _service.GetByIdAsync(id); + if (node is null) return NotFound(); + return Ok(node); + } + + [HttpPost] + public async Task> Create([FromBody] CreateTaskNodeDto dto) + { + try + { + var node = await _service.CreateAsync(dto); + return CreatedAtAction(nameof(GetById), new { id = node.Id }, node); + } + catch (ArgumentException ex) + { + return BadRequest(new { message = ex.Message }); + } + } + + [HttpPut("{id:guid}")] + public async Task> Update(Guid id, [FromBody] UpdateTaskNodeDto dto) + { + var node = await _service.UpdateAsync(id, dto); + if (node is null) return NotFound(); + return Ok(node); + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + var result = await _service.DeleteAsync(id); + if (!result) return NotFound(); + return NoContent(); + } + } +} diff --git a/FlowAPI/Controllers/UsersController.cs b/FlowAPI/Controllers/UsersController.cs new file mode 100644 index 0000000000000000000000000000000000000000..e1b5de994ce1e7663e5436f3e9c9ab7539b6a5e7 --- /dev/null +++ b/FlowAPI/Controllers/UsersController.cs @@ -0,0 +1,103 @@ +using FlowAPI.Application.DTOs.User; +using FlowAPI.Application.Interfaces; +using Microsoft.AspNetCore.Mvc; + +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; + +namespace FlowAPI.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class UsersController : ControllerBase + { + private readonly IUserService _service; + + public UsersController(IUserService service) + { + _service = service; + } + + [Authorize] + [HttpGet("me")] + public async Task> GetProfile() + { + var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (string.IsNullOrEmpty(userIdStr) || !Guid.TryParse(userIdStr, out var userId)) + { + return Unauthorized(); + } + + var user = await _service.GetByIdAsync(userId); + if (user is null) return NotFound(); + return Ok(user); + } + + [HttpGet] + public async Task>> GetAll() + { + var users = await _service.GetAllAsync(); + return Ok(users); + } + + [HttpGet("{id:guid}")] + public async Task> GetById(Guid id) + { + var user = await _service.GetByIdAsync(id); + if (user is null) return NotFound(); + return Ok(user); + } + + [HttpPost("register")] + public async Task> Register([FromBody] CreateUserDto dto) + { + try + { + var response = await _service.RegisterAsync(dto); + return Ok(response); + } + catch (InvalidOperationException ex) + { + return Conflict(new { message = ex.Message }); + } + } + + [HttpPost("login")] + public async Task> Login([FromBody] LoginDto dto) + { + var response = await _service.LoginAsync(dto); + if (response is null) return Unauthorized(new { message = "Invalid email or password." }); + return Ok(response); + } + + [HttpPost("google-login")] + public async Task> GoogleLogin([FromBody] GoogleLoginDto dto) + { + try + { + var response = await _service.GoogleLoginAsync(dto); + return Ok(response); + } + catch (Exception ex) + { + return BadRequest(new { message = "Google authentication failed: " + ex.Message }); + } + } + + [HttpPut("{id:guid}")] + public async Task> Update(Guid id, [FromBody] UpdateUserDto dto) + { + var user = await _service.UpdateAsync(id, dto); + if (user is null) return NotFound(); + return Ok(user); + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + var result = await _service.DeleteAsync(id); + if (!result) return NotFound(); + return NoContent(); + } + } +} diff --git a/FlowAPI/FlowAPI.csproj b/FlowAPI/FlowAPI.csproj new file mode 100644 index 0000000000000000000000000000000000000000..d95b60677bef8efc6153aa9c840deef133bd0802 --- /dev/null +++ b/FlowAPI/FlowAPI.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + enable + enable + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + diff --git a/FlowAPI/FlowAPI.http b/FlowAPI/FlowAPI.http new file mode 100644 index 0000000000000000000000000000000000000000..ca79370490e61b6f121b109d1eb6ecd64ec85d79 --- /dev/null +++ b/FlowAPI/FlowAPI.http @@ -0,0 +1,6 @@ +@FlowAPI_HostAddress = http://localhost:5181 + +GET {{FlowAPI_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/FlowAPI/Program.cs b/FlowAPI/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..e823ecb26df3f7385df7bdac0ae5a5ac128dd4b3 --- /dev/null +++ b/FlowAPI/Program.cs @@ -0,0 +1,133 @@ +using FlowAPI.Application.Interfaces; +using FlowAPI.Application.Services; +using FlowAPI.Infrastructure.Data; +using FlowAPI.Infrastructure.Repositories; +using Microsoft.EntityFrameworkCore; + +namespace FlowAPI +{ + public class Program + { + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + + // --- Database --- + builder.Services.AddDbContext(options => + options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))); + + // --- Repositories (Infrastructure) --- + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + + // --- Services (Application) --- + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + + // --- Singletons --- + builder.Services.AddSingleton(); + + // --- Authentication --- + var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new Exception("JWT Key missing"); + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtKey)), + ValidateIssuer = true, + ValidIssuer = builder.Configuration["Jwt:Issuer"], + ValidateAudience = true, + ValidAudience = builder.Configuration["Jwt:Audience"], + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }; + }); + + // --- Controllers & OpenAPI --- + builder.Services.AddControllers() + .AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add( + new System.Text.Json.Serialization.JsonStringEnumConverter()); + }); + builder.Services.AddOpenApi(); + + // --- CORS --- + builder.Services.AddCors(options => + { + options.AddPolicy("AllowAll", policy => + { + policy.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); + }); + + var app = builder.Build(); + + // --- Auto-migrate database and seed --- + using (var scope = app.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + + // Auto-seed achievements + var achievementService = scope.ServiceProvider.GetRequiredService(); + achievementService.SeedAchievementsAsync().Wait(); + } + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) + { + app.MapOpenApi(); + } + + app.UseCors("AllowAll"); + app.UseHttpsRedirection(); + + app.Use(async (context, next) => + { + context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin"); + try + { + await next(); + } + catch (IOException ex) when (ex.Message.Contains("The client reset the request stream") || + ex.Message.Contains("connection was aborted")) + { + // Silence exception when client resets the request stream (e.g. user cancels or navigates away) + } + catch (OperationCanceledException) + { + // Silence exception when request execution is cancelled (e.g. client disconnects) + } + }); + + app.UseAuthentication(); + app.UseAuthorization(); + app.MapControllers(); + + app.Run(); + } + } +} diff --git a/FlowAPI/Properties/launchSettings.json b/FlowAPI/Properties/launchSettings.json new file mode 100644 index 0000000000000000000000000000000000000000..a248d70b9cbffe47581987209f0cc5c3405376f3 --- /dev/null +++ b/FlowAPI/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5181", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7000;http://localhost:5181", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/FlowAPI/appsettings.Production.json b/FlowAPI/appsettings.Production.json new file mode 100644 index 0000000000000000000000000000000000000000..3ca13a16a4dbd7e12e454a98fd016b1cbaf02859 --- /dev/null +++ b/FlowAPI/appsettings.Production.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Data Source=/app/data/taskflow.db" + } +} diff --git a/FlowAPI/appsettings.json b/FlowAPI/appsettings.json new file mode 100644 index 0000000000000000000000000000000000000000..5a6277dafdbf9b0f1557200700a0f64a6e4d57b3 --- /dev/null +++ b/FlowAPI/appsettings.json @@ -0,0 +1,28 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "DefaultConnection": "Data Source=taskflow.db" + }, + "Jwt": { + "Key": "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#", + "Issuer": "TaskFlowAPI", + "Audience": "TaskFlowWeb", + "ExpiryDays": 14 + }, + "Google": { + "ClientId": "181646538378-kbabhecenasb8pca0uh95prhk8b0vrbr.apps.googleusercontent.com" + }, + "OpenAI": { + "ApiKey": "" + }, + "Stripe": { + "SecretKey": "", + "WebhookSecret": "" + } +} diff --git a/FlowAPI/gemini_bridge.py b/FlowAPI/gemini_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..d56abe8b9bb5e9fed07bb578d95b6b547c613430 --- /dev/null +++ b/FlowAPI/gemini_bridge.py @@ -0,0 +1,473 @@ +import sys +import json +import time +import os +import signal +import datetime +import re +import argparse +import threading +import base64 +import io +import queue +import ctypes + +# Win32 Constants +SW_HIDE = 0 +SW_SHOW = 5 +SW_MINIMIZE = 6 +SW_RESTORE = 9 + +# Add the current directory to sys.path to ensure we can import modules if needed +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +from camoufox.sync_api import Camoufox + +def log_message(message): + """Log messages to stderr and bridge_log.txt.""" + timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]") + log_line = f"{timestamp} [BRIDGE] {message}\n" + sys.stderr.write(log_line) + sys.stderr.flush() + try: + with open("bridge_log.txt", "a", encoding="utf-8") as f: + f.write(log_line) + except: + pass + +def signal_handler(sig, frame): + log_message("Received signal to exit.") + sys.exit(0) + +signal.signal(signal.SIGINT, signal_handler) +signal.signal(signal.SIGTERM, signal_handler) + +# --- Browser Logic (Adapted from gemini_agent.py) --- + +def get_message_count(page) -> int: + return page.locator('div[id^="model-response-message-content"]').count() + +def wait_for_new_response(page, previous_count: int, msg_id: str, timeout: int = 120): + log_message(f"Waiting for new response (prev count: {previous_count})...") + start = time.time() + + new_msg_detected = False + new_count = previous_count + + # 1. Wait for the new message container to appear + while time.time() - start < timeout: + try: + current_count = get_message_count(page) + if current_count > previous_count: + new_msg_detected = True + new_count = current_count + log_message(f"New message detected! Count: {previous_count} -> {current_count}") + break + except Exception: + pass + time.sleep(1) + + if not new_msg_detected: + log_message(f"TIMEOUT: No new message after {timeout}s") + return False, new_count + + log_message("Monitoring generation for streaming...") + + stable_checks = 0 + last_len = 0 + last_text = "" + + # 2. Monitor for changes (Streaming) + while time.time() - start < timeout: + try: + # Check for generating indicators (stop button, progress bar, or sparkle) + # If these are gone, generation is likely done. + generating_selectors = [ + '.mat-mdc-progress-bar', + 'mat-progress-bar', + '.loading-indicator', + 'button[aria-label*="Stop"]', + 'button[aria-label*="stop"]', + 'button[aria-label*="Cancel"]', + 'button[aria-label*="cancel"]', + 'img[src*="sparkle_thinking"]', + '.sparkle-loading' + ] + + is_generating = False + for sel in generating_selectors: + try: + if page.locator(sel).first.is_visible(): + is_generating = True + break + except: + pass + + els = page.locator('div[id^="model-response-message-content"]').all() + if not els: + time.sleep(0.5) + continue + + # Get current text of the *last* message + curr_text = els[-1].inner_text() + curr_len = len(curr_text) + + # Emit partial if changed + if curr_len > last_len: + if curr_text.startswith(last_text): + diff = curr_text[len(last_text):] + if diff: + print(json.dumps({ + "type": "partial_response", + "id": msg_id, + "content": diff + }), flush=True) + + last_text = curr_text + last_len = curr_len + stable_checks = 0 # Reset stability if text changed + + if not is_generating: + # Double check stability + if curr_len > 0 and curr_len == last_len: + stable_checks += 1 + # Robust warm-up protection: if length is very small (< 150 chars), require + # 12 stable checks (6.0 seconds of no change) before cut-off to allow the AI to think and start streaming. + # Otherwise, require 3 stable checks (1.5 seconds of no change) to finish. + required_checks = 12 if curr_len < 150 else 3 + if stable_checks >= required_checks: + log_message(f"Generation complete (indicator gone). Length: {curr_len}") + return True, new_count + else: + # Still generating, but maybe paused? + if curr_len > 0 and curr_len == last_len: + stable_checks += 1 + if stable_checks >= 10: # 5 seconds of no change even if indicator present? + pass + else: + stable_checks = 0 # Text changing, so active + + except Exception as e: + pass + + time.sleep(0.5) # Poll every 500ms + + return True, new_count + +def get_specific_response(page, index: int) -> str: + try: + els = page.locator('div[id^="model-response-message-content"]').all() + if len(els) > index: + return els[index].inner_text().strip() + elif len(els) > 0: + return els[-1].inner_text().strip() + except: + pass + return "" + +def send_gemini_message(page, message: str) -> bool: + try: + page.bring_to_front() + # Find input box + input_el = page.locator('div[contenteditable="true"]').first + if not input_el.is_visible(): + input_el = page.locator('textarea').first + + if input_el.is_visible(timeout=5000): + input_el.click() + time.sleep(0.5) + input_el.fill(message) + time.sleep(0.5) + + # Find send button + send_btn = page.locator('button[aria-label*="Send"], mat-icon[data-mat-icon-name="send"]').first + if send_btn.is_visible(): + send_btn.click() + else: + input_el.press("Enter") + + return True + else: + log_message("Input element not found!") + except Exception as e: + log_message(f"Send failed: {e}") + return False + +def send_gemini_image_message(page, message: str, image_path: str) -> (bool, str): + try: + page.bring_to_front() + + # Check if "Upload files" is already visible (menu open from previous attempt?) + upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first + if not upload_btn.is_visible(): + upload_btn = page.locator('div.menu-text:has-text("Upload files")').first + + if not upload_btn.is_visible(): + log_message("Upload button not visible, looking for Plus button...") + plus_btn = page.locator('button[aria-label*="Upload files"], button[aria-label*="Add"], button:has(mat-icon[fonticon="add"]), button:has(mat-icon[data-mat-icon-name="add"]), button:has(mat-icon[fonticon="add_circle"]), button:has(mat-icon[fonticon="add_2"]), button:has(mat-icon[data-mat-icon-name="add_2"])').first + + if plus_btn.is_visible(): + log_message(f"Clicking Plus button: {plus_btn.get_attribute('aria-label')}") + plus_btn.click() + time.sleep(1.0) # Wait for menu animation + + # Re-check upload button + upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first + if not upload_btn.is_visible(): + upload_btn = page.locator('div.menu-text:has-text("Upload files")').first + else: + log_message("Plus button not found with standard selectors.") + return False, "Plus/Add button not found" + + if upload_btn.is_visible(): + log_message("Clicking Upload files button...") + try: + with page.expect_file_chooser(timeout=5000) as fc_info: + upload_btn.click() + except Exception as e: + return False, f"Timeout waiting for file chooser: {e}" + + file_chooser = fc_info.value + log_message(f"Uploading image: {image_path}") + file_chooser.set_files(image_path) + + # Wait for upload to process. + time.sleep(4) + + if send_gemini_message(page, message): + return True, "" + else: + return False, "Failed to send text message after upload" + else: + log_message("Upload files button not found in menu!") + return False, "Upload files button not found in menu" + + except Exception as e: + log_message(f"Send image failed: {e}") + return False, f"Exception: {str(e)}" + +def get_active_page(context, url="https://gemini.google.com/app"): + """Finds an existing Gemini page or creates a new one and ensures it's navigated.""" + page = None + for p in context.pages: + try: + if not p.is_closed(): + page = p + break + except: + continue + + if not page: + log_message("No active page found, creating new one...") + page = context.new_page() + page.add_init_script("Object.defineProperty(document, 'hidden', { get: () => false });") + + try: + current_url = page.url + # If we are on Google login or account setup, DO NOT redirect/reload! + if "accounts.google" in current_url or "google.com/accounts" in current_url: + return page + + if url not in current_url: + log_message(f"Navigating to {url} (current: {current_url})...") + page.goto(url, timeout=60000) + time.sleep(2) + except Exception as e: + log_message(f"Navigation check/error: {e}") + + return page + +def stdin_reader(q): + """Reads stdin lines in a background thread and puts them in a queue.""" + while True: + line = sys.stdin.readline() + if not line: + q.put(None) + break + q.put(line) + +def set_browser_window_visibility(visible): + """Находит окно браузера и скрывает/показывает его через Win32 API""" + if sys.platform != 'win32': + return + + log_message(f"Starting window search (visibility={visible})...") + found_count = [0] + + def foreach_window(hwnd, lParam): + class_name = ctypes.create_unicode_buffer(256) + ctypes.windll.user32.GetClassNameW(hwnd, class_name, 256) + + length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) + title = "" + if length > 0: + buff = ctypes.create_unicode_buffer(length + 1) + ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) + title = buff.value + + is_browser = (class_name.value == "MozillaWindowClass") + + if is_browser: + log_message(f"Checking window: '{title}' (Class: {class_name.value})") + is_match = any(term in title for term in ["Gemini", "Camoufox", "Firefox", "Nightly", "Google"]) + if is_match or not title: + log_message(f"Found target browser window! Setting visibility: {visible}") + found_count[0] += 1 + if visible: + log_message(f"Restoring window: '{title}'") + ctypes.windll.user32.ShowWindow(hwnd, SW_RESTORE) + ctypes.windll.user32.SetForegroundWindow(hwnd) + else: + log_message(f"Minimizing window: '{title}'") + ctypes.windll.user32.ShowWindow(hwnd, SW_MINIMIZE) + return True + + enum_proc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)(foreach_window) + ctypes.windll.user32.EnumWindows(enum_proc, 0) + log_message(f"Window search finished. Found {found_count[0]} windows.") + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--headless", action="store_true", help="Run in headless mode") + args_parsed = parser.parse_args() + + # Use the profile folder relative to this script's directory + profile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gemini_profile_bridge") + + headless_to_use = args_parsed.headless + log_message(f"Starting Gemini Bridge (Headless: {headless_to_use})...") + + if not os.path.exists(profile_path): + os.makedirs(profile_path, exist_ok=True) + + log_message(f"Initializing Camoufox with profile: {profile_path}") + + try: + with Camoufox( + headless=headless_to_use, + persistent_context=True, + user_data_dir=profile_path, + viewport={'width': 1280, 'height': 1000}, + humanize=False, + geoip=False, + args=["--no-sandbox", "--disable-setuid-sandbox"] + ) as context: + + page = get_active_page(context) + + if "accounts.google.com" in page.url: + log_message("WARNING: Login required! Please log in manually in the browser window.") + + log_message("Browser ready. Waiting for input on stdin...") + print(json.dumps({"type": "ready"}), flush=True) + + input_queue = queue.Queue() + threading.Thread(target=stdin_reader, args=(input_queue,), daemon=True).start() + + def delayed_hide(): + time.sleep(3) + log_message("Attempting initial window hide...") + set_browser_window_visibility(False) + + if not headless_to_use: + threading.Thread(target=delayed_hide, daemon=True).start() + + # Screenshots disabled + + while True: + try: + while not input_queue.empty(): + line = input_queue.get_nowait() + if line is None: return + + line = line.strip() + if not line: continue + + log_message(f"Received JSON: {line[:50]}...") + try: + data = json.loads(line) + msg_type = data.get("type") + + if msg_type == "prompt" or msg_type == "prompt_with_image": + prompt, msg_id = data.get("content"), data.get("id") + image_path = data.get("image_path") + is_new_chat = data.get("new_chat", False) + + page = get_active_page(context) + + if is_new_chat: + log_message("Request implies new chat. Searching for 'New Chat' button...") + try: + new_chat_btn = page.locator('side-nav-action-button[data-test-id="new-chat-button"]').first + if new_chat_btn.is_visible(): + log_message("Clicking 'New Chat' button.") + new_chat_btn.click() + # Wait for old messages to disappear + log_message("Waiting for old messages to clear...") + start_wait = time.time() + while time.time() - start_wait < 10: + if get_message_count(page) == 0: + break + time.sleep(0.5) + time.sleep(1.0) # Additional settling time + else: + log_message("'New Chat' button not visible. Assuming already on a fresh chat.") + except Exception as e: + log_message(f"Warning: Failed to click new chat: {e}") + + initial_count = get_message_count(page) + + sent, error_msg = False, "" + if msg_type == "prompt_with_image" and image_path: + sent, error_msg = send_gemini_image_message(page, prompt, image_path) + else: + sent = send_gemini_message(page, prompt) + if not sent: error_msg = "Failed to send" + + if sent: + success, new_count = wait_for_new_response(page, initial_count, msg_id, timeout=120) + if success: + resp = get_specific_response(page, new_count - 1) + print(json.dumps({"type": "response", "id": msg_id, "status": "success", "content": resp}), flush=True) + else: + print(json.dumps({"type": "response", "id": msg_id, "status": "timeout"}), flush=True) + else: + print(json.dumps({"type": "response", "id": msg_id, "status": "error", "error": error_msg}), flush=True) + + elif msg_type == "click": + x, y = data.get("x"), data.get("y") + if x is not None and y is not None: + p = get_active_page(context) + if p: + p.bring_to_front() + p.mouse.move(x, y) + time.sleep(0.1) + p.mouse.click(x, y) + log_message(f"Hover & Click at {x}, {y}") + + elif msg_type == "set_visibility": + visible = data.get("visible", True) + set_browser_window_visibility(visible) + log_message(f"Window visibility set to: {visible}") + + elif msg_type == "ping": + print(json.dumps({"type": "pong"}), flush=True) + elif msg_type == "exit": + return + except Exception as inner_e: + log_message(f"Msg error: {inner_e}") + + # Periodic screenshot disabled + + time.sleep(0.1) + except Exception as e: + log_message(f"Loop error: {e}") + time.sleep(1) + + except Exception as e: + log_message(f"Fatal Error: {e}") + print(json.dumps({"type": "fatal_error", "error": str(e)}), flush=True) + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/FlowAPI/inspect_db.py b/FlowAPI/inspect_db.py new file mode 100644 index 0000000000000000000000000000000000000000..e57fc4e3c0120c01d2576845e9f85c2bac6419b8 --- /dev/null +++ b/FlowAPI/inspect_db.py @@ -0,0 +1,15 @@ +import sqlite3 +conn = sqlite3.connect('taskflow.db') +cursor = conn.cursor() + +print("--- All TaskNodes ---") +nodes = cursor.execute("SELECT * FROM TaskNodes").fetchall() +for n in nodes: + print(n) + +print("\n--- All Edges ---") +edges = cursor.execute("SELECT * FROM Edges").fetchall() +for e in edges: + print(e) + +conn.close() diff --git a/FlowAPI/query_achievements.py b/FlowAPI/query_achievements.py new file mode 100644 index 0000000000000000000000000000000000000000..8d32fef22fc007e06ae559c1e7d2661e81ba14fa --- /dev/null +++ b/FlowAPI/query_achievements.py @@ -0,0 +1,17 @@ +import sqlite3 +import json + +conn = sqlite3.connect('taskflow.db') +cursor = conn.cursor() + +print("--- Achievements ---") +achievements = cursor.execute("SELECT Id, Title, TargetValue FROM Achievements").fetchall() +for a in achievements: + print(a) + +print("\n--- UserAchievements ---") +user_ach = cursor.execute("SELECT Id, UserId, AchievementId, CurrentValue, IsUnlocked FROM UserAchievements").fetchall() +for ua in user_ach: + print(ua) + +conn.close()