danylokhodus commited on
Commit
7039b6a
·
1 Parent(s): ab6ad9a

Implement custom templates and subscription tiers backend changes

Browse files
FlowAPI.Application/DTOs/User/UserDtos.cs CHANGED
@@ -13,6 +13,7 @@ namespace FlowAPI.Application.DTOs.User
13
  public bool? IsPremium { get; set; }
14
  public string? AvatarUrl { get; set; }
15
  public string? Password { get; set; }
 
16
  }
17
 
18
  public class LoginDto
@@ -29,6 +30,7 @@ namespace FlowAPI.Application.DTOs.User
29
  public bool IsPremium { get; set; }
30
  public string? AvatarUrl { get; set; }
31
  public DateTime CreatedAt { get; set; }
 
32
  }
33
 
34
  public class AuthResponseDto
 
13
  public bool? IsPremium { get; set; }
14
  public string? AvatarUrl { get; set; }
15
  public string? Password { get; set; }
16
+ public string? SubscriptionTier { get; set; }
17
  }
18
 
19
  public class LoginDto
 
30
  public bool IsPremium { get; set; }
31
  public string? AvatarUrl { get; set; }
32
  public DateTime CreatedAt { get; set; }
33
+ public string SubscriptionTier { get; set; } = "Free";
34
  }
35
 
36
  public class AuthResponseDto
FlowAPI.Application/Interfaces/ICustomTemplateRepository.cs ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using FlowAPI.Domain.Entities;
2
+ using System;
3
+ using System.Collections.Generic;
4
+ using System.Threading.Tasks;
5
+
6
+ namespace FlowAPI.Application.Interfaces
7
+ {
8
+ public interface ICustomTemplateRepository
9
+ {
10
+ Task<CustomTemplate?> GetByIdAsync(Guid id);
11
+ Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId);
12
+ Task<CustomTemplate> CreateAsync(CustomTemplate template);
13
+ }
14
+ }
FlowAPI.Application/Interfaces/IGraphService.cs CHANGED
@@ -15,5 +15,8 @@ namespace FlowAPI.Application.Interfaces
15
  Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);
16
  Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);
17
  Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);
 
 
 
18
  }
19
  }
 
15
  Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);
16
  Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);
17
  Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);
18
+
19
+ Task<FlowAPI.Domain.Entities.CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description);
20
+ Task<IEnumerable<FlowAPI.Domain.Entities.CustomTemplate>> GetCustomTemplatesAsync(Guid userId);
21
  }
22
  }
FlowAPI.Application/Services/GraphService.cs CHANGED
@@ -4,6 +4,7 @@ using FlowAPI.Domain.Entities;
4
  using System;
5
  using System.Collections.Generic;
6
  using System.Linq;
 
7
  using System.Threading.Tasks;
8
 
9
  namespace FlowAPI.Application.Services
@@ -16,6 +17,7 @@ namespace FlowAPI.Application.Services
16
  private readonly IAchievementService _achievementService;
17
  private readonly ISharedGraphRepository _sharedGraphRepo;
18
  private readonly IUserRepository _userRepo;
 
19
 
20
  public GraphService(
21
  IGraphRepository repo,
@@ -23,7 +25,8 @@ namespace FlowAPI.Application.Services
23
  IEdgeRepository edgeRepo,
24
  IAchievementService achievementService,
25
  ISharedGraphRepository sharedGraphRepo,
26
- IUserRepository userRepo)
 
27
  {
28
  _repo = repo;
29
  _nodeRepo = nodeRepo;
@@ -31,6 +34,7 @@ namespace FlowAPI.Application.Services
31
  _achievementService = achievementService;
32
  _sharedGraphRepo = sharedGraphRepo;
33
  _userRepo = userRepo;
 
34
  }
35
 
36
  public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)
@@ -137,6 +141,18 @@ namespace FlowAPI.Application.Services
137
 
138
  public async Task<GraphResponseDto> CreateAsync(CreateGraphDto dto, Guid currentUserId)
