transactions

This commit is contained in:
2025-08-24 14:18:20 +02:00
parent 1b2d95344a
commit 5777e351bf
107 changed files with 4940 additions and 1266 deletions

View File

@@ -0,0 +1,28 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class EventRelationEstablisher: IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>(entity =>
{
entity.HasMany(d => d.Tags).WithMany(p => p.Events)
.UsingEntity<Dictionary<string, object>>(
"EventTag",
r => r.HasOne<Tag>().WithMany()
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Event>().WithMany()
.HasForeignKey("EventId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("EventId", "TagId");
j.ToTable("EventTags");
});
});
}
}

View File

@@ -0,0 +1,68 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class GalleryRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Gallery>(entity =>
{
entity.Property(e => e.IsArchived).HasDefaultValue(0);
entity.Property(e => e.IsFavorite).HasDefaultValue(0);
entity.Property(e => e.IsPublic).HasDefaultValue(1);
entity.HasOne(d => d.CreatedByNavigation).WithMany(p => p.Galleries)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.Event).WithMany(p => p.Galleries).HasForeignKey(d => d.EventId);
entity.HasMany(d => d.Photos).WithMany(p => p.Galleries)
.UsingEntity<Dictionary<string, object>>(
"GalleryPhoto",
r => r.HasOne<Photo>().WithMany()
.HasForeignKey("PhotoId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Gallery>().WithMany()
.HasForeignKey("GalleryId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("GalleryId", "PhotoId");
j.ToTable("GalleryPhotos");
});
entity.HasMany(d => d.Tags).WithMany(p => p.Galleries)
.UsingEntity<Dictionary<string, object>>(
"GalleryTag",
r => r.HasOne<Tag>().WithMany()
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Gallery>().WithMany()
.HasForeignKey("GalleryId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("GalleryId", "TagId");
j.ToTable("GalleryTags");
});
entity.HasMany(d => d.Users).WithMany(p => p.GalleriesNavigation)
.UsingEntity<Dictionary<string, object>>(
"GalleryUserViewer",
r => r.HasOne<User>().WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Gallery>().WithMany()
.HasForeignKey("GalleryId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("GalleryId", "UserId");
j.ToTable("GalleryUserViewers");
});
});
}
}

View File

@@ -0,0 +1,8 @@
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public interface IRelationEstablisher
{
void EstablishRelation(ModelBuilder modelBuilder);
}

View File

@@ -0,0 +1,68 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class PersonRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Photo>(entity =>
{
entity.Property(e => e.IsArchived).HasDefaultValue(0);
entity.Property(e => e.IsFavorite).HasDefaultValue(0);
entity.Property(e => e.IsPublic).HasDefaultValue(1);
entity.HasOne(d => d.CreatedByNavigation).WithMany(p => p.Photos)
.HasForeignKey(d => d.CreatedBy)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.Event).WithMany(p => p.Photos).HasForeignKey(d => d.EventId);
entity.HasMany(d => d.People).WithMany(p => p.PhotosNavigation)
.UsingEntity<Dictionary<string, object>>(
"PhotoPerson",
r => r.HasOne<Person>().WithMany()
.HasForeignKey("PersonId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Photo>().WithMany()
.HasForeignKey("PhotoId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("PhotoId", "PersonId");
j.ToTable("PhotoPersons");
});
entity.HasMany(d => d.Tags).WithMany(p => p.Photos)
.UsingEntity<Dictionary<string, object>>(
"PhotoTag",
r => r.HasOne<Tag>().WithMany()
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Photo>().WithMany()
.HasForeignKey("PhotoId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("PhotoId", "TagId");
j.ToTable("PhotoTags");
});
entity.HasMany(d => d.Users).WithMany(p => p.Photos)
.UsingEntity<Dictionary<string, object>>(
"PhotoUserBuyer",
r => r.HasOne<User>().WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Photo>().WithMany()
.HasForeignKey("PhotoId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("PhotoId", "UserId");
j.ToTable("PhotoUserBuyers");
});
});
}
}

View File

