Spaces:
Running
Running
Commit ·
7039b6a
1
Parent(s): ab6ad9a
Implement custom templates and subscription tiers backend changes
Browse filesFiles changed (18)
- FlowAPI.Application/DTOs/User/UserDtos.cs+2
- FlowAPI.Application/Interfaces/ICustomTemplateRepository.csAdded+14
- FlowAPI.Application/Interfaces/IGraphService.cs+3
- FlowAPI.Application/Services/GraphService.cs+180-1
- FlowAPI.Application/Services/HabitService.cs+17-1
- FlowAPI.Application/Services/UserService.cs+7-1
- FlowAPI.Domain/Entities/CustomTemplate.csAdded+19
- FlowAPI.Domain/Entities/User.cs+5
- FlowAPI.Infrastructure/Data/AppDbContext.cs+18
- FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.Designer.csAdded+517
- FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.csAdded+85
- FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs+68
- FlowAPI.Infrastructure/Repositories/CustomTemplateRepository.csAdded+41
- FlowAPI/Controllers/AIController.cs+12
- FlowAPI/Controllers/GraphsController.cs+74-10
- FlowAPI/Controllers/HabitsController.cs+9-2
- FlowAPI/Controllers/PaymentsController.cs+35-1
- FlowAPI/Program.cs+1
12 unmodified lines1314151617181910 unmodified lines3031323334353612 unmodified lines public bool? IsPremium { get; set; } public string? AvatarUrl { get; set; } public string? Password { get; set; } public string? SubscriptionTier { get; set; } }
public class LoginDto10 unmodified lines public bool IsPremium { get; set; } public string? AvatarUrl { get; set; } public DateTime CreatedAt { get; set; } public string SubscriptionTier { get; set; } = "Free"; }
public class AuthResponseDto1234567891011121314using FlowAPI.Domain.Entities;using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface ICustomTemplateRepository { Task<CustomTemplate?> GetByIdAsync(Guid id); Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId); Task<CustomTemplate> CreateAsync(CustomTemplate template); }}14 unmodified lines151617181920212214 unmodified lines 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);
Task<FlowAPI.Domain.Entities.CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description); Task<IEnumerable<FlowAPI.Domain.Entities.CustomTemplate>> GetCustomTemplatesAsync(Guid userId); }}3 unmodified lines456789106 unmodified lines171819202122231 unmodified line2526272628293031321 unmodified line34353637383940100 unmodified lines1411421431441451461471481491501511521531541551561571585 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123270 unmodified lines30330430530630730830931031131231331431531631731831958 unmodified lines3783793803813823833843853865 unmodified lines39239339439539639739839940040140240340440540640740840941075 unmodified lines4864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635643 unmodified linesusing System;using System.Collections.Generic;using System.Linq;using System.Text.Json;using System.Threading.Tasks;
namespace FlowAPI.Application.Services6 unmodified lines private readonly IAchievementService _achievementService; private readonly ISharedGraphRepository _sharedGraphRepo; private readonly IUserRepository _userRepo; private readonly ICustomTemplateRepository _customTemplateRepo;
public GraphService( IGraphRepository repo, 1 unmodified line IEdgeRepository edgeRepo, IAchievementService achievementService, ISharedGraphRepository sharedGraphRepo, IUserRepository userRepo) IUserRepository userRepo, ICustomTemplateRepository customTemplateRepo) { _repo = repo; _nodeRepo = nodeRepo;1 unmodified line _achievementService = achievementService; _sharedGraphRepo = sharedGraphRepo; _userRepo = userRepo; _customTemplateRepo = customTemplateRepo; }
public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)100 unmodified lines
public async Task<GraphResponseDto> CreateAsync(CreateGraphDto dto, Guid currentUserId) { var user = await _userRepo.GetByIdAsync(currentUserId); if (user == null) throw new Exception("User not found.");
if (user.SubscriptionTier == "Free") { var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count(); if (ownedGraphsCount >= 3) { throw new InvalidOperationException("Free tier is limited to 3 canvases."); } }
var graph = new Graph { Id = Guid.NewGuid(),5 unmodified lines
if (!string.IsNullOrEmpty(dto.TemplateKey)) { // Try to load system template first var (nodes, edges) = TemplateLibrary.GetTemplateContent(dto.TemplateKey, graph.Id); // If not found in system templates, check custom templates in DB if (nodes.Count == 0 && Guid.TryParse(dto.TemplateKey, out var customTemplateId)) { var customTemplate = await _customTemplateRepo.GetByIdAsync(customTemplateId); if (customTemplate != null && (customTemplate.UserId == currentUserId || user.SubscriptionTier == "Ultra")) { try { var data = JsonSerializer.Deserialize<CustomTemplateContentDto>(customTemplate.ContentJson); if (data != null) { var idMapping = new Dictionary<Guid, Guid>(); foreach (var nodeDto in data.Nodes) { var newId = Guid.NewGuid(); idMapping[nodeDto.Id] = newId; var node = new TaskNode { Id = newId, GraphId = graph.Id, Label = nodeDto.Label, PosX = nodeDto.PosX, PosY = nodeDto.PosY, Type = nodeDto.Type, State = FlowAPI.Domain.Enums.NodeState.Pending, CreatedAt = DateTime.UtcNow, Description = nodeDto.Description, Color = nodeDto.Color, IsPinned = nodeDto.IsPinned, Width = nodeDto.Width, Height = nodeDto.Height, Data = nodeDto.Data, Decision = nodeDto.Decision }; nodes.Add(node); } foreach (var edgeDto in data.Edges) { if (idMapping.TryGetValue(edgeDto.FromNodeId, out var fromId) && idMapping.TryGetValue(edgeDto.ToNodeId, out var toId)) { edges.Add(new Edge { Id = Guid.NewGuid(), GraphId = graph.Id, FromNodeId = fromId, ToNodeId = toId, Condition = edgeDto.Condition }); } } } } catch (Exception ex) { System.Console.WriteLine($"[GraphService] Failed to load custom template: {ex.Message}"); } } }
if (nodes.Count > 0) { graph.Nodes = nodes;70 unmodified lines var graph = await _repo.GetByIdWithDetailsAsync(id); if (graph is null) return false;
var user = await _userRepo.GetByIdAsync(currentUserId); if (user == null) throw new Exception("User not found.");
if (user.SubscriptionTier == "Free") { if (dto.Nodes.Count > 200) { throw new InvalidOperationException("Free tier is limited to 200 nodes per canvas."); } }
// Secure: only allowed for owner or shared users with Edit permission if (graph.UserId != currentUserId) {58 unmodified lines var graph = await _repo.GetByIdAsync(graphId); if (graph is null || graph.UserId != ownerId) return null;
var owner = await _userRepo.GetByIdAsync(ownerId); if (owner == null) throw new Exception("Owner user not found.");
var targetUser = await _userRepo.GetByEmailAsync(dto.Email.ToLower().Trim()); if (targetUser is null || targetUser.Id == ownerId) return null;
5 unmodified lines } else { // Enforce sharing tier limits based on owner's tier var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId); int currentSharedCount = shares?.Count() ?? 0;
if (owner.SubscriptionTier == "Free" && currentSharedCount >= 1) { throw new InvalidOperationException("Free tier is limited to 2 people on a board (1 guest)."); } else if (owner.SubscriptionTier == "Pro" && currentSharedCount >= 9) { throw new InvalidOperationException("Pro tier is limited to 10 people on a board (9 guests)."); }
var share = new SharedGraph { Id = Guid.NewGuid(),75 unmodified lines Description = graph.Description, CreatedAt = graph.CreatedAt };
public async Task<CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description) { var user = await _userRepo.GetByIdAsync(userId); if (user == null) throw new Exception("User not found.");
if (user.SubscriptionTier != "Ultra") { throw new InvalidOperationException("Creating custom templates is an Ultra tier feature."); }
var graph = await _repo.GetByIdWithDetailsAsync(graphId); if (graph == null || graph.UserId != userId) { throw new Exception("Graph not found or you are not the owner."); }
// Map nodes and edges to DTOs for serialization var 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, Description = n.Description, Color = n.Color, IsPinned = n.IsPinned, Width = n.Width, Height = n.Height, Data = n.Data }).ToList();
var edges = graph.Edges.Select(e => new EdgeDto { Id = e.Id, FromNodeId = e.FromNodeId, ToNodeId = e.ToNodeId, Condition = e.Condition }).ToList();
var contentJson = JsonSerializer.Serialize(new CustomTemplateContentDto { Nodes = nodes, Edges = edges });
var template = new CustomTemplate { Id = Guid.NewGuid(), UserId = userId, Title = title, Description = description, Category = "Custom", Icon = "BookOpen", ContentJson = contentJson, CreatedAt = DateTime.UtcNow };
return await _customTemplateRepo.CreateAsync(template); }
public async Task<IEnumerable<CustomTemplate>> GetCustomTemplatesAsync(Guid userId) { return await _customTemplateRepo.GetByUserIdAsync(userId); }
private class CustomTemplateContentDto { public List<NodeDto> Nodes { get; set; } = new(); public List<EdgeDto> Edges { get; set; } = new(); } }}6 unmodified lines78910111212131415161718195 unmodified lines2526272829303132333435363738394041424344454647486 unmodified lines public class HabitService : IHabitService { private readonly IHabitRecordRepository _repo; private readonly IUserRepository _userRepo; private readonly IAchievementService _achievementService;
public HabitService(IHabitRecordRepository repo, IAchievementService achievementService) public HabitService(IHabitRecordRepository repo, IUserRepository userRepo, IAchievementService achievementService) { _repo = repo; _userRepo = userRepo; _achievementService = achievementService; }
5 unmodified lines
public async Task<HabitRecordResponseDto> RecordHabitAsync(CreateHabitRecordDto dto) { var user = await _userRepo.GetByIdAsync(dto.UserId); if (user == null) throw new Exception("User not found.");
var targetDate = dto.CheckedDate ?? DateTime.UtcNow; var existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date); if (existing is not null) return MapToDto(existing);
if (user.SubscriptionTier == "Free") { var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId); var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();
if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >= 3) { throw new InvalidOperationException("Free tier is limited to 3 habits."); } }
var record = new HabitRecord { Id = Guid.NewGuid(),110 unmodified lines11111211311411511611711811912012124 unmodified lines146147148144149150151152153110 unmodified lines 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; if (dto.SubscriptionTier is not null) { user.SubscriptionTier = dto.SubscriptionTier; user.IsPremium = dto.SubscriptionTier != "Free"; } if (!string.IsNullOrEmpty(dto.Password)) user.PasswordHash = HashPassword(dto.Password);
var updated = await _repo.UpdateAsync(user);24 unmodified lines DisplayName = user.DisplayName, IsPremium = user.IsPremium, AvatarUrl = user.AvatarUrl, CreatedAt = user.CreatedAt CreatedAt = user.CreatedAt, SubscriptionTier = user.SubscriptionTier }; }}12345678910111213141516171819using System;
namespace FlowAPI.Domain.Entities{ public class CustomTemplate { public Guid Id { get; set; } public Guid UserId { get; set; } public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Category { get; set; } = "Custom"; public string Icon { get; set; } = "BookOpen"; public string ContentJson { get; set; } = string.Empty; // Holds serialized nodes and edges public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
// Navigation properties public User User { get; set; } = null!; }}9 unmodified lines10111213141516171819209 unmodified lines public string? AvatarUrl { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
// Subscription Tier info public string SubscriptionTier { get; set; } = "Free"; // "Free", "Pro", "Ultra" public int DailyAiGenerationsCount { get; set; } public DateTime LastAiGenerationDate { get; set; } = DateTime.UtcNow;
// Navigation properties public ICollection<Graph> Graphs { get; set; } = new List<Graph>(); public ICollection<HabitRecord> HabitRecords { get; set; } = new List<HabitRecord>();15 unmodified lines161718192021227 unmodified lines30313233343536106 unmodified lines14314414514614714814915015115215315415515615715815916016116216316415 unmodified lines public DbSet<Achievement> Achievements => Set<Achievement>(); public DbSet<UserAchievement> UserAchievements => Set<UserAchievement>(); public DbSet<SharedGraph> SharedGraphs => Set<SharedGraph>(); public DbSet<CustomTemplate> CustomTemplates => Set<CustomTemplate>();
protected override void OnModelCreating(ModelBuilder modelBuilder) {7 unmodified lines entity.Property(e => e.Email).IsRequired().HasMaxLength(256); entity.Property(e => e.PasswordHash).IsRequired(); entity.Property(e => e.DisplayName).HasMaxLength(100); entity.Property(e => e.SubscriptionTier).HasDefaultValue("Free").HasMaxLength(50); });
// Graph106 unmodified lines
entity.HasIndex(e => new { e.GraphId, e.SharedWithUserId }).IsUnique(); });
// CustomTemplate modelBuilder.Entity<CustomTemplate>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Title).IsRequired().HasMaxLength(200); entity.Property(e => e.Description).HasMaxLength(1000); entity.Property(e => e.Category).HasMaxLength(100); entity.Property(e => e.Icon).HasMaxLength(100); entity.Property(e => e.ContentJson).IsRequired().HasMaxLength(10000000);
entity.HasOne(e => e.User) .WithMany() .HasForeignKey(e => e.UserId) .OnDelete(DeleteBehavior.Cascade); }); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517// <auto-generated />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("20260607131226_AddSubscriptionTiers")] partial class AddSubscriptionTiers { /// <inheritdoc /> 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<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("Category") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("Description") .IsRequired() .HasColumnType("TEXT");
b.Property<string>("IconUrl") .IsRequired() .HasColumnType("TEXT");
b.Property<int>("RewardPoints") .HasColumnType("INTEGER");
b.Property<int>("TargetValue") .HasColumnType("INTEGER");
b.Property<string>("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT");
b.Property<string>("TriggerEventName") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<int>("Type") .HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Achievements"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("Category") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("ContentJson") .IsRequired() .HasMaxLength(10000000) .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<string>("Description") .IsRequired() .HasMaxLength(1000) .HasColumnType("TEXT");
b.Property<string>("Icon") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT");
b.Property<Guid>("UserId") .HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("CustomTemplates"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("Condition") .IsRequired() .HasMaxLength(500) .HasColumnType("TEXT");
b.Property<Guid>("FromNodeId") .HasColumnType("TEXT");
b.Property<Guid>("GraphId") .HasColumnType("TEXT");
b.Property<Guid>("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<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("TEXT");
b.Property<string>("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt") .HasColumnType("TEXT");
b.Property<Guid>("UserId") .HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Graphs"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<DateTime>("CheckedDate") .HasColumnType("TEXT");
b.Property<string>("HabitName") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<int>("StreakCount") .HasColumnType("INTEGER");
b.Property<Guid>("UserId") .HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("HabitRecords"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<Guid>("GraphId") .HasColumnType("TEXT");
b.Property<string>("Permission") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(50) .HasColumnType("TEXT") .HasDefaultValue("Read");
b.Property<Guid>("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<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("Color") .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<string>("Data") .HasMaxLength(10000000) .HasColumnType("TEXT");
b.Property<string>("Decision") .HasMaxLength(1000000) .HasColumnType("TEXT");
b.Property<string>("Description") .HasMaxLength(10000) .HasColumnType("TEXT");
b.Property<Guid>("GraphId") .HasColumnType("TEXT");
b.Property<double?>("Height") .HasColumnType("REAL");
b.Property<bool>("IsPinned") .HasColumnType("INTEGER");
b.Property<string>("Label") .IsRequired() .HasMaxLength(1000) .HasColumnType("TEXT");
b.Property<double>("PosX") .HasColumnType("REAL");
b.Property<double>("PosY") .HasColumnType("REAL");
b.Property<string>("State") .IsRequired() .ValueGeneratedOnAdd() .HasColumnType("TEXT") .HasDefaultValue("Pending");
b.Property<string>("Type") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(100) .HasColumnType("TEXT") .HasDefaultValue("sketch");
b.Property<double?>("Width") .HasColumnType("REAL");
b.HasKey("Id");
b.HasIndex("GraphId");
b.ToTable("TaskNodes"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.User", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("AvatarUrl") .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<int>("DailyAiGenerationsCount") .HasColumnType("INTEGER");
b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("TEXT");
b.Property<bool>("IsPremium") .HasColumnType("INTEGER");
b.Property<DateTime>("LastAiGenerationDate") .HasColumnType("TEXT");
b.Property<string>("PasswordHash") .IsRequired() .HasColumnType("TEXT");
b.Property<string>("SubscriptionTier") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(50) .HasColumnType("TEXT") .HasDefaultValue("Free");
b.HasKey("Id");
b.HasIndex("Email") .IsUnique();
b.ToTable("Users"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<Guid>("AchievementId") .HasColumnType("TEXT");
b.Property<int>("CurrentValue") .HasColumnType("INTEGER");
b.Property<bool>("IsUnlocked") .HasColumnType("INTEGER");
b.Property<DateTime?>("UnlockedAt") .HasColumnType("TEXT");
b.Property<Guid>("UserId") .HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("AchievementId");
b.HasIndex("UserId");
b.ToTable("UserAchievements"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b => { b.HasOne("FlowAPI.Domain.Entities.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired();
b.Navigation("User"); });
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 } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485using System;using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FlowAPI.Infrastructure.Migrations{ /// <inheritdoc /> public partial class AddSubscriptionTiers : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "DailyAiGenerationsCount", table: "Users", type: "INTEGER", nullable: false, defaultValue: 0);
migrationBuilder.AddColumn<DateTime>( name: "LastAiGenerationDate", table: "Users", type: "TEXT", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.AddColumn<string>( name: "SubscriptionTier", table: "Users", type: "TEXT", maxLength: 50, nullable: false, defaultValue: "Free");
migrationBuilder.CreateTable( name: "CustomTemplates", columns: table => new { Id = table.Column<Guid>(type: "TEXT", nullable: false), UserId = table.Column<Guid>(type: "TEXT", nullable: false), Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false), Description = table.Column<string>(type: "TEXT", maxLength: 1000, nullable: false), Category = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false), Icon = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false), ContentJson = table.Column<string>(type: "TEXT", maxLength: 10000000, nullable: false), CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false) }, constraints: table => { table.PrimaryKey("PK_CustomTemplates", x => x.Id); table.ForeignKey( name: "FK_CustomTemplates_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); });
migrationBuilder.CreateIndex( name: "IX_CustomTemplates_UserId", table: "CustomTemplates", column: "UserId"); }
/// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "CustomTemplates");
migrationBuilder.DropColumn( name: "DailyAiGenerationsCount", table: "Users");
migrationBuilder.DropColumn( name: "LastAiGenerationDate", table: "Users");
migrationBuilder.DropColumn( name: "SubscriptionTier", table: "Users"); } }}59 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109195 unmodified lines3053063073083093103113123137 unmodified lines32132232332432532632732832933033133233333433533633733833934032 unmodified lines37337437537637737837938038138238338438538638738838959 unmodified lines b.ToTable("Achievements"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("TEXT");
b.Property<string>("Category") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("ContentJson") .IsRequired() .HasMaxLength(10000000) .HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<string>("Description") .IsRequired() .HasMaxLength(1000) .HasColumnType("TEXT");
b.Property<string>("Icon") .IsRequired() .HasMaxLength(100) .HasColumnType("TEXT");
b.Property<string>("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT");
b.Property<Guid>("UserId") .HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("CustomTemplates"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => { b.Property<Guid>("Id")195 unmodified lines b.Property<DateTime>("CreatedAt") .HasColumnType("TEXT");
b.Property<int>("DailyAiGenerationsCount") .HasColumnType("INTEGER");
b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(100)7 unmodified lines b.Property<bool>("IsPremium") .HasColumnType("INTEGER");
b.Property<DateTime>("LastAiGenerationDate") .HasColumnType("TEXT");
b.Property<string>("PasswordHash") .IsRequired() .HasColumnType("TEXT");
b.Property<string>("SubscriptionTier") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(50) .HasColumnType("TEXT") .HasDefaultValue("Free");
b.HasKey("Id");
b.HasIndex("Email")32 unmodified lines b.ToTable("UserAchievements"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b => { b.HasOne("FlowAPI.Domain.Entities.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired();
b.Navigation("User"); });
modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b => { b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode")1234567891011121314151617181920212223242526272829303132333435363738394041using 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 CustomTemplateRepository : ICustomTemplateRepository { private readonly AppDbContext _context;
public CustomTemplateRepository(AppDbContext context) { _context = context; }
public async Task<CustomTemplate?> GetByIdAsync(Guid id) { return await _context.CustomTemplates.FirstOrDefaultAsync(t => t.Id == id); }
public async Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId) { return await _context.CustomTemplates .Where(t => t.UserId == userId) .OrderByDescending(t => t.CreatedAt) .ToListAsync(); }
public async Task<CustomTemplate> CreateAsync(CustomTemplate template) { _context.CustomTemplates.Add(template); await _context.SaveChangesAsync(); return template; } }}27 unmodified lines282930313233343536378 unmodified lines464748495051525354558 unmodified lines6465666768697071727327 unmodified lines { return StatusCode(403, new { message = "Premium subscription required for AI generation." }); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message });8 unmodified lines var response = await _aiService.GenerateGoalGraphAsync(request); return Ok(response); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message });8 unmodified lines var response = await _aiService.CanvasAssistAsync(request); return Ok(response); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message });31 unmodified lines3233343535363737383940414243444546474849505152535455565732 unmodified lines90919293947677959697989910010110210310421 unmodified lines1261271281291301051061071311321331341351361371381391401411 unmodified line14314414514614711511611714814915015115215315415515615715814 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220331 unmodified lines }
[HttpGet("templates")] public ActionResult<IEnumerable<TemplateInfoDto>> GetTemplates() public async Task<ActionResult<IEnumerable<TemplateInfoDto>>> GetTemplates() { var templates = TemplateLibrary.GetTemplateInfos(); var templates = TemplateLibrary.GetTemplateInfos().ToList(); var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (Guid.TryParse(userIdStr, out var userId)) { var customTemplates = await _service.GetCustomTemplatesAsync(userId); foreach (var t in customTemplates) { templates.Add(new TemplateInfoDto { Key = t.Id.ToString(), Title = t.Title, Description = t.Description, Icon = t.Icon, Category = t.Category }); } } return Ok(templates); }
32 unmodified lines { if (CurrentUserId == Guid.Empty) return Unauthorized();
try { var graph = await _service.CreateAsync(dto, CurrentUserId); return CreatedAtAction(nameof(GetById), new { id = graph.Id }, graph); var graph = await _service.CreateAsync(dto, CurrentUserId); return CreatedAtAction(nameof(GetById), new { id = graph.Id }, graph); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } }
[HttpPut("{id:guid}")]21 unmodified lines { if (CurrentUserId == Guid.Empty) return Unauthorized();
try { var result = await _service.SaveFullGraphAsync(id, dto, CurrentUserId); if (!result) return NotFound(); return Ok(); var result = await _service.SaveFullGraphAsync(id, dto, CurrentUserId); if (!result) return NotFound(); return Ok(); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } }
[HttpPost("{id:guid}/share")]1 unmodified line { if (CurrentUserId == Guid.Empty) return Unauthorized();
try { var result = await _service.ShareGraphAsync(id, CurrentUserId, dto); if (result is null) return BadRequest("Не вдалося поділитися дошкою. Перевірте email або права."); return Ok(result); var result = await _service.ShareGraphAsync(id, CurrentUserId, dto); if (result is null) return BadRequest("Не вдалося поділитися дошкою. Перевірте email або права."); return Ok(result); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } }
[HttpGet("{id:guid}/shares")]14 unmodified lines if (!result) return NotFound(); return NoContent(); }
[HttpPost("{id:guid}/save-as-template")] public async Task<IActionResult> SaveAsTemplate(Guid id, [FromBody] SaveTemplateDto dto) { if (CurrentUserId == Guid.Empty) return Unauthorized();
try { var template = await _service.SaveAsTemplateAsync(id, CurrentUserId, dto.Title, dto.Description); return Ok(new { message = "Template saved successfully", templateId = template.Id }); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } } }
public class SaveTemplateDto { public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; }}24 unmodified lines252627282928293031323334353637383924 unmodified lines [HttpPost("record")] public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto) { try { var record = await _service.RecordHabitAsync(dto); return Ok(record); var record = await _service.RecordHabitAsync(dto); return Ok(record); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } }
[HttpGet("streak/{userId:guid}/{habitName}")]7 unmodified lines89101112121314151617181913 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697 unmodified lines public class PaymentsController : ControllerBase { private readonly IPaymentService _paymentService; private readonly IUserRepository _userRepo;
public PaymentsController(IPaymentService paymentService) public PaymentsController(IPaymentService paymentService, IUserRepository userRepo) { _paymentService = paymentService; _userRepo = userRepo; }
[HttpPost("create-checkout-session/{userId:guid}")]13 unmodified lines if (result) return Ok(); return BadRequest(); }
[HttpPost("change-tier/{userId:guid}")] public async Task<IActionResult> ChangeTier(Guid userId, [FromBody] ChangeTierDto dto) { var user = await _userRepo.GetByIdAsync(userId); if (user == null) return NotFound("User not found.");
var upperTier = dto.Tier.Trim(); if (upperTier != "Free" && upperTier != "Pro" && upperTier != "Ultra") { return BadRequest("Invalid tier. Must be 'Free', 'Pro', or 'Ultra'."); }
user.SubscriptionTier = upperTier; user.IsPremium = upperTier != "Free"; await _userRepo.UpdateAsync(user);
return Ok(new { id = user.Id, email = user.Email, displayName = user.DisplayName, isPremium = user.IsPremium, avatarUrl = user.AvatarUrl, createdAt = user.CreatedAt, subscriptionTier = user.SubscriptionTier }); } }
public class ChangeTierDto { public string Tier { get; set; } = string.Empty; }}27 unmodified lines2829303132333427 unmodified lines builder.Services.AddScoped<IAchievementRepository, AchievementRepository>(); builder.Services.AddScoped<IUserAchievementRepository, UserAchievementRepository>(); builder.Services.AddScoped<ISharedGraphRepository, SharedGraphRepository>(); builder.Services.AddScoped<ICustomTemplateRepository, CustomTemplateRepository>();
// --- Services (Application) --- builder.Services.AddScoped<ITokenService, TokenService>();FlowAPI.Application/DTOs/User/UserDtos.cs+2
FlowAPI.Application/Interfaces/ICustomTemplateRepository.csAdded+14
FlowAPI.Application/Interfaces/IGraphService.cs+3
FlowAPI.Application/Services/GraphService.cs+180-1
FlowAPI.Application/Services/HabitService.cs+17-1
FlowAPI.Application/Services/UserService.cs+7-1
FlowAPI.Domain/Entities/CustomTemplate.csAdded+19
FlowAPI.Domain/Entities/User.cs+5
FlowAPI.Infrastructure/Data/AppDbContext.cs+18
FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.Designer.csAdded+517
FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.csAdded+85
FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs+68
FlowAPI.Infrastructure/Repositories/CustomTemplateRepository.csAdded+41
FlowAPI/Controllers/AIController.cs+12
FlowAPI/Controllers/GraphsController.cs+74-10
FlowAPI/Controllers/HabitsController.cs+9-2
FlowAPI/Controllers/PaymentsController.cs+35-1
FlowAPI/Program.cs+1