139
  {
 
 
 
 
 
 
 
 
 
 
 
 
140
  var graph = new Graph
141
  {
142
  Id = Guid.NewGuid(),
@@ -148,7 +164,69 @@ namespace FlowAPI.Application.Services
148
 
149
  if (!string.IsNullOrEmpty(dto.TemplateKey))
150
  {
 
151
  var (nodes, edges) = TemplateLibrary.GetTemplateContent(dto.TemplateKey, graph.Id);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  if (nodes.Count > 0)
153
  {
154
  graph.Nodes = nodes;
@@ -225,6 +303,17 @@ namespace FlowAPI.Application.Services
225
  var graph = await _repo.GetByIdWithDetailsAsync(id);
226
  if (graph is null) return false;
227
 
 
 
 
 
 
 
 
 
 
 
 
228
  // Secure: only allowed for owner or shared users with Edit permission
229
  if (graph.UserId != currentUserId)
230
  {
@@ -289,6 +378,9 @@ namespace FlowAPI.Application.Services
289
  var graph = await _repo.GetByIdAsync(graphId);
290
  if (graph is null || graph.UserId != ownerId) return null;
291
 
 
 
 
292
  var targetUser = await _userRepo.GetByEmailAsync(dto.Email.ToLower().Trim());
293
  if (targetUser is null || targetUser.Id == ownerId) return null;
294
 
@@ -300,6 +392,19 @@ namespace FlowAPI.Application.Services
300
  }
301
  else
302
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  var share = new SharedGraph
304
  {
305
  Id = Guid.NewGuid(),
@@ -381,5 +486,79 @@ namespace FlowAPI.Application.Services
381
  Description = graph.Description,
382
  CreatedAt = graph.CreatedAt
383
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  }
385
  }
 
4
  using System;
5
  using System.Collections.Generic;
6
  using System.Linq;
7
+ using System.Text.Json;
8
  using System.Threading.Tasks;
9
 
10
  namespace FlowAPI.Application.Services
 
17
  private readonly IAchievementService _achievementService;
18
  private readonly ISharedGraphRepository _sharedGraphRepo;
19
  private readonly IUserRepository _userRepo;
20
+ private readonly ICustomTemplateRepository _customTemplateRepo;
21
 
22
  public GraphService(
23
  IGraphRepository repo,
 
25
  IEdgeRepository edgeRepo,
26
  IAchievementService achievementService,
27
  ISharedGraphRepository sharedGraphRepo,
28
+ IUserRepository userRepo,
29
+ ICustomTemplateRepository customTemplateRepo)
30
  {
31
  _repo = repo;
32
  _nodeRepo = nodeRepo;
 
34
  _achievementService = achievementService;
35
  _sharedGraphRepo = sharedGraphRepo;
36
  _userRepo = userRepo;
37
+ _customTemplateRepo = customTemplateRepo;
38
  }
39
 
40
  public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)
 
141
 
142
  public async Task<GraphResponseDto> CreateAsync(CreateGraphDto dto, Guid currentUserId)
143
  {
144
+ var user = await _userRepo.GetByIdAsync(currentUserId);
145
+ if (user == null) throw new Exception("User not found.");
146
+
147
+ if (user.SubscriptionTier == "Free")
148
+ {
149
+ var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();
150
+ if (ownedGraphsCount >= 3)
151
+ {
152
+ throw new InvalidOperationException("Free tier is limited to 3 canvases.");
153
+ }
154
+ }
155
+
156
  var graph = new Graph
157
  {
158
  Id = Guid.NewGuid(),
 
164
 
165
  if (!string.IsNullOrEmpty(dto.TemplateKey))
166
  {
167
+ // Try to load system template first
168
  var (nodes, edges) = TemplateLibrary.GetTemplateContent(dto.TemplateKey, graph.Id);
169
+
170
+ // If not found in system templates, check custom templates in DB
171
+ if (nodes.Count == 0 && Guid.TryParse(dto.TemplateKey, out var customTemplateId))
172
+ {
173
+ var customTemplate = await _customTemplateRepo.GetByIdAsync(customTemplateId);
174
+ if (customTemplate != null && (customTemplate.UserId == currentUserId || user.SubscriptionTier == "Ultra"))
175
+ {
176
+ try
177
+ {
178
+ var data = JsonSerializer.Deserialize<CustomTemplateContentDto>(customTemplate.ContentJson);
179
+ if (data != null)
180
+ {
181
+ var idMapping = new Dictionary<Guid, Guid>();
182
+ foreach (var nodeDto in data.Nodes)
183
+ {
184
+ var newId = Guid.NewGuid();
185
+ idMapping[nodeDto.Id] = newId;
186
+ var node = new TaskNode
187
+ {
188
+ Id = newId,
189
+ GraphId = graph.Id,
190
+ Label = nodeDto.Label,
191
+ PosX = nodeDto.PosX,
192
+ PosY = nodeDto.PosY,
193
+ Type = nodeDto.Type,
194
+ State = FlowAPI.Domain.Enums.NodeState.Pending,
195
+ CreatedAt = DateTime.UtcNow,
196
+ Description = nodeDto.Description,
197
+ Color = nodeDto.Color,
198
+ IsPinned = nodeDto.IsPinned,
199
+ Width = nodeDto.Width,
200
+ Height = nodeDto.Height,
201
+ Data = nodeDto.Data,
202
+ Decision = nodeDto.Decision
203
+ };
204
+ nodes.Add(node);
205
+ }
206
+ foreach (var edgeDto in data.Edges)
207
+ {
208
+ if (idMapping.TryGetValue(edgeDto.FromNodeId, out var fromId) &&
209
+ idMapping.TryGetValue(edgeDto.ToNodeId, out var toId))
210
+ {
211
+ edges.Add(new Edge
212
+ {
213
+ Id = Guid.NewGuid(),
214
+ GraphId = graph.Id,
215
+ FromNodeId = fromId,
216
+ ToNodeId = toId,
217
+ Condition = edgeDto.Condition
218
+ });
219
+ }
220
+ }
221
+ }
222
+ }
223
+ catch (Exception ex)
224
+ {
225
+ System.Console.WriteLine($"[GraphService] Failed to load custom template: {ex.Message}");
226
+ }
227
+ }
228
+ }
229
+
230
  if (nodes.Count > 0)
231
  {
232
  graph.Nodes = nodes;
 
303
  var graph = await _repo.GetByIdWithDetailsAsync(id);
304
  if (graph is null) return false;
305
 
306
+ var user = await _userRepo.GetByIdAsync(currentUserId);
307
+ if (user == null) throw new Exception("User not found.");
308
+
309
+ if (user.SubscriptionTier == "Free")
310
+ {
311
+ if (dto.Nodes.Count > 200)
312
+ {
313
+ throw new InvalidOperationException("Free tier is limited to 200 nodes per canvas.");
314
+ }
315
+ }
316
+
317
  // Secure: only allowed for owner or shared users with Edit permission
318
  if (graph.UserId != currentUserId)
319
  {
 
378
  var graph = await _repo.GetByIdAsync(graphId);
379
  if (graph is null || graph.UserId != ownerId) return null;
380
 
381
+ var owner = await _userRepo.GetByIdAsync(ownerId);
382
+ if (owner == null) throw new Exception("Owner user not found.");
383
+
384
  var targetUser = await _userRepo.GetByEmailAsync(dto.Email.ToLower().Trim());
385
  if (targetUser is null || targetUser.Id == ownerId) return null;
386
 
 
392
  }
393
  else
394
  {
395
+ // Enforce sharing tier limits based on owner's tier
396
+ var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);
397
+ int currentSharedCount = shares?.Count() ?? 0;
398
+
399
+ if (owner.SubscriptionTier == "Free" && currentSharedCount >= 1)
400
+ {
401
+ throw new InvalidOperationException("Free tier is limited to 2 people on a board (1 guest).");
402
+ }
403
+ else if (owner.SubscriptionTier == "Pro" && currentSharedCount >= 9)
404
+ {
405
+ throw new InvalidOperationException("Pro tier is limited to 10 people on a board (9 guests).");
406
+ }
407
+
408
  var share = new SharedGraph
409
  {
410
  Id = Guid.NewGuid(),
 
486
  Description = graph.Description,
487
  CreatedAt = graph.CreatedAt
488
  };
489
+
490
+ public async Task<CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description)
491
+ {
492
+ var user = await _userRepo.GetByIdAsync(userId);
493
+ if (user == null) throw new Exception("User not found.");
494
+
495
+ if (user.SubscriptionTier != "Ultra")
496
+ {
497
+ throw new InvalidOperationException("Creating custom templates is an Ultra tier feature.");
498
+ }
499
+
500
+ var graph = await _repo.GetByIdWithDetailsAsync(graphId);
501
+ if (graph == null || graph.UserId != userId)
502
+ {
503
+ throw new Exception("Graph not found or you are not the owner.");
504
+ }
505
+
506
+ // Map nodes and edges to DTOs for serialization
507
+ var nodes = graph.Nodes.Select(n => new NodeDto
508
+ {
509
+ Id = n.Id,
510
+ Label = n.Label,
511
+ PosX = n.PosX,
512
+ PosY = n.PosY,
513
+ Type = n.Type,
514
+ State = (int)n.State,
515
+ Decision = n.Decision,
516
+ Description = n.Description,
517
+ Color = n.Color,
518
+ IsPinned = n.IsPinned,
519
+ Width = n.Width,
520
+ Height = n.Height,
521
+ Data = n.Data
522
+ }).ToList();
523
+
524
+ var edges = graph.Edges.Select(e => new EdgeDto
525
+ {
526
+ Id = e.Id,
527
+ FromNodeId = e.FromNodeId,
528
+ ToNodeId = e.ToNodeId,
529
+ Condition = e.Condition
530
+ }).ToList();
531
+
532
+ var contentJson = JsonSerializer.Serialize(new CustomTemplateContentDto
533
+ {
534
+ Nodes = nodes,
535
+ Edges = edges
536
+ });
537
+
538
+ var template = new CustomTemplate
539
+ {
540
+ Id = Guid.NewGuid(),
541
+ UserId = userId,
542
+ Title = title,
543
+ Description = description,
544
+ Category = "Custom",
545
+ Icon = "BookOpen",
546
+ ContentJson = contentJson,
547
+ CreatedAt = DateTime.UtcNow
548
+ };
549
+
550
+ return await _customTemplateRepo.CreateAsync(template);
551
+ }
552
+
553
+ public async Task<IEnumerable<CustomTemplate>> GetCustomTemplatesAsync(Guid userId)
554
+ {
555
+ return await _customTemplateRepo.GetByUserIdAsync(userId);
556
+ }
557
+
558
+ private class CustomTemplateContentDto
559
+ {
560
+ public List<NodeDto> Nodes { get; set; } = new();
561
+ public List<EdgeDto> Edges { get; set; } = new();
562
+ }
563
  }
564
  }
FlowAPI.Application/Services/HabitService.cs CHANGED
@@ -7,11 +7,13 @@ namespace FlowAPI.Application.Services
7
  public class HabitService : IHabitService
8
  {
9
  private readonly IHabitRecordRepository _repo;
 
10
  private readonly IAchievementService _achievementService;
11
 
12
- public HabitService(IHabitRecordRepository repo, IAchievementService achievementService)
13
  {
14
  _repo = repo;
 
15
  _achievementService = achievementService;
16
  }
17
 
@@ -23,10 +25,24 @@ namespace FlowAPI.Application.Services
23
 
24
  public async Task<HabitRecordResponseDto> RecordHabitAsync(CreateHabitRecordDto dto)
25
  {
 
 
 
26
  var targetDate = dto.CheckedDate ?? DateTime.UtcNow;
27
  var existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);
28
  if (existing is not null) return MapToDto(existing);
29
 
 
 
 
 
 
 
 
 
 
 
 
30
  var record = new HabitRecord
31
  {
32
  Id = Guid.NewGuid(),
 
7
  public class HabitService : IHabitService
8
  {
9
  private readonly IHabitRecordRepository _repo;
10
+ private readonly IUserRepository _userRepo;
11
  private readonly IAchievementService _achievementService;
12
 
13
+ public HabitService(IHabitRecordRepository repo, IUserRepository userRepo, IAchievementService achievementService)
14
  {
15
  _repo = repo;
16
+ _userRepo = userRepo;
17
  _achievementService = achievementService;
18
  }
19
 
 
25
 
26
  public async Task<HabitRecordResponseDto> RecordHabitAsync(CreateHabitRecordDto dto)
27
  {
28
+ var user = await _userRepo.GetByIdAsync(dto.UserId);
29
+ if (user == null) throw new Exception("User not found.");
30
+
31
  var targetDate = dto.CheckedDate ?? DateTime.UtcNow;
32
  var existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);
33
  if (existing is not null) return MapToDto(existing);
34
 
35
+ if (user.SubscriptionTier == "Free")
36
+ {
37
+ var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId);
38
+ var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();
39
+
40
+ if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >= 3)
41
+ {
42
+ throw new InvalidOperationException("Free tier is limited to 3 habits.");
43
+ }
44
+ }
45
+
46
  var record = new HabitRecord
47
  {
48
  Id = Guid.NewGuid(),
FlowAPI.Application/Services/UserService.cs CHANGED
@@ -111,6 +111,11 @@ namespace FlowAPI.Application.Services
111
  if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;
112
  if (dto.IsPremium.HasValue) user.IsPremium = dto.IsPremium.Value;
113
  if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;
 
 
 
 
 
114
  if (!string.IsNullOrEmpty(dto.Password)) user.PasswordHash = HashPassword(dto.Password);
115
 
116
  var updated = await _repo.UpdateAsync(user);
@@ -141,7 +146,8 @@ namespace FlowAPI.Application.Services
141
  DisplayName = user.DisplayName,
142
  IsPremium = user.IsPremium,
143
  AvatarUrl = user.AvatarUrl,
144
- CreatedAt = user.CreatedAt
 
145
  };
146
  }
147
  }
 
111
  if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;
112
  if (dto.IsPremium.HasValue) user.IsPremium = dto.IsPremium.Value;
113
  if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;
114
+ if (dto.SubscriptionTier is not null)
115
+ {
116
+ user.SubscriptionTier = dto.SubscriptionTier;
117
+ user.IsPremium = dto.SubscriptionTier != "Free";
118
+ }
119
  if (!string.IsNullOrEmpty(dto.Password)) user.PasswordHash = HashPassword(dto.Password);
120
 
121
  var updated = await _repo.UpdateAsync(user);
 
146
  DisplayName = user.DisplayName,
147
  IsPremium = user.IsPremium,
148
  AvatarUrl = user.AvatarUrl,
149
+ CreatedAt = user.CreatedAt,
150
+ SubscriptionTier = user.SubscriptionTier
151
  };
152
  }