@@ -0,0 +1,307 @@
//using back.DataModels;
//using back.DTO;
//using back.persistance.blob;
//using back.services.ImageResizer;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.Hosting.Internal;
//namespace back.persistance.data.relations;
//public class PhotoContext : DbContext
//{
// private readonly IImageResizer _Resizer;
// private readonly IBlobStorageService _BlobStorage;
// private readonly TagContext _tagContext;
// private readonly EventContext _eventContext;
// private readonly PersonRelationEstablisher _personContext;
// public PhotoContext(DbContextOptions<PhotoContext> options, IHostEnvironment hostingEnvironment,
// IImageResizer resizer,
// IBlobStorageService blobStorage,
// TagContext tags,
// EventContext events,
// PersonRelationEstablisher persons
// ) : base(options)
// {
// _Resizer = resizer;
// _BlobStorage = blobStorage;
// _tagContext = tags;
// _eventContext = events;
// _personContext = persons;
// if (hostingEnvironment.IsDevelopment())
// {
// Database.EnsureCreated();
// }
// else
// {
// Database.Migrate();
// }
// }
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// // Photo -> Tags (muchos-a-muchos)
// modelBuilder.Entity<Photo>()
// .HasMany(p => p.Tags)
// .WithMany(t => t.Photos)
// .UsingEntity(j => j.ToTable("PhotoTags"));
// // Photo -> Persons (muchos-a-muchos)
// modelBuilder.Entity<Photo>()
// .HasMany(p => p.PersonsIn)
// .WithMany(per => per.Photos)
// .UsingEntity(j => j.ToTable("PhotoPersons"));
// // Photo -> Event (muchos-a-uno)
// modelBuilder.Entity<Photo>()
// .HasOne(p => p.Event)
// .WithMany() // Un evento puede tener múltiples fotos
// .HasForeignKey(p => p.EventId);
// // Photo -> Ranking (uno-a-uno)
// modelBuilder.Entity<Photo>()
// .HasOne(p => p.Ranking)
// .WithOne(r => r.Photo) // Un ranking está asociado a una sola foto
// .HasForeignKey<Photo>(p => p.RankingId);
// base.OnModelCreating(modelBuilder);
// }
// public async Task CreateNew(PhotoFormModel? form)
// {
// if (form == null) { return; }
// var photo = new Photo(
// Guid.NewGuid().ToString(),
// form.Title,
// form.Description ?? string.Empty,
// string.Empty, // LowResUrl will be set later
// string.Empty, // MidResUrl will be set later
// string.Empty, // HighResUrl will be set later
// DateTime.UtcNow,
// DateTime.UtcNow,
// form.UserId,
// form.UserId
// )
// {
// IsPublic = form.IsPublic
// };
// List<Task> tasks = [
// SaveBlob(photo, form),
// LinkTags(photo, form.Tags ?? [], form.UserId),
// LinkEvent(photo, form.Evento ?? "", form.UserId),
// LinkPersons(photo, form.People ?? [], form.UserId),
// ];
// await Task.WhenAll(tasks);
// await Photos.AddAsync(photo);
// await SaveChangesAsync();
// }
// private async Task LinkPersons(Photo photo, string[] personas, string updatedBy = "SYSTEM")
// {
// if (photo == null || personas == null || personas.Length == 0) return;
// foreach (var personId in personas)
// {
// var person = await _personContext.GetById(personId);
// if (person != null)
// {
// await LinkPersons(photo, person, updatedBy);
// }
// }
// }
// private async Task LinkPersons(Photo photo, Person tag, string updatedBy = "SYSTEM")
// {
// if (tag == null) return;
// // Ensure the tag exists
// if (await _personContext.Exists(tag.Id))
// {
// photo.PersonsIn ??= [];
// photo.PersonsIn.Add(tag);
// photo.UpdatedAt = DateTime.UtcNow;
// photo.UpdatedBy = updatedBy; // or use a more appropriate value
// }
// }
// private async Task LinkTags(Photo photo, string[] tags, string updatedBy = "SYSTEM")
// {
// if (photo == null || tags == null || tags.Length == 0) return;
// foreach (var tagId in tags)
// {
// var tag = await _tagContext.GetById(tagId);
// if (tag != null)
// {
// await LinkTag(photo, tag, updatedBy);
// }
// }
// }
// private async Task LinkTag(Photo photo, Tag tag, string updatedBy = "SYSTEM")
// {
// if (tag == null) return;
// // Ensure the tag exists
// if (await _tagContext.Exists(tag.Id))
// {
// photo.Tags.Add(tag);
// photo.UpdatedAt = DateTime.UtcNow;
// photo.UpdatedBy = updatedBy; // or use a more appropriate value
// }
// }
// private async Task LinkEvent(Photo photo, string eventId, string updatedBy = "SYSTEM")
// {
// if (string.IsNullOrEmpty(eventId)) return;
// var evento = await _eventContext.GetById(eventId);
// if (evento != null)
// {
// await LinkEvent(photo, evento, updatedBy);
// }
// }
// private async Task LinkEvent(Photo photo, Event? evento, string updatedBy = "SYSTEM")
// {
// if (evento == null) return;
// // Ensure the event exists
// if (await _eventContext.Exists(evento.Id))
// {
// photo.Event = evento;
// photo.UpdatedAt = DateTime.UtcNow;
// photo.UpdatedBy = updatedBy;
// }
// }
// private async Task SaveBlob(Photo photo, PhotoFormModel form)
// {
// if (form.Image != null && form.Image.Length > 0)
// {
// var lowRes = await _Resizer.ResizeImage(form.Image, 480);
// var midRes = await _Resizer.ResizeImage(form.Image, 720);
// // Upload images to blob storage
// photo.Extension = form.Image.FileName.Split('.').Last();
// photo.LowResUrl = $"low/{photo.Id}.webp";
// photo.MidResUrl = $"mid/{photo.Id}.webp";
// photo.HighResUrl = $"high/{photo.Id}.{photo.Extension}";
// await _BlobStorage.SaveAsync(lowRes, photo.LowResUrl);
// await _BlobStorage.SaveAsync(midRes, photo.MidResUrl);
// await _BlobStorage.SaveAsync(form.Image.OpenReadStream(), photo.HighResUrl);
// }
// }
// public async Task<Photo?> GetById(string id)
// {
// return await GetById(Guid.Parse(id));
// }
// public async Task<Photo?> GetById(Guid id)
// {
// try
// {
// return await Photos.FindAsync(id);
// }
// catch
// {
// return null;
// }
// }
// public async Task<int> GetTotalItems()
// {
// try
// {
// return await Photos.CountAsync();
// }
// catch
// {
// return 0;
// }
// }
// public async Task<IEnumerable<Photo>?> GetPage(int page = 1, int pageSize = 20)
// {
// if (page < 1) page = 1;
// if (pageSize < 1) pageSize = 20;
// try
// {
// return await Photos
// .OrderByDescending(p => p.CreatedAt)
// .Skip((page - 1) * pageSize)
// .Take(pageSize)
// .ToListAsync();
// }
// catch
// {
// return null;
// }
// }
// public async Task<bool> Exists(Photo? photo)
// {
// try
// {
// if (photo == null) return false;
// if (string.IsNullOrEmpty(photo.Id)) return false;
// return await Photos.AnyAsync(p => p.Id == photo.Id);
// }
// catch
// {
// return false; // Handle exceptions gracefully
// }
// }
// public async Task<bool> Exists(string id)
// {
// try
// {
// if (string.IsNullOrEmpty(id)) return false;
// return await Photos.AnyAsync(p => p.Id == id);
// }
// catch
// {
// return false; // Handle exceptions gracefully
// }
// }
// public async Task Delete(Photo photo)
// {
// if (photo == null) return;
// if (await Exists(photo))
// {
// // Delete the photo from blob storage
// if (!string.IsNullOrEmpty(photo.LowResUrl))
// await _BlobStorage.DeleteAsync(photo.LowResUrl);
// if (!string.IsNullOrEmpty(photo.MidResUrl))
// await _BlobStorage.DeleteAsync(photo.MidResUrl);
// if (!string.IsNullOrEmpty(photo.HighResUrl))
// await _BlobStorage.DeleteAsync(photo.HighResUrl);
// Photos.Remove(photo);
// await SaveChangesAsync();
// }
// }
// public async Task Update(Photo photo)
// {
// if (photo == null) return;
// if (await Exists(photo))
// {
// var evento = photo.Event;
// photo.Event = null;
// await LinkEvent(photo, evento, photo.UpdatedBy);
// var tags = photo.Tags.Select(t => t.Id);
// photo.Tags.Clear();
// await LinkTags(photo, [.. tags], photo.UpdatedBy);
// var persons = photo.PersonsIn?.Select(t => t.Id) ?? [];
// photo.PersonsIn = null;
// await LinkPersons(photo, [.. persons], photo.UpdatedBy);
// Photos.Update(photo);
// await SaveChangesAsync();
// }
// }
//}

