Spaces:
Running
Running
Commit ·
b9c7f0e
1
Parent(s): 9c5dea4
init
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignoreAdded+21
- DockerfileAdded+63
- FlowAPI.Application/DTOs/AI/AIDtos.csAdded+36
- FlowAPI.Application/DTOs/AchievementDto.csAdded+17
- FlowAPI.Application/DTOs/Edge/EdgeDtos.csAdded+26
- FlowAPI.Application/DTOs/Graph/GraphDtos.csAdded+69
- FlowAPI.Application/DTOs/Habit/HabitDtos.csAdded+17
- FlowAPI.Application/DTOs/Sync/SyncDtos.csAdded+27
- FlowAPI.Application/DTOs/TaskNode/TaskNodeDtos.csAdded+32
- FlowAPI.Application/DTOs/User/UserDtos.csAdded+43
- FlowAPI.Application/DTOs/UserAchievementDto.csAdded+14
- FlowAPI.Application/FlowAPI.Application.csprojAdded+20
- FlowAPI.Application/Interfaces/IAIService.csAdded+12
- FlowAPI.Application/Interfaces/IAchievementRepository.csAdded+13
- FlowAPI.Application/Interfaces/IAchievementService.csAdded+14
- FlowAPI.Application/Interfaces/IEdgeRepository.csAdded+9
- FlowAPI.Application/Interfaces/IEdgeService.csAdded+12
- FlowAPI.Application/Interfaces/IGeminiBridgeManager.csAdded+9
- FlowAPI.Application/Interfaces/IGenericRepository.csAdded+11
- FlowAPI.Application/Interfaces/IGraphRepository.csAdded+12
- FlowAPI.Application/Interfaces/IGraphService.csAdded+19
- FlowAPI.Application/Interfaces/IHabitRecordRepository.csAdded+10
- FlowAPI.Application/Interfaces/IHabitService.csAdded+11
- FlowAPI.Application/Interfaces/IPaymentService.csAdded+8
- FlowAPI.Application/Interfaces/ISharedGraphRepository.csAdded+14
- FlowAPI.Application/Interfaces/ISyncService.csAdded+9
- FlowAPI.Application/Interfaces/ITaskNodeRepository.csAdded+9
- FlowAPI.Application/Interfaces/ITaskNodeService.csAdded+13
- FlowAPI.Application/Interfaces/ITokenService.csAdded+9
- FlowAPI.Application/Interfaces/IUserAchievementRepository.csAdded+13
- FlowAPI.Application/Interfaces/IUserRepository.csAdded+9
- FlowAPI.Application/Interfaces/IUserService.csAdded+15
- FlowAPI.Application/Services/AIService.csAdded+740
- FlowAPI.Application/Services/AchievementService.csAdded+161
- FlowAPI.Application/Services/EdgeService.csAdded+57
- FlowAPI.Application/Services/GeminiBridgeManager.csAdded+203
- FlowAPI.Application/Services/GraphService.csAdded+320
- FlowAPI.Application/Services/HabitService.csAdded+85
- FlowAPI.Application/Services/PaymentService.csAdded+61
- FlowAPI.Application/Services/SyncService.csAdded+95
- FlowAPI.Application/Services/TaskNodeService.csAdded+80
- FlowAPI.Application/Services/TokenService.csAdded+49
- FlowAPI.Application/Services/UserService.csAdded+146
- FlowAPI.Domain/Entities/Achievement.csAdded+23
- FlowAPI.Domain/Entities/Edge.csAdded+18
- FlowAPI.Domain/Entities/Graph.csAdded+18
- FlowAPI.Domain/Entities/HabitRecord.csAdded+14
- FlowAPI.Domain/Entities/SharedGraph.csAdded+17
- FlowAPI.Domain/Entities/TaskNode.csAdded+22
- FlowAPI.Domain/Entities/User.csAdded+19
123456789101112131415161718192021.vs/bin/obj/*.user*.lock.json*.suo*.userosscache*.sln.docstatesout/[Dd]ebug/[Rr]elease/appsettings.Development.json*.db-shm*.db-walbridge_log.txtgemini_profile_bridge/*.sqlite-shm*.sqlite-wal# Ignore SQLite database files to avoid checking them intaskflow.db/app/data/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Stage 1: Build .NET 10 APIFROM mcr.microsoft.com/dotnet/sdk:10.0 AS buildWORKDIR /src
# Copy csproj files and restore dependenciesCOPY ["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 buildCOPY . .WORKDIR "/src/FlowAPI"RUN dotnet publish "FlowAPI.csproj" -c Release -o /app/publish /p:UseAppHost=false
# Stage 2: RuntimeFROM mcr.microsoft.com/dotnet/aspnet:10.0 AS finalWORKDIR /appEXPOSE 8080EXPOSE 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 cleanlyRUN python3 -m venv /opt/venvENV PATH="/opt/venv/bin:$PATH"
# Install camoufox python library and its dependenciesRUN pip3 install --no-cache-dir camoufox# Pre-download Camoufox/Playwright browser engines so they are readyRUN python3 -m camoufox fetch
# Copy published .NET appCOPY --from=build /app/publish .
# Explicitly copy the python bridge script to ensure it is in the run directoryCOPY --from=build /src/FlowAPI/gemini_bridge.py .
# Set entrypointENTRYPOINT ["dotnet", "FlowAPI.dll"]123456789101112131415161718192021222324252627282930313233343536using 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<TaskNodeResponseDto> SuggestedNodes { get; set; } = new(); public List<EdgeResponseDto> 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<NodeDto> NewNodes { get; set; } = new(); public List<EdgeDto> NewEdges { get; set; } = new(); }}1234567891011121314151617using 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; } }}1234567891011121314151617181920212223242526using 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; } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869using 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<NodeDto> Nodes { get; set; } = new(); public List<EdgeDto> 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; } }}1234567891011121314151617namespace 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; } }}123456789101112131415161718192021222324252627using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.DTOs.Edge;
namespace FlowAPI.Application.DTOs.Sync{ public class SyncRequestDto { public List<CreateTaskNodeDto> NewNodes { get; set; } = new(); public List<UpdateTaskNodeDtoWithId> UpdatedNodes { get; set; } = new(); public List<Guid> DeletedNodeIds { get; set; } = new();
public List<CreateEdgeDto> NewEdges { get; set; } = new(); public List<Guid> 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; }}1234567891011121314151617181920212223242526272829303132using 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; } }}12345678910111213141516171819202122232425262728293031323334353637383940414243namespace 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; }}1234567891011121314using 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; } }}1234567891011121314151617181920<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup>
<ItemGroup> <ProjectReference Include="..\FlowAPI.Domain\FlowAPI.Domain.csproj" /> </ItemGroup>
<ItemGroup> <PackageReference Include="Google.Apis.Auth" Version="1.74.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.8" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.8" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.18.0" /> </ItemGroup>
</Project>123456789101112using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;
namespace FlowAPI.Application.Interfaces{ public interface IAIService { Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request); Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request); Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request); }}12345678910111213using FlowAPI.Domain.Entities;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface IAchievementRepository : IGenericRepository<Achievement> { Task<IEnumerable<Achievement>> GetByTriggerEventAsync(string eventName); Task<IEnumerable<Achievement>> GetByTitlesAsync(IEnumerable<string> titles); Task AddRangeAsync(IEnumerable<Achievement> achievements); }}1234567891011121314using FlowAPI.Application.DTOs;using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface IAchievementService { Task<IEnumerable<UserAchievementDto>> GetUserAchievementsAsync(Guid userId); Task SeedAchievementsAsync(); Task ProcessEventAsync(Guid userId, string eventName, int amount = 1); }}123456789using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface IEdgeRepository : IGenericRepository<Edge> { Task<IEnumerable<Edge>> GetAllByGraphIdAsync(Guid graphId); }}123456789101112using FlowAPI.Application.DTOs.Edge;
namespace FlowAPI.Application.Interfaces{ public interface IEdgeService { Task<IEnumerable<EdgeResponseDto>> GetAllByGraphIdAsync(Guid graphId); Task<EdgeResponseDto?> GetByIdAsync(Guid id); Task<EdgeResponseDto> CreateAsync(CreateEdgeDto dto); Task<bool> DeleteAsync(Guid id); }}123456789using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface IGeminiBridgeManager { Task<string> SendPromptAsync(string prompt, bool isNewChat, int timeoutSeconds = 120); }}1234567891011namespace FlowAPI.Application.Interfaces{ public interface IGenericRepository<T> where T : class { Task<IEnumerable<T>> GetAllAsync(); Task<T?> GetByIdAsync(Guid id); Task<T> CreateAsync(T entity); Task<T> UpdateAsync(T entity); Task<bool> DeleteAsync(Guid id); }}123456789101112using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface IGraphRepository : IGenericRepository<Graph> { Task<IEnumerable<Graph>> GetAllByUserIdAsync(Guid userId); Task<Graph?> GetByIdWithDetailsAsync(Guid id); Task ClearDetailsAsync(Guid id); Task<bool> UpsertFullGraphAsync(Guid graphId, IEnumerable<TaskNode> nodes, IEnumerable<Edge> edges); }}12345678910111213141516171819using FlowAPI.Application.DTOs.Graph;
namespace FlowAPI.Application.Interfaces{ public interface IGraphService { Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId); Task<GraphResponseDto?> GetByIdAsync(Guid id, Guid currentUserId); Task<FullGraphResponseDto?> GetFullByIdAsync(Guid id, Guid currentUserId); Task<GraphResponseDto> CreateAsync(CreateGraphDto dto, Guid currentUserId); Task<GraphResponseDto?> UpdateAsync(Guid id, UpdateGraphDto dto, Guid currentUserId); Task<bool> DeleteAsync(Guid id, Guid currentUserId); Task<bool> SaveFullGraphAsync(Guid id, FullGraphResponseDto dto, Guid currentUserId);
Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto); Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId); Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId); }}12345678910using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface IHabitRecordRepository : IGenericRepository<HabitRecord> { Task<IEnumerable<HabitRecord>> GetAllByUserIdAsync(Guid userId); Task<HabitRecord?> GetTodayRecordAsync(Guid userId, string habitName); }}1234567891011using FlowAPI.Application.DTOs.Habit;
namespace FlowAPI.Application.Interfaces{ public interface IHabitService { Task<IEnumerable<HabitRecordResponseDto>> GetAllByUserIdAsync(Guid userId); Task<HabitRecordResponseDto> RecordHabitAsync(CreateHabitRecordDto dto); Task<int> GetStreakAsync(Guid userId, string habitName); }}12345678namespace FlowAPI.Application.Interfaces{ public interface IPaymentService { Task<string> CreateCheckoutSessionAsync(Guid userId); Task<bool> HandleWebhookAsync(string payload, string signature); }}1234567891011121314using FlowAPI.Domain.Entities;using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface ISharedGraphRepository : IGenericRepository<SharedGraph> { Task<IEnumerable<SharedGraph>> GetSharedGraphsByUserIdAsync(Guid userId); Task<SharedGraph?> GetShareAsync(Guid graphId, Guid sharedWithUserId); Task<IEnumerable<SharedGraph>> GetSharesForGraphAsync(Guid graphId); }}123456789using FlowAPI.Application.DTOs.Sync;
namespace FlowAPI.Application.Interfaces{ public interface ISyncService { Task<SyncResponseDto> SyncChangesAsync(Guid userId, SyncRequestDto request); }}123456789using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface ITaskNodeRepository : IGenericRepository<TaskNode> { Task<IEnumerable<TaskNode>> GetAllByGraphIdAsync(Guid graphId); }}12345678910111213using FlowAPI.Application.DTOs.TaskNode;
namespace FlowAPI.Application.Interfaces{ public interface ITaskNodeService { Task<IEnumerable<TaskNodeResponseDto>> GetAllByGraphIdAsync(Guid graphId); Task<TaskNodeResponseDto?> GetByIdAsync(Guid id); Task<TaskNodeResponseDto> CreateAsync(CreateTaskNodeDto dto); Task<TaskNodeResponseDto?> UpdateAsync(Guid id, UpdateTaskNodeDto dto); Task<bool> DeleteAsync(Guid id); }}123456789using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface ITokenService { string CreateToken(User user); }}12345678910111213using FlowAPI.Domain.Entities;using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface IUserAchievementRepository : IGenericRepository<UserAchievement> { Task<IEnumerable<UserAchievement>> GetByUserIdAsync(Guid userId); Task<IEnumerable<UserAchievement>> GetByUserAndAchievementIdsAsync(Guid userId, IEnumerable<Guid> achievementIds); }}123456789using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Interfaces{ public interface IUserRepository : IGenericRepository<User> { Task<User?> GetByEmailAsync(string email); }}123456789101112131415using FlowAPI.Application.DTOs.User;
namespace FlowAPI.Application.Interfaces{ public interface IUserService { Task<IEnumerable<UserResponseDto>> GetAllAsync(); Task<UserResponseDto?> GetByIdAsync(Guid id); Task<AuthResponseDto> RegisterAsync(CreateUserDto dto); Task<AuthResponseDto?> LoginAsync(LoginDto dto); Task<AuthResponseDto> GoogleLoginAsync(GoogleLoginDto dto); Task<UserResponseDto?> UpdateAsync(Guid id, UpdateUserDto dto); Task<bool> DeleteAsync(Guid id); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740using 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<AIPathResponseDto> 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<FullGraphResponseDto> 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<AIGoalGraphResponse>(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<string, Guid>(); var nodeDtos = new List<NodeDto>();
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<object>(); 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<EdgeDto>(); 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<AICanvasAssistResponseDto> 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<AICanvasAssistResponseInternal>(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<string, Guid>(); var newNodesEntities = new List<FlowAPI.Domain.Entities.TaskNode>(); var nodeDtos = new List<NodeDto>();
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<object>(); 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<FlowAPI.Domain.Entities.Edge>(); var edgeDtos = new List<EdgeDto>();
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<FlowAPI.Domain.Enums.EdgeCondition>(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<NodeDto> nodes, List<EdgeDto> edges) { if (nodes == null || nodes.Count == 0) return;
var inDegree = new Dictionary<Guid, int>(); var adj = new Dictionary<Guid, List<Guid>>(); foreach (var node in nodes) { inDegree[node.Id] = 0; adj[node.Id] = new List<Guid>(); }
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<Guid, int>(); foreach (var node in nodes) { layers[node.Id] = 0; }
var queue = new Queue<Guid>(); 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<Guid>(); 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<int, List<NodeDto>>(); foreach (var node in nodes) { int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<NodeDto>(); } 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<FlowAPI.Domain.Entities.TaskNode> nodes, List<FlowAPI.Domain.Entities.Edge> edges) { if (nodes == null || nodes.Count == 0) return;
var inDegree = new Dictionary<Guid, int>(); var adj = new Dictionary<Guid, List<Guid>>(); foreach (var node in nodes) { inDegree[node.Id] = 0; adj[node.Id] = new List<Guid>(); }
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<Guid, int>(); foreach (var node in nodes) { layers[node.Id] = 0; }
var queue = new Queue<Guid>(); 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<Guid>(); 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<int, List<FlowAPI.Domain.Entities.TaskNode>>(); foreach (var node in nodes) { int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<FlowAPI.Domain.Entities.TaskNode>(); } 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<AINodeDto> Nodes { get; set; } = new(); public List<AIEdgeDto> 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<AIOptionDto>? 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<AINewNodeInternalDto> NewNodes { get; set; } = new(); public List<AINewEdgeInternalDto> 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<AIOptionDto>? 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; } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161using 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<IEnumerable<UserAchievementDto>> 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<UserAchievementDto>();
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<Achievement> { 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); } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657using 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<IEnumerable<EdgeResponseDto>> GetAllByGraphIdAsync(Guid graphId) { var edges = await _repo.GetAllByGraphIdAsync(graphId); return edges.Select(MapToDto); }
public async Task<EdgeResponseDto?> GetByIdAsync(Guid id) { var edge = await _repo.GetByIdAsync(id); return edge is null ? null : MapToDto(edge); }
public async Task<EdgeResponseDto> 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<bool> 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 }; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203using 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<GeminiBridgeManager> _logger; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private Process? _process; private bool _isReady = false; private readonly JsonSerializerOptions _serializeOptions;
public GeminiBridgeManager(ILogger<GeminiBridgeManager> 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<string> 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(); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320using 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<IEnumerable<GraphResponseDto>> 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<GraphResponseDto?> 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<FullGraphResponseDto?> 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<GraphResponseDto> 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<GraphResponseDto?> 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<bool> 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<bool> 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<FlowAPI.Domain.Enums.EdgeCondition>(edgeDto.Condition, true, out var cond) ? cond : FlowAPI.Domain.Enums.EdgeCondition.True }).ToList();
// Calculate deltas for achievements var oldNodes = graph.Nodes ?? new List<TaskNode>(); var oldEdges = graph.Edges ?? new List<Edge>();
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<GraphResponseDto?> 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<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId) { var graph = await _repo.GetByIdAsync(graphId); if (graph is null || graph.UserId != ownerId) return Enumerable.Empty<SharedUserResponseDto>();
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<bool> 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 }; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485using 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<IEnumerable<HabitRecordResponseDto>> GetAllByUserIdAsync(Guid userId) { var records = await _repo.GetAllByUserIdAsync(userId); return records.Select(MapToDto); }
public async Task<HabitRecordResponseDto> 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<int> 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 }; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061using 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<string> 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<bool> 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); } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495using 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<SyncResponseDto> 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 }; } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980using 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<IEnumerable<TaskNodeResponseDto>> GetAllByGraphIdAsync(Guid graphId) { var nodes = await _repo.GetAllByGraphIdAsync(graphId); return nodes.Select(MapToDto); }
public async Task<TaskNodeResponseDto?> GetByIdAsync(Guid id) { var node = await _repo.GetByIdAsync(id); return node is null ? null : MapToDto(node); }
public async Task<TaskNodeResponseDto> 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<TaskNodeResponseDto?> 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<bool> 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 }; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849using 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<Claim> { 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); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146using 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<IEnumerable<UserResponseDto>> GetAllAsync() { var users = await _repo.GetAllAsync(); return users.Select(MapToDto); }
public async Task<UserResponseDto?> GetByIdAsync(Guid id) { var user = await _repo.GetByIdAsync(id); return user is null ? null : MapToDto(user); }
public async Task<AuthResponseDto> 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<AuthResponseDto?> 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<AuthResponseDto> GoogleLoginAsync(GoogleLoginDto dto) { var settings = new Google.Apis.Auth.GoogleJsonWebSignature.ValidationSettings { Audience = new List<string> { _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<UserResponseDto?> 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<bool> 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 }; }}1234567891011121314151617181920212223using 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; }}123456789101112131415161718using 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!; }}123456789101112131415161718namespace 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<TaskNode> Nodes { get; set; } = new List<TaskNode>(); public ICollection<Edge> Edges { get; set; } = new List<Edge>(); public ICollection<SharedGraph> SharedGraphs { get; set; } = new List<SharedGraph>(); }}1234567891011121314namespace 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!; }}1234567891011121314151617using 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!; }}12345678910111213141516171819202122using 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<Edge> OutgoingEdges { get; set; } = new List<Edge>(); public ICollection<Edge> IncomingEdges { get; set; } = new List<Edge>(); }}12345678910111213141516171819namespace 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<Graph> Graphs { get; set; } = new List<Graph>(); public ICollection<HabitRecord> HabitRecords { get; set; } = new List<HabitRecord>(); public ICollection<UserAchievement> UserAchievements { get; set; } = new List<UserAchievement>(); public ICollection<SharedGraph> SharedGraphs { get; set; } = new List<SharedGraph>(); }}.gitignoreAdded+21
DockerfileAdded+63
FlowAPI.Application/DTOs/AI/AIDtos.csAdded+36
FlowAPI.Application/DTOs/AchievementDto.csAdded+17
FlowAPI.Application/DTOs/Edge/EdgeDtos.csAdded+26
FlowAPI.Application/DTOs/Graph/GraphDtos.csAdded+69
FlowAPI.Application/DTOs/Habit/HabitDtos.csAdded+17
FlowAPI.Application/DTOs/Sync/SyncDtos.csAdded+27
FlowAPI.Application/DTOs/TaskNode/TaskNodeDtos.csAdded+32
FlowAPI.Application/DTOs/User/UserDtos.csAdded+43
FlowAPI.Application/DTOs/UserAchievementDto.csAdded+14
FlowAPI.Application/FlowAPI.Application.csprojAdded+20
FlowAPI.Application/Interfaces/IAIService.csAdded+12
FlowAPI.Application/Interfaces/IAchievementRepository.csAdded+13
FlowAPI.Application/Interfaces/IAchievementService.csAdded+14
FlowAPI.Application/Interfaces/IEdgeRepository.csAdded+9
FlowAPI.Application/Interfaces/IEdgeService.csAdded+12
FlowAPI.Application/Interfaces/IGeminiBridgeManager.csAdded+9
FlowAPI.Application/Interfaces/IGenericRepository.csAdded+11
FlowAPI.Application/Interfaces/IGraphRepository.csAdded+12
FlowAPI.Application/Interfaces/IGraphService.csAdded+19
FlowAPI.Application/Interfaces/IHabitRecordRepository.csAdded+10
FlowAPI.Application/Interfaces/IHabitService.csAdded+11
FlowAPI.Application/Interfaces/IPaymentService.csAdded+8
FlowAPI.Application/Interfaces/ISharedGraphRepository.csAdded+14
FlowAPI.Application/Interfaces/ISyncService.csAdded+9
FlowAPI.Application/Interfaces/ITaskNodeRepository.csAdded+9
FlowAPI.Application/Interfaces/ITaskNodeService.csAdded+13
FlowAPI.Application/Interfaces/ITokenService.csAdded+9
FlowAPI.Application/Interfaces/IUserAchievementRepository.csAdded+13
FlowAPI.Application/Interfaces/IUserRepository.csAdded+9
FlowAPI.Application/Interfaces/IUserService.csAdded+15
FlowAPI.Application/Services/AIService.csAdded+740
FlowAPI.Application/Services/AchievementService.csAdded+161
FlowAPI.Application/Services/EdgeService.csAdded+57
FlowAPI.Application/Services/GeminiBridgeManager.csAdded+203
FlowAPI.Application/Services/GraphService.csAdded+320
FlowAPI.Application/Services/HabitService.csAdded+85
FlowAPI.Application/Services/PaymentService.csAdded+61
FlowAPI.Application/Services/SyncService.csAdded+95
FlowAPI.Application/Services/TaskNodeService.csAdded+80
FlowAPI.Application/Services/TokenService.csAdded+49
FlowAPI.Application/Services/UserService.csAdded+146
FlowAPI.Domain/Entities/Achievement.csAdded+23
FlowAPI.Domain/Entities/Edge.csAdded+18
FlowAPI.Domain/Entities/Graph.csAdded+18
FlowAPI.Domain/Entities/HabitRecord.csAdded+14
FlowAPI.Domain/Entities/SharedGraph.csAdded+17
FlowAPI.Domain/Entities/TaskNode.csAdded+22
FlowAPI.Domain/Entities/User.csAdded+19