153
  }
FlowAPI.Domain/Entities/CustomTemplate.cs ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+
3
+ namespace FlowAPI.Domain.Entities
4
+ {
5
+ public class CustomTemplate
6
+ {
7
+ public Guid Id { get; set; }
8
+ public Guid UserId { get; set; }
9
+ public string Title { get; set; } = string.Empty;
10
+ public string Description { get; set; } = string.Empty;
11
+ public string Category { get; set; } = "Custom";
12
+ public string Icon { get; set; } = "BookOpen";
13
+ public string ContentJson { get; set; } = string.Empty; // Holds serialized nodes and edges
14
+ public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
15
+
16
+ // Navigation properties
17
+ public User User { get; set; } = null!;
18
+ }
19
+ }
FlowAPI.Domain/Entities/User.cs CHANGED
@@ -10,6 +10,11 @@ namespace FlowAPI.Domain.Entities
10
  public string? AvatarUrl { get; set; }
11
  public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
12
 
 
 
 
 
 
13
  // Navigation properties
14
  public ICollection<Graph> Graphs { get; set; } = new List<Graph>();
15
  public ICollection<HabitRecord> HabitRecords { get; set; } = new List<HabitRecord>();
 
10
  public string? AvatarUrl { get; set; }
11
  public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
12
 
13
+ // Subscription Tier info
14
+ public string SubscriptionTier { get; set; } = "Free"; // "Free", "Pro", "Ultra"
15
+ public int DailyAiGenerationsCount { get; set; }
16
+ public DateTime LastAiGenerationDate { get; set; } = DateTime.UtcNow;
17
+
18
  // Navigation properties
19
  public ICollection<Graph> Graphs { get; set; } = new List<Graph>();
20
  public ICollection<HabitRecord> HabitRecords { get; set; } = new List<HabitRecord>();
FlowAPI.Infrastructure/Data/AppDbContext.cs CHANGED
@@ -16,6 +16,7 @@ namespace FlowAPI.Infrastructure.Data
16
  public DbSet<Achievement> Achievements => Set<Achievement>();
17
  public DbSet<UserAchievement> UserAchievements => Set<UserAchievement>();
18
  public DbSet<SharedGraph> SharedGraphs => Set<SharedGraph>();
 
19
 
20
  protected override void OnModelCreating(ModelBuilder modelBuilder)
21
  {
@@ -29,6 +30,7 @@ namespace FlowAPI.Infrastructure.Data
29
  entity.Property(e => e.Email).IsRequired().HasMaxLength(256);
30
  entity.Property(e => e.PasswordHash).IsRequired();
31
  entity.Property(e => e.DisplayName).HasMaxLength(100);
 
32
  });
33
 
34
  // Graph
@@ -141,6 +143,22 @@ namespace FlowAPI.Infrastructure.Data
141
 
142
  entity.HasIndex(e => new { e.GraphId, e.SharedWithUserId }).IsUnique();
143
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  }
145
  }
146
  }
 
16
  public DbSet<Achievement> Achievements => Set<Achievement>();
17
  public DbSet<UserAchievement> UserAchievements => Set<UserAchievement>();
18
  public DbSet<SharedGraph> SharedGraphs => Set<SharedGraph>();
19
+ public DbSet<CustomTemplate> CustomTemplates => Set<CustomTemplate>();
20
 
21
  protected override void OnModelCreating(ModelBuilder modelBuilder)
22
  {
 
30
  entity.Property(e => e.Email).IsRequired().HasMaxLength(256);
31
  entity.Property(e => e.PasswordHash).IsRequired();
32
  entity.Property(e => e.DisplayName).HasMaxLength(100);
33
+ entity.Property(e => e.SubscriptionTier).HasDefaultValue("Free").HasMaxLength(50);
34
  });
35
 
36
  // Graph
 
143
 
144
  entity.HasIndex(e => new { e.GraphId, e.SharedWithUserId }).IsUnique();
145
  });
146
+
147
+ // CustomTemplate
148
+ modelBuilder.Entity<CustomTemplate>(entity =>
149
+ {
150
+ entity.HasKey(e => e.Id);
151
+ entity.Property(e => e.Title).IsRequired().HasMaxLength(200);
152
+ entity.Property(e => e.Description).HasMaxLength(1000);
153
+ entity.Property(e => e.Category).HasMaxLength(100);
154
+ entity.Property(e => e.Icon).HasMaxLength(100);
155
+ entity.Property(e => e.ContentJson).IsRequired().HasMaxLength(10000000);
156
+
157
+ entity.HasOne(e => e.User)
158
+ .WithMany()
159
+ .HasForeignKey(e => e.UserId)
160
+ .OnDelete(DeleteBehavior.Cascade);
161
+ });
162
  }