View File

@@ -0,0 +1,15 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class PhotoRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>(entity =>
{
entity.HasOne(d => d.SocialMedia).WithMany(p => p.People).HasForeignKey(d => d.SocialMediaId);
});
}
}

View File

@@ -0,0 +1,25 @@
//using back.DataModels;
//using Microsoft.EntityFrameworkCore;
//namespace back.persistance.data.relations;
//public class RoleContext : DbContext
//{
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// // Role -> Permissions (muchos-a-muchos)
// modelBuilder.Entity<Role>()
// .HasMany(r => r.Permissions)
// .WithMany(p => p.Roles)
// .UsingEntity(j => j.ToTable("RolePermissions"));
// // Role -> BaseRole (auto-referencial)
// modelBuilder.Entity<Role>()
// .HasOne(r => r.BaseRoleModel)
// .WithMany() // Un rol base puede ser heredado por múltiples roles
// .HasForeignKey(r => r.BaseRoleModelId);
// base.OnModelCreating(modelBuilder);
// }
//}

View File

@@ -0,0 +1,30 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class RoleRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Role>(entity =>
{
entity.HasOne(d => d.BaseRoleModel).WithMany(p => p.InverseBaseRoleModel).HasForeignKey(d => d.BaseRoleModelId);
entity.HasMany(d => d.Permissions).WithMany(p => p.Roles)
.UsingEntity<Dictionary<string, object>>(
"RolePermission",
r => r.HasOne<Permission>().WithMany()
.HasForeignKey("PermissionId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<Role>().WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("RoleId", "PermissionId");
j.ToTable("RolePermissions");
});
});
}
}