163
  }
164
  }
FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.Designer.cs ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // <auto-generated />
2
+ using System;
3
+ using FlowAPI.Infrastructure.Data;
4
+ using Microsoft.EntityFrameworkCore;
5
+ using Microsoft.EntityFrameworkCore.Infrastructure;
6
+ using Microsoft.EntityFrameworkCore.Migrations;
7
+ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
8
+
9
+ #nullable disable
10
+
11
+ namespace FlowAPI.Infrastructure.Migrations
12
+ {
13
+ [DbContext(typeof(AppDbContext))]
14
+ [Migration("20260607131226_AddSubscriptionTiers")]
15
+ partial class AddSubscriptionTiers
16
+ {
17
+ /// <inheritdoc />
18
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
19
+ {
20
+ #pragma warning disable 612, 618
21
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.8");
22
+
23
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Achievement", b =>
24
+ {
25
+ b.Property<Guid>("Id")
26
+ .ValueGeneratedOnAdd()
27
+ .HasColumnType("TEXT");
28
+
29
+ b.Property<string>("Category")
30
+ .IsRequired()
31
+ .HasMaxLength(100)
32
+ .HasColumnType("TEXT");
33
+
34
+ b.Property<string>("Description")
35
+ .IsRequired()
36
+ .HasColumnType("TEXT");
37
+
38
+ b.Property<string>("IconUrl")
39
+ .IsRequired()
40
+ .HasColumnType("TEXT");
41
+
42
+ b.Property<int>("RewardPoints")
43
+ .HasColumnType("INTEGER");
44
+
45
+ b.Property<int>("TargetValue")
46
+ .HasColumnType("INTEGER");
47
+
48
+ b.Property<string>("Title")
49
+ .IsRequired()
50
+ .HasMaxLength(200)
51
+ .HasColumnType("TEXT");
52
+
53
+ b.Property<string>("TriggerEventName")
54
+ .IsRequired()
55
+ .HasMaxLength(100)
56
+ .HasColumnType("TEXT");
57
+
58
+ b.Property<int>("Type")
59
+ .HasColumnType("INTEGER");
60
+
61
+ b.HasKey("Id");
62
+
63
+ b.ToTable("Achievements");
64
+ });
65
+
66
+ modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b =>
67
+ {
68
+ b.Property<Guid>("Id")
69
+ .ValueGeneratedOnAdd()
70
+ .HasColumnType("TEXT");
71
+
72
+ b.Property<string>("Category")
73
+ .IsRequired()
74
+ .HasMaxLength(100)
75
+ .HasColumnType("TEXT");
76
+
77
+ b.Property<string>("ContentJson")
78
+ .IsRequired()
79
+ .HasMaxLength(10000000)
80
+ .HasColumnType("TEXT");
81
+
82
+ b.Property<DateTime>("CreatedAt")
83
+ .HasColumnType("TEXT");
84
+
85
+ b.Property<string>("Description")
86
+ .IsRequired()
87
+ .HasMaxLength(1000)
88
+ .HasColumnType("TEXT");
89
+
90
+ b.Property<string>("Icon")
91
+ .IsRequired()
92
+ .HasMaxLength(100)
93
+ .HasColumnType("TEXT");
94
+
95
+ b.Property<string>("Title")
96
+ .IsRequired()
97
+ .HasMaxLength(200)
98
+ .HasColumnType("TEXT");
99
+
100
+ b.Property<Guid>("UserId")
101
+ .HasColumnType("TEXT");
102
+
103
+ b.HasKey("Id");
104
+
105
+ b.HasIndex("UserId");
106
+
107
+ b.ToTable("CustomTemplates");
108
+ });
109
+
110
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
111
+ {
112
+ b.Property<Guid>("Id")
113
+ .ValueGeneratedOnAdd()
114
+ .HasColumnType("TEXT");
115
+
116
+ b.Property<string>("Condition")
117
+ .IsRequired()
118
+ .HasMaxLength(500)
119
+ .HasColumnType("TEXT");
120
+
121
+ b.Property<Guid>("FromNodeId")
122
+ .HasColumnType("TEXT");
123
+
124
+ b.Property<Guid>("GraphId")
125
+ .HasColumnType("TEXT");
126
+
127
+ b.Property<Guid>("ToNodeId")
128
+ .HasColumnType("TEXT");
129
+
130
+ b.HasKey("Id");
131
+
132
+ b.HasIndex("FromNodeId");
133
+
134
+ b.HasIndex("GraphId");
135
+
136
+ b.HasIndex("ToNodeId");
137
+
138
+ b.ToTable("Edges");
139
+ });
140
+
141
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b =>
142
+ {
143
+ b.Property<Guid>("Id")
144
+ .ValueGeneratedOnAdd()
145
+ .HasColumnType("TEXT");
146
+
147
+ b.Property<DateTime>("CreatedAt")
148
+ .HasColumnType("TEXT");
149
+
150
+ b.Property<string>("Description")
151
+ .HasMaxLength(1000)
152
+ .HasColumnType("TEXT");
153
+
154
+ b.Property<string>("Title")
155
+ .IsRequired()
156
+ .HasMaxLength(200)
157
+ .HasColumnType("TEXT");
158
+
159
+ b.Property<DateTime>("UpdatedAt")
160
+ .HasColumnType("TEXT");
161
+
162
+ b.Property<Guid>("UserId")
163
+ .HasColumnType("TEXT");
164
+
165
+ b.HasKey("Id");
166
+
167
+ b.HasIndex("UserId");
168
+
169
+ b.ToTable("Graphs");
170
+ });
171
+
172
+ modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b =>
173
+ {
174
+ b.Property<Guid>("Id")
175
+ .ValueGeneratedOnAdd()
176
+ .HasColumnType("TEXT");
177
+
178
+ b.Property<DateTime>("CheckedDate")
179
+ .HasColumnType("TEXT");
180
+
181
+ b.Property<string>("HabitName")
182
+ .IsRequired()
183
+ .HasMaxLength(100)
184
+ .HasColumnType("TEXT");
185
+
186
+ b.Property<int>("StreakCount")
187
+ .HasColumnType("INTEGER");
188
+
189
+ b.Property<Guid>("UserId")
190
+ .HasColumnType("TEXT");
191
+
192
+ b.HasKey("Id");
193
+
194
+ b.HasIndex("UserId");
195
+
196
+ b.ToTable("HabitRecords");
197
+ });
198
+
199
+ modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b =>
200
+ {
201
+ b.Property<Guid>("Id")
202
+ .ValueGeneratedOnAdd()
203
+ .HasColumnType("TEXT");
204
+
205
+ b.Property<DateTime>("CreatedAt")
206
+ .HasColumnType("TEXT");
207
+
208
+ b.Property<Guid>("GraphId")
209
+ .HasColumnType("TEXT");
210
+
211
+ b.Property<string>("Permission")
212
+ .IsRequired()
213
+ .ValueGeneratedOnAdd()
214
+ .HasMaxLength(50)
215
+ .HasColumnType("TEXT")
216
+ .HasDefaultValue("Read");
217
+
218
+ b.Property<Guid>("SharedWithUserId")
219
+ .HasColumnType("TEXT");
220
+
221
+ b.HasKey("Id");
222
+
223
+ b.HasIndex("SharedWithUserId");
224
+
225
+ b.HasIndex("GraphId", "SharedWithUserId")
226
+ .IsUnique();
227
+
228
+ b.ToTable("SharedGraphs");
229
+ });
230
+
231
+ modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b =>
232
+ {
233
+ b.Property<Guid>("Id")
234
+ .ValueGeneratedOnAdd()
235
+ .HasColumnType("TEXT");
236
+
237
+ b.Property<string>("Color")
238
+ .HasMaxLength(100)
239
+ .HasColumnType("TEXT");
240
+
241
+ b.Property<DateTime>("CreatedAt")
242
+ .HasColumnType("TEXT");
243
+
244
+ b.Property<string>("Data")
245
+ .HasMaxLength(10000000)
246
+ .HasColumnType("TEXT");
247
+
248
+ b.Property<string>("Decision")
249
+ .HasMaxLength(1000000)
250
+ .HasColumnType("TEXT");
251
+
252
+ b.Property<string>("Description")
253
+ .HasMaxLength(10000)
254
+ .HasColumnType("TEXT");
255
+
256
+ b.Property<Guid>("GraphId")
257
+ .HasColumnType("TEXT");
258
+
259
+ b.Property<double?>("Height")
260
+ .HasColumnType("REAL");
261
+
262
+ b.Property<bool>("IsPinned")
263
+ .HasColumnType("INTEGER");
264
+
265
+ b.Property<string>("Label")
266
+ .IsRequired()
267
+ .HasMaxLength(1000)
268
+ .HasColumnType("TEXT");
269
+
270
+ b.Property<double>("PosX")
271
+ .HasColumnType("REAL");
272
+
273
+ b.Property<double>("PosY")
274
+ .HasColumnType("REAL");
275
+
276
+ b.Property<string>("State")
277
+ .IsRequired()
278
+ .ValueGeneratedOnAdd()
279
+ .HasColumnType("TEXT")
280
+ .HasDefaultValue("Pending");
281
+
282
+ b.Property<string>("Type")
283
+ .IsRequired()
284
+ .ValueGeneratedOnAdd()
285
+ .HasMaxLength(100)
286
+ .HasColumnType("TEXT")
287
+ .HasDefaultValue("sketch");
288
+
289
+ b.Property<double?>("Width")
290
+ .HasColumnType("REAL");
291
+
292
+ b.HasKey("Id");
293
+
294
+ b.HasIndex("GraphId");
295
+
296
+ b.ToTable("TaskNodes");
297
+ });
298
+
299
+ modelBuilder.Entity("FlowAPI.Domain.Entities.User", b =>
300
+ {
301
+ b.Property<Guid>("Id")
302
+ .ValueGeneratedOnAdd()
303
+ .HasColumnType("TEXT");
304
+
305
+ b.Property<string>("AvatarUrl")
306
+ .HasColumnType("TEXT");
307
+
308
+ b.Property<DateTime>("CreatedAt")
309
+ .HasColumnType("TEXT");
310
+
311
+ b.Property<int>("DailyAiGenerationsCount")
312
+ .HasColumnType("INTEGER");
313
+
314
+ b.Property<string>("DisplayName")
315
+ .IsRequired()
316
+ .HasMaxLength(100)
317
+ .HasColumnType("TEXT");
318
+
319
+ b.Property<string>("Email")
320
+ .IsRequired()
321
+ .HasMaxLength(256)
322
+ .HasColumnType("TEXT");
323
+
324
+ b.Property<bool>("IsPremium")
325
+ .HasColumnType("INTEGER");
326
+
327
+ b.Property<DateTime>("LastAiGenerationDate")
328
+ .HasColumnType("TEXT");
329
+
330
+ b.Property<string>("PasswordHash")
331
+ .IsRequired()
332
+ .HasColumnType("TEXT");
333
+
334
+ b.Property<string>("SubscriptionTier")
335
+ .IsRequired()
336
+ .ValueGeneratedOnAdd()
337
+ .HasMaxLength(50)
338
+ .HasColumnType("TEXT")
339
+ .HasDefaultValue("Free");
340
+
341
+ b.HasKey("Id");
342
+
343
+ b.HasIndex("Email")
344
+ .IsUnique();
345
+
346
+ b.ToTable("Users");
347
+ });
348
+
349
+ modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b =>
350
+ {
351
+ b.Property<Guid>("Id")
352
+ .ValueGeneratedOnAdd()
353
+ .HasColumnType("TEXT");
354
+
355
+ b.Property<Guid>("AchievementId")
356
+ .HasColumnType("TEXT");
357
+
358
+ b.Property<int>("CurrentValue")
359
+ .HasColumnType("INTEGER");
360
+
361
+ b.Property<bool>("IsUnlocked")
362
+ .HasColumnType("INTEGER");
363
+
364
+ b.Property<DateTime?>("UnlockedAt")
365
+ .HasColumnType("TEXT");
366
+
367
+ b.Property<Guid>("UserId")
368
+ .HasColumnType("TEXT");
369
+
370
+ b.HasKey("Id");
371
+
372
+ b.HasIndex("AchievementId");
373
+
374
+ b.HasIndex("UserId");
375
+
376
+ b.ToTable("UserAchievements");
377
+ });
378
+
379
+ modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b =>
380
+ {
381
+ b.HasOne("FlowAPI.Domain.Entities.User", "User")
382
+ .WithMany()
383
+ .HasForeignKey("UserId")
384
+ .OnDelete(DeleteBehavior.Cascade)
385
+ .IsRequired();
386
+
387
+ b.Navigation("User");
388
+ });
389
+
390
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
391
+ {
392
+ b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode")
393
+ .WithMany("OutgoingEdges")
394
+ .HasForeignKey("FromNodeId")
395
+ .OnDelete(DeleteBehavior.Cascade)
396
+ .IsRequired();
397
+
398
+ b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph")
399
+ .WithMany("Edges")
400
+ .HasForeignKey("GraphId")
401
+ .OnDelete(DeleteBehavior.Cascade)
402
+ .IsRequired();
403
+
404
+ b.HasOne("FlowAPI.Domain.Entities.TaskNode", "ToNode")
405
+ .WithMany("IncomingEdges")
406
+ .HasForeignKey("ToNodeId")
407
+ .OnDelete(DeleteBehavior.Cascade)
408
+ .IsRequired();
409
+
410
+ b.Navigation("FromNode");
411
+
412
+ b.Navigation("Graph");
413
+
414
+ b.Navigation("ToNode");
415
+ });
416
+
417
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b =>
418
+ {
419
+ b.HasOne("FlowAPI.Domain.Entities.User", "User")
420
+ .WithMany("Graphs")
421
+ .HasForeignKey("UserId")
422
+ .OnDelete(DeleteBehavior.Cascade)
423
+ .IsRequired();
424
+
425
+ b.Navigation("User");
426
+ });
427
+
428
+ modelBuilder.Entity("FlowAPI.Domain.Entities.HabitRecord", b =>
429
+ {
430
+ b.HasOne("FlowAPI.Domain.Entities.User", "User")
431
+ .WithMany("HabitRecords")
432
+ .HasForeignKey("UserId")
433
+ .OnDelete(DeleteBehavior.Cascade)
434
+ .IsRequired();
435
+
436
+ b.Navigation("User");
437
+ });
438
+
439
+ modelBuilder.Entity("FlowAPI.Domain.Entities.SharedGraph", b =>
440
+ {
441
+ b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph")
442
+ .WithMany("SharedGraphs")
443
+ .HasForeignKey("GraphId")
444
+ .OnDelete(DeleteBehavior.Cascade)
445
+ .IsRequired();
446
+
447
+ b.HasOne("FlowAPI.Domain.Entities.User", "SharedWithUser")
448
+ .WithMany("SharedGraphs")
449
+ .HasForeignKey("SharedWithUserId")
450
+ .OnDelete(DeleteBehavior.Cascade)
451
+ .IsRequired();
452
+
453
+ b.Navigation("Graph");
454
+
455
+ b.Navigation("SharedWithUser");
456
+ });
457
+
458
+ modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b =>
459
+ {
460
+ b.HasOne("FlowAPI.Domain.Entities.Graph", "Graph")
461
+ .WithMany("Nodes")
462
+ .HasForeignKey("GraphId")
463
+ .OnDelete(DeleteBehavior.Cascade)
464
+ .IsRequired();
465
+
466
+ b.Navigation("Graph");
467
+ });
468
+
469
+ modelBuilder.Entity("FlowAPI.Domain.Entities.UserAchievement", b =>
470
+ {
471
+ b.HasOne("FlowAPI.Domain.Entities.Achievement", "Achievement")
472
+ .WithMany()
473
+ .HasForeignKey("AchievementId")
474
+ .OnDelete(DeleteBehavior.Cascade)
475
+ .IsRequired();
476
+
477
+ b.HasOne("FlowAPI.Domain.Entities.User", "User")
478
+ .WithMany("UserAchievements")
479
+ .HasForeignKey("UserId")
480
+ .OnDelete(DeleteBehavior.Cascade)
481
+ .IsRequired();
482
+
483
+ b.Navigation("Achievement");
484
+
485
+ b.Navigation("User");
486
+ });
487
+
488
+ modelBuilder.Entity("FlowAPI.Domain.Entities.Graph", b =>
489
+ {
490
+ b.Navigation("Edges");
491
+
492
+ b.Navigation("Nodes");
493
+
494
+ b.Navigation("SharedGraphs");
495
+ });
496
+
497
+ modelBuilder.Entity("FlowAPI.Domain.Entities.TaskNode", b =>
498
+ {
499
+ b.Navigation("IncomingEdges");
500
+
501
+ b.Navigation("OutgoingEdges");
502
+ });
503
+
504
+ modelBuilder.Entity("FlowAPI.Domain.Entities.User", b =>
505
+ {
506
+ b.Navigation("Graphs");
507
+
508
+ b.Navigation("HabitRecords");
509
+
510
+ b.Navigation("SharedGraphs");
511
+
512
+ b.Navigation("UserAchievements");
513
+ });
514
+ #pragma warning restore 612, 618
515
+ }
516
+ }
517
+ }
FlowAPI.Infrastructure/Migrations/20260607131226_AddSubscriptionTiers.cs ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using Microsoft.EntityFrameworkCore.Migrations;
3
+
4
+ #nullable disable
5
+
6
+ namespace FlowAPI.Infrastructure.Migrations
7
+ {
8
+ /// <inheritdoc />
9
+ public partial class AddSubscriptionTiers : Migration
10
+ {
11
+ /// <inheritdoc />
12
+ protected override void Up(MigrationBuilder migrationBuilder)
13
+ {
14
+ migrationBuilder.AddColumn<int>(
15
+ name: "DailyAiGenerationsCount",
16
+ table: "Users",
17
+ type: "INTEGER",
18
+ nullable: false,
19
+ defaultValue: 0);
20
+
21
+ migrationBuilder.AddColumn<DateTime>(
22
+ name: "LastAiGenerationDate",
23
+ table: "Users",
24
+ type: "TEXT",
25
+ nullable: false,
26
+ defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
27
+
28
+ migrationBuilder.AddColumn<string>(
29
+ name: "SubscriptionTier",
30
+ table: "Users",
31
+ type: "TEXT",
32
+ maxLength: 50,
33
+ nullable: false,
34
+ defaultValue: "Free");
35
+
36
+ migrationBuilder.CreateTable(
37
+ name: "CustomTemplates",
38
+ columns: table => new
39
+ {
40
+ Id = table.Column<Guid>(type: "TEXT", nullable: false),
41
+ UserId = table.Column<Guid>(type: "TEXT", nullable: false),
42
+ Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
43
+ Description = table.Column<string>(type: "TEXT", maxLength: 1000, nullable: false),
44
+ Category = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
45
+ Icon = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
46
+ ContentJson = table.Column<string>(type: "TEXT", maxLength: 10000000, nullable: false),
47
+ CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
48
+ },
49
+ constraints: table =>
50
+ {
51
+ table.PrimaryKey("PK_CustomTemplates", x => x.Id);
52
+ table.ForeignKey(
53
+ name: "FK_CustomTemplates_Users_UserId",
54
+ column: x => x.UserId,
55
+ principalTable: "Users",
56
+ principalColumn: "Id",
57
+ onDelete: ReferentialAction.Cascade);
58
+ });
59
+
60
+ migrationBuilder.CreateIndex(
61
+ name: "IX_CustomTemplates_UserId",
62
+ table: "CustomTemplates",
63
+ column: "UserId");
64
+ }
65
+
66
+ /// <inheritdoc />
67
+ protected override void Down(MigrationBuilder migrationBuilder)
68
+ {
69
+ migrationBuilder.DropTable(
70
+ name: "CustomTemplates");
71
+
72
+ migrationBuilder.DropColumn(
73
+ name: "DailyAiGenerationsCount",
74
+ table: "Users");
75
+
76
+ migrationBuilder.DropColumn(
77
+ name: "LastAiGenerationDate",
78
+ table: "Users");
79
+
80
+ migrationBuilder.DropColumn(
81
+ name: "SubscriptionTier",
82
+ table: "Users");
83
+ }
84
+ }
85
+ }
FlowAPI.Infrastructure/Migrations/AppDbContextModelSnapshot.cs CHANGED
@@ -60,6 +60,50 @@ namespace FlowAPI.Infrastructure.Migrations
60
  b.ToTable("Achievements");
61
  });
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
64
  {
65
  b.Property<Guid>("Id")
@@ -261,6 +305,9 @@ namespace FlowAPI.Infrastructure.Migrations
261
  b.Property<DateTime>("CreatedAt")
262
  .HasColumnType("TEXT");
263
 
 
 
 
264
  b.Property<string>("DisplayName")
265
  .IsRequired()
266
  .HasMaxLength(100)
@@ -274,10 +321,20 @@ namespace FlowAPI.Infrastructure.Migrations
274
  b.Property<bool>("IsPremium")
275
  .HasColumnType("INTEGER");
276
 
 
 
 
277
  b.Property<string>("PasswordHash")
278
  .IsRequired()
279
  .HasColumnType("TEXT");
280
 
 
 
 
 
 
 
 
281
  b.HasKey("Id");
282
 
283
  b.HasIndex("Email")
@@ -316,6 +373,17 @@ namespace FlowAPI.Infrastructure.Migrations
316
  b.ToTable("UserAchievements");
317
  });