View File

@@ -0,0 +1,40 @@
//using back.DataModels;
//using Microsoft.EntityFrameworkCore;
//namespace back.persistance.data.relations;
//public class SeedingDbContext : DbContext
//{
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// // 3. CONFIGURAR RELACIONES
// modelBuilder.Entity<Role>()
// .HasMany(r => r.Permissions)
// .WithMany(p => p.Roles)
// .UsingEntity<Dictionary<string, object>>(
// "RolePermissions",
// j => j.HasOne<Permission>().WithMany().HasForeignKey("PermissionsId"),
// j => j.HasOne<Role>().WithMany().HasForeignKey("RolesId"),
// j => j.HasData(
// // Usuario: VIEW_CONTENT y LIKE_CONTENT
// new { RolesId = "1", PermissionsId = "1" },
// new { RolesId = "1", PermissionsId = "2" },
// // Content Manager: permisos adicionales
// new { RolesId = "2", PermissionsId = "5" },
// new { RolesId = "2", PermissionsId = "3" },
// new { RolesId = "2", PermissionsId = "4" },
// new { RolesId = "2", PermissionsId = "9" },
// new { RolesId = "2", PermissionsId = "8" },
// // Admin: permisos adicionales
// new { RolesId = "3", PermissionsId = "6" },
// new { RolesId = "3", PermissionsId = "7" },
// new { RolesId = "3", PermissionsId = "10" }
// )
// );
// // Resto de configuraciones...
// base.OnModelCreating(modelBuilder);
// }
//}

View File

@@ -0,0 +1,15 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class TagRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Tag>(entity =>
{
entity.HasIndex(e => e.Name, "IX_Tags_Name").IsUnique();
});
}
}

View File

@@ -0,0 +1,32 @@
using back.DataModels;
using Microsoft.EntityFrameworkCore;
namespace back.persistance.data.relations;
public class UserRelationEstablisher : IRelationEstablisher
{
public void EstablishRelation(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.HasOne(d => d.IdNavigation).WithOne(p => p.User)
.HasForeignKey<User>(d => d.Id)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasMany(d => d.Roles).WithMany(p => p.Users)
.UsingEntity<Dictionary<string, object>>(
"UserRole",
r => r.HasOne<Role>().WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.ClientSetNull),
l => l.HasOne<User>().WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.ClientSetNull),
j =>
{
j.HasKey("UserId", "RoleId");
j.ToTable("UserRoles");
});
});
}
}