318
 
 
 
 
 
 
 
 
 
 
 
 
319
  modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
320
  {
321
  b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode")
 
60
  b.ToTable("Achievements");
61
  });
62
 
63
+ modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b =>
64
+ {
65
+ b.Property<Guid>("Id")
66
+ .ValueGeneratedOnAdd()
67
+ .HasColumnType("TEXT");
68
+
69
+ b.Property<string>("Category")
70
+ .IsRequired()
71
+ .HasMaxLength(100)
72
+ .HasColumnType("TEXT");
73
+
74
+ b.Property<string>("ContentJson")
75
+ .IsRequired()
76
+ .HasMaxLength(10000000)
77
+ .HasColumnType("TEXT");
78
+
79
+ b.Property<DateTime>("CreatedAt")
80
+ .HasColumnType("TEXT");
81
+
82
+ b.Property<string>("Description")
83
+ .IsRequired()
84
+ .HasMaxLength(1000)
85
+ .HasColumnType("TEXT");
86
+
87
+ b.Property<string>("Icon")
88
+ .IsRequired()
89
+ .HasMaxLength(100)
90
+ .HasColumnType("TEXT");
91
+
92
+ b.Property<string>("Title")
93
+ .IsRequired()
94
+ .HasMaxLength(200)
95
+ .HasColumnType("TEXT");
96
+
97
+ b.Property<Guid>("UserId")
98
+ .HasColumnType("TEXT");
99
+
100
+ b.HasKey("Id");
101
+
102
+ b.HasIndex("UserId");
103
+
104
+ b.ToTable("CustomTemplates");
105
+ });
106
+
107
  modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
108
  {
109
  b.Property<Guid>("Id")
 
305
  b.Property<DateTime>("CreatedAt")
306
  .HasColumnType("TEXT");
307
 
308
+ b.Property<int>("DailyAiGenerationsCount")
309
+ .HasColumnType("INTEGER");
310
+
311
  b.Property<string>("DisplayName")
312
  .IsRequired()
313
  .HasMaxLength(100)
 
321
  b.Property<bool>("IsPremium")
322
  .HasColumnType("INTEGER");
323
 
324
+ b.Property<DateTime>("LastAiGenerationDate")
325
+ .HasColumnType("TEXT");
326
+
327
  b.Property<string>("PasswordHash")
328
  .IsRequired()
329
  .HasColumnType("TEXT");
330
 
331
+ b.Property<string>("SubscriptionTier")
332
+ .IsRequired()
333
+ .ValueGeneratedOnAdd()
334
+ .HasMaxLength(50)
335
+ .HasColumnType("TEXT")
336
+ .HasDefaultValue("Free");
337
+
338
  b.HasKey("Id");
339
 
340
  b.HasIndex("Email")
 
373
  b.ToTable("UserAchievements");
374
  });
375
 
376
+ modelBuilder.Entity("FlowAPI.Domain.Entities.CustomTemplate", b =>
377
+ {
378
+ b.HasOne("FlowAPI.Domain.Entities.User", "User")
379
+ .WithMany()
380
+ .HasForeignKey("UserId")
381
+ .OnDelete(DeleteBehavior.Cascade)
382
+ .IsRequired();
383
+
384
+ b.Navigation("User");
385
+ });
386
+
387
  modelBuilder.Entity("FlowAPI.Domain.Entities.Edge", b =>
388
  {
389
  b.HasOne("FlowAPI.Domain.Entities.TaskNode", "FromNode")
FlowAPI.Infrastructure/Repositories/CustomTemplateRepository.cs ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using FlowAPI.Application.Interfaces;
2
+ using FlowAPI.Domain.Entities;
3
+ using FlowAPI.Infrastructure.Data;
4
+ using Microsoft.EntityFrameworkCore;
5
+ using System;
6
+ using System.Collections.Generic;
7
+ using System.Linq;
8
+ using System.Threading.Tasks;
9
+
10
+ namespace FlowAPI.Infrastructure.Repositories
11
+ {
12
+ public class CustomTemplateRepository : ICustomTemplateRepository
13
+ {
14
+ private readonly AppDbContext _context;
15
+
16
+ public CustomTemplateRepository(AppDbContext context)
17
+ {
18
+ _context = context;
19
+ }
20
+
21
+ public async Task<CustomTemplate?> GetByIdAsync(Guid id)
22
+ {
23
+ return await _context.CustomTemplates.FirstOrDefaultAsync(t => t.Id == id);
24
+ }
25
+
26
+ public async Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId)
27
+ {
28
+ return await _context.CustomTemplates
29
+ .Where(t => t.UserId == userId)
30
+ .OrderByDescending(t => t.CreatedAt)
31
+ .ToListAsync();
32
+ }
33
+
34
+ public async Task<CustomTemplate> CreateAsync(CustomTemplate template)
35
+ {
36
+ _context.CustomTemplates.Add(template);
37
+ await _context.SaveChangesAsync();
38
+ return template;
39
+ }
40
+ }
41
+ }
FlowAPI/Controllers/AIController.cs CHANGED
@@ -28,6 +28,10 @@ namespace FlowAPI.Controllers
28
  {
29
  return StatusCode(403, new { message = "Premium subscription required for AI generation." });
30
  }
 
 
 
 
31
  catch (Exception ex)
32
  {
33
  return BadRequest(new { message = ex.Message });
@@ -42,6 +46,10 @@ namespace FlowAPI.Controllers
42
  var response = await _aiService.GenerateGoalGraphAsync(request);
43
  return Ok(response);
44
  }
 
 
 
 
45
  catch (Exception ex)
46
  {
47
  return BadRequest(new { message = ex.Message });
@@ -56,6 +64,10 @@ namespace FlowAPI.Controllers
56
  var response = await _aiService.CanvasAssistAsync(request);
57
  return Ok(response);
58
  }
 
 
 
 
59
  catch (Exception ex)
60
  {
61
  return BadRequest(new { message = ex.Message });
 
28
  {
29
  return StatusCode(403, new { message = "Premium subscription required for AI generation." });
30
  }
31
+ catch (InvalidOperationException ex)
32
+ {
33
+ return StatusCode(403, new { message = ex.Message });
34
+ }
35
  catch (Exception ex)
36
  {
37
  return BadRequest(new { message = ex.Message });
 
46
  var response = await _aiService.GenerateGoalGraphAsync(request);
47
  return Ok(response);
48
  }
49
+ catch (InvalidOperationException ex)
50
+ {
51
+ return StatusCode(403, new { message = ex.Message });
52
+ }
53
  catch (Exception ex)
54
  {
55
  return BadRequest(new { message = ex.Message });
 
64
  var response = await _aiService.CanvasAssistAsync(request);
65
  return Ok(response);
66
  }
67
+ catch (InvalidOperationException ex)
68
+ {
69
+ return StatusCode(403, new { message = ex.Message });
70
+ }
71
  catch (Exception ex)
72
  {
73
  return BadRequest(new { message = ex.Message });
FlowAPI/Controllers/GraphsController.cs CHANGED
@@ -32,9 +32,26 @@ namespace FlowAPI.Controllers
32
  }
33
 
34
  [HttpGet("templates")]
35
- public ActionResult<IEnumerable<TemplateInfoDto>> GetTemplates()
36
  {
37
- var templates = TemplateLibrary.GetTemplateInfos();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  return Ok(templates);
39
  }
40
 
@@ -73,8 +90,15 @@ namespace FlowAPI.Controllers
73
  {
74
  if (CurrentUserId == Guid.Empty) return Unauthorized();
75
 
76
- var graph = await _service.CreateAsync(dto, CurrentUserId);
77
- return CreatedAtAction(nameof(GetById), new { id = graph.Id }, graph);
 
 
 
 
 
 
 
78
  }
79
 
80
  [HttpPut("{id:guid}")]
@@ -102,9 +126,16 @@ namespace FlowAPI.Controllers
102
  {
103
  if (CurrentUserId == Guid.Empty) return Unauthorized();
104
 
105
- var result = await _service.SaveFullGraphAsync(id, dto, CurrentUserId);
106
- if (!result) return NotFound();
107
- return Ok();
 
 
 
 
 
 
 
108
  }
109
 
110
  [HttpPost("{id:guid}/share")]
@@ -112,9 +143,16 @@ namespace FlowAPI.Controllers
112
  {
113
  if (CurrentUserId == Guid.Empty) return Unauthorized();
114
 
115
- var result = await _service.ShareGraphAsync(id, CurrentUserId, dto);
116
- if (result is null) return BadRequest("Не вдалося поділитися дошкою. Перевірте email або права.");
117
- return Ok(result);
 
 
 
 
 
 
 
118
  }
119
 
120
  [HttpGet("{id:guid}/shares")]
@@ -135,5 +173,31 @@ namespace FlowAPI.Controllers
135
  if (!result) return NotFound();
136
  return NoContent();
137
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  }
139
  }
 
32
  }
33
 
34
  [HttpGet("templates")]
35
+ public async Task<ActionResult<IEnumerable<TemplateInfoDto>>> GetTemplates()
36
  {
37
+ var templates = TemplateLibrary.GetTemplateInfos().ToList();
38
+
39
+ var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
40
+ if (Guid.TryParse(userIdStr, out var userId))
41
+ {
42
+ var customTemplates = await _service.GetCustomTemplatesAsync(userId);
43
+ foreach (var t in customTemplates)
44
+ {
45
+ templates.Add(new TemplateInfoDto
46
+ {
47
+ Key = t.Id.ToString(),
48
+ Title = t.Title,
49
+ Description = t.Description,
50
+ Icon = t.Icon,
51
+ Category = t.Category
52
+ });
53
+ }
54
+ }
55
  return Ok(templates);
56
  }
57
 
 
90
  {
91
  if (CurrentUserId == Guid.Empty) return Unauthorized();
92
 
93
+ try
94
+ {
95
+ var graph = await _service.CreateAsync(dto, CurrentUserId);
96
+ return CreatedAtAction(nameof(GetById), new { id = graph.Id }, graph);
97
+ }
98
+ catch (InvalidOperationException ex)
99
+ {
100
+ return BadRequest(new { message = ex.Message });
101
+ }
102
  }
103
 
104
  [HttpPut("{id:guid}")]
 
126
  {
127
  if (CurrentUserId == Guid.Empty) return Unauthorized();
128
 
129
+ try
130
+ {
131
+ var result = await _service.SaveFullGraphAsync(id, dto, CurrentUserId);
132
+ if (!result) return NotFound();
133
+ return Ok();
134
+ }
135
+ catch (InvalidOperationException ex)
136
+ {
137
+ return BadRequest(new { message = ex.Message });
138
+ }
139
  }
140
 
141
  [HttpPost("{id:guid}/share")]
 
143
  {
144
  if (CurrentUserId == Guid.Empty) return Unauthorized();
145
 
146
+ try
147
+ {
148
+ var result = await _service.ShareGraphAsync(id, CurrentUserId, dto);
149
+ if (result is null) return BadRequest("Не вдалося поділитися дошкою. Перевірте email або права.");
150
+ return Ok(result);
151
+ }
152
+ catch (InvalidOperationException ex)
153
+ {
154
+ return BadRequest(new { message = ex.Message });
155
+ }
156
  }
157
 
158
  [HttpGet("{id:guid}/shares")]
 
173
  if (!result) return NotFound();
174
  return NoContent();
175
  }
176
+
177
+ [HttpPost("{id:guid}/save-as-template")]
178
+ public async Task<IActionResult> SaveAsTemplate(Guid id, [FromBody] SaveTemplateDto dto)
179
+ {
180
+ if (CurrentUserId == Guid.Empty) return Unauthorized();
181
+
182
+ try
183
+ {
184
+ var template = await _service.SaveAsTemplateAsync(id, CurrentUserId, dto.Title, dto.Description);
185
+ return Ok(new { message = "Template saved successfully", templateId = template.Id });
186
+ }
187
+ catch (InvalidOperationException ex)
188
+ {
189
+ return BadRequest(new { message = ex.Message });
190
+ }
191
+ catch (Exception ex)
192
+ {
193
+ return BadRequest(new { message = ex.Message });
194
+ }
195
+ }
196
+ }
197
+
198
+ public class SaveTemplateDto
199
+ {
200
+ public string Title { get; set; } = string.Empty;
201
+ public string Description { get; set; } = string.Empty;
202
  }
203
  }
FlowAPI/Controllers/HabitsController.cs CHANGED
@@ -25,8 +25,15 @@ namespace FlowAPI.Controllers
25
  [HttpPost("record")]
26
  public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto)
27
  {
28
- var record = await _service.RecordHabitAsync(dto);
29
- return Ok(record);
 
 
 
 
 
 
 
30
  }
31
 
32
  [HttpGet("streak/{userId:guid}/{habitName}")]
 
25
  [HttpPost("record")]
26
  public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto)
27
  {
28
+ try
29
+ {
30
+ var record = await _service.RecordHabitAsync(dto);
31
+ return Ok(record);
32
+ }
33
+ catch (InvalidOperationException ex)
34
+ {
35
+ return BadRequest(new { message = ex.Message });
36
+ }
37
  }
38
 
39
  [HttpGet("streak/{userId:guid}/{habitName}")]
FlowAPI/Controllers/PaymentsController.cs CHANGED
@@ -8,10 +8,12 @@ namespace FlowAPI.Controllers
8
  public class PaymentsController : ControllerBase
9
  {
10
  private readonly IPaymentService _paymentService;
 
11
 
12
- public PaymentsController(IPaymentService paymentService)
13
  {
14
  _paymentService = paymentService;
 
15
  }
16
 
17
  [HttpPost("create-checkout-session/{userId:guid}")]
@@ -31,5 +33,37 @@ namespace FlowAPI.Controllers
31
  if (result) return Ok();
32
  return BadRequest();
33
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  }
35
  }
 
8
  public class PaymentsController : ControllerBase
9
  {
10
  private readonly IPaymentService _paymentService;
11
+ private readonly IUserRepository _userRepo;
12
 
13
+ public PaymentsController(IPaymentService paymentService, IUserRepository userRepo)
14
  {
15
  _paymentService = paymentService;
16
+ _userRepo = userRepo;
17
  }
18
 
19
  [HttpPost("create-checkout-session/{userId:guid}")]
 
33
  if (result) return Ok();
34
  return BadRequest();
35
  }
36
+
37
+ [HttpPost("change-tier/{userId:guid}")]
38
+ public async Task<IActionResult> ChangeTier(Guid userId, [FromBody] ChangeTierDto dto)
39
+ {
40
+ var user = await _userRepo.GetByIdAsync(userId);
41
+ if (user == null) return NotFound("User not found.");
42
+
43
+ var upperTier = dto.Tier.Trim();
44
+ if (upperTier != "Free" && upperTier != "Pro" && upperTier != "Ultra")
45
+ {
46
+ return BadRequest("Invalid tier. Must be 'Free', 'Pro', or 'Ultra'.");
47
+ }
48
+
49
+ user.SubscriptionTier = upperTier;
50
+ user.IsPremium = upperTier != "Free";
51
+ await _userRepo.UpdateAsync(user);
52
+
53
+ return Ok(new {
54
+ id = user.Id,
55
+ email = user.Email,
56
+ displayName = user.DisplayName,
57
+ isPremium = user.IsPremium,
58
+ avatarUrl = user.AvatarUrl,
59
+ createdAt = user.CreatedAt,
60
+ subscriptionTier = user.SubscriptionTier
61
+ });
62
+ }
63
+ }
64
+
65
+ public class ChangeTierDto
66
+ {
67
+ public string Tier { get; set; } = string.Empty;
68
  }
69
  }
FlowAPI/Program.cs CHANGED
@@ -28,6 +28,7 @@ namespace FlowAPI
28
  builder.Services.AddScoped<IAchievementRepository, AchievementRepository>();
29
  builder.Services.AddScoped<IUserAchievementRepository, UserAchievementRepository>();
30
  builder.Services.AddScoped<ISharedGraphRepository, SharedGraphRepository>();
 
31
 
32
  // --- Services (Application) ---
33
  builder.Services.AddScoped<ITokenService, TokenService>();
 
28
  builder.Services.AddScoped<IAchievementRepository, AchievementRepository>();
29
  builder.Services.AddScoped<IUserAchievementRepository, UserAchievementRepository>();
30
  builder.Services.AddScoped<ISharedGraphRepository, SharedGraphRepository>();
31
+ builder.Services.AddScoped<ICustomTemplateRepository, CustomTemplateRepository>();
32
 
33
  // --- Services (Application) ---
34
  builder.Services.AddScoped<ITokenService, TokenService>();