Budget fixes! (pre new budget)
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Elias Jansson
2025-05-26 14:20:24 +02:00
parent a9e6628fca
commit 0f0eaad7b1
33 changed files with 2136 additions and 329 deletions

View File

@@ -18,6 +18,7 @@ namespace Aberwyn.Controllers
_context = context;
}
[HttpGet("{year:int}/{month:int}")]
public async Task<IActionResult> GetBudget(int year, int month)
{
@@ -123,6 +124,7 @@ namespace Aberwyn.Controllers
existing.Amount = incoming.Amount;
existing.IsExpense = incoming.IsExpense;
existing.IncludeInSummary = incoming.IncludeInSummary;
existing.Order = incoming.Order;
}
}
}

View File

@@ -31,8 +31,12 @@ namespace Aberwyn.Controllers
[HttpGet]
public IActionResult PizzaOrder()
{
var pizzas = _menuService.GetMealsByCategory("Pizza");
var pizzas = _menuService.GetMealsByCategory("Pizza")
.Where(p => p.IsAvailable)
.ToList();
ViewBag.Pizzas = pizzas;
ViewBag.RestaurantIsOpen = GetRestaurantStatus();
int? lastId = HttpContext.Session.GetInt32("LastPizzaOrderId");
if (lastId.HasValue)
@@ -47,6 +51,7 @@ namespace Aberwyn.Controllers
return View();
}
[HttpGet]
public IActionResult EditPizzaOrder(int id)
{
@@ -138,18 +143,27 @@ namespace Aberwyn.Controllers
.OrderBy(o => o.OrderedAt)
.ToList();
ViewBag.ActiveOrders = allOrders
.Where(o => o.Status != "Finished")
.ToList();
var viewModel = new PizzaAdminViewModel
{
ActiveOrders = allOrders.Where(o => o.Status != "Finished").ToList(),
CompletedOrders = allOrders.Where(o => o.Status == "Finished").ToList()
};
ViewBag.CompletedOrders = allOrders
.Where(o => o.Status == "Finished")
.ToList();
var allMeals = _menuService.GetMeals();
return View();
viewModel.AvailablePizzas = allMeals
.Where(m => m.Category == "Pizza")
.OrderBy(m => m.Name)
.ToList();
ViewBag.RestaurantIsOpen = GetRestaurantStatus();
return View(viewModel);
}
[HttpPost]
[Authorize(Roles = "Chef")]
public IActionResult UpdatePizzaOrder(int id, string status, string ingredientsJson)
@@ -354,6 +368,91 @@ namespace Aberwyn.Controllers
return RedirectToAction("Veckomeny", new { week, year });
}
private bool GetRestaurantStatus()
{
var value = _context.AppSettings.FirstOrDefault(s => s.Key == "RestaurantIsOpen")?.Value;
return bool.TryParse(value, out var isOpen) && isOpen;
}
private void SetRestaurantStatus(bool isOpen)
{
var setting = _context.AppSettings.FirstOrDefault(s => s.Key == "RestaurantIsOpen");
if (setting == null)
{
setting = new AppSetting { Key = "RestaurantIsOpen", Value = isOpen.ToString().ToLower() };
_context.AppSettings.Add(setting);
}
else
{
setting.Value = isOpen.ToString().ToLower();
_context.AppSettings.Update(setting);
}
_context.SaveChanges();
}
[HttpPost]
[Authorize(Roles = "Chef")]
public IActionResult ToggleRestaurant(bool isOpen)
{
var existing = _context.AppSettings.FirstOrDefault(s => s.Key == "RestaurantIsOpen");
if (existing != null)
{
existing.Value = isOpen.ToString();
}
else
{
_context.AppSettings.Add(new AppSetting { Key = "RestaurantIsOpen", Value = isOpen.ToString() });
}
_context.SaveChanges();
return RedirectToAction("PizzaAdmin");
}
[Authorize(Roles = "Chef")]
public IActionResult PizzaAdminPartial()
{
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
var allOrders = _context.PizzaOrders
.Where(o => o.OrderedAt >= today && o.OrderedAt < tomorrow)
.OrderBy(o => o.OrderedAt)
.ToList();
var allMeals = _menuService.GetMealsByCategory("Pizza");
var vm = new PizzaAdminViewModel
{
ActiveOrders = allOrders.Where(o => o.Status != "Finished").ToList(),
CompletedOrders = allOrders.Where(o => o.Status == "Finished").ToList(),
AvailablePizzas = allMeals,
RestaurantIsOpen = GetRestaurantStatus()
};
return PartialView("_PizzaAdminPartial", vm);
}
[HttpPost]
[Authorize(Roles = "Chef")]
public IActionResult UpdatePizzaAvailability(List<int> availableIds)
{
availableIds ??= new List<int>(); // Om null, ersätt med tom lista
var allPizzas = _menuService.GetMealsByCategory("Pizza");
foreach (var meal in allPizzas)
{
var isAvailable = availableIds.Contains(meal.Id);
if (meal.IsAvailable != isAvailable)
{
meal.IsAvailable = isAvailable;
_menuService.SaveOrUpdateMeal(meal);
}
}
return RedirectToAction("PizzaAdmin");
}
}
}

View File

@@ -12,17 +12,21 @@ namespace Aberwyn.Controllers
private readonly ILogger<HomeController> _logger;
//private readonly BudgetService _budgetService;
private readonly MenuService _menuService;
private readonly ApplicationDbContext _context;
// Constructor to inject dependencies
public HomeController(ILogger<HomeController> logger, MenuService menuService)
public HomeController(ApplicationDbContext applicationDbContext, ILogger<HomeController> logger, MenuService menuService)
{
_logger = logger;
_menuService = menuService;
_context = applicationDbContext;
}
public IActionResult Index()
{
var isOpen = _context.AppSettings.FirstOrDefault(x => x.Key == "RestaurantIsOpen")?.Value == "True";
ViewBag.RestaurantIsOpen = isOpen;
return View();
}

View File

@@ -16,6 +16,7 @@ namespace Aberwyn.Data
public DbSet<BudgetItem> BudgetItems { get; set; }
public DbSet<PushSubscriber> PushSubscribers { get; set; }
public DbSet<PizzaOrder> PizzaOrders { get; set; }
public DbSet<AppSetting> AppSettings { get; set; }
}
}

View File

@@ -190,27 +190,31 @@ namespace Aberwyn.Data
using (var connection = GetConnection())
{
connection.Open();
string query = "SELECT Id, Name, ImageUrl, ImageData, ImageMimeType FROM Meals";
string query = @"
SELECT Id, Name, ImageUrl, ImageData, ImageMimeType, Category, IsAvailable
FROM Meals";
using (var cmd = new MySqlCommand(query, connection))
using (var reader = cmd.ExecuteReader())
{
using (var reader = cmd.ExecuteReader())
while (reader.Read())
{
while (reader.Read())
meals.Add(new Meal
{
meals.Add(new Meal
{
Id = reader.GetInt32("Id"),
Name = reader.GetString("Name"),
ImageData = reader.IsDBNull(reader.GetOrdinal("ImageData")) ? null : (byte[])reader["ImageData"],
ImageMimeType = reader.IsDBNull(reader.GetOrdinal("ImageMimeType")) ? null : reader.GetString(reader.GetOrdinal("ImageMimeType")),
ImageUrl = reader.IsDBNull(reader.GetOrdinal("ImageUrl")) ? null : reader.GetString(reader.GetOrdinal("ImageUrl"))
});
}
Id = reader.GetInt32("Id"),
Name = reader.GetString("Name"),
ImageData = reader.IsDBNull(reader.GetOrdinal("ImageData")) ? null : (byte[])reader["ImageData"],
ImageMimeType = reader.IsDBNull(reader.GetOrdinal("ImageMimeType")) ? null : reader.GetString(reader.GetOrdinal("ImageMimeType")),
ImageUrl = reader.IsDBNull(reader.GetOrdinal("ImageUrl")) ? null : reader.GetString(reader.GetOrdinal("ImageUrl")),
Category = reader.IsDBNull(reader.GetOrdinal("Category")) ? null : reader.GetString(reader.GetOrdinal("Category")),
IsAvailable = reader.IsDBNull(reader.GetOrdinal("IsAvailable")) ? true : reader.GetBoolean(reader.GetOrdinal("IsAvailable"))
});
}
}
}
return meals;
}
public List<Meal> GetMealsDetailed()
{
var meals = new List<Meal>();
@@ -304,9 +308,9 @@ namespace Aberwyn.Data
{
cmd.CommandText = @"
INSERT INTO Meals
(Name, Description, ProteinType, CarbType, RecipeUrl, CreatedAt, ImageUrl, ImageData, ImageMimeType, Instructions)
(Name, Description, ProteinType, CarbType, RecipeUrl, CreatedAt, ImageUrl, ImageData, ImageMimeType, Instructions, Category, IsAvailable)
VALUES
(@Name, @Description, @ProteinType, @CarbType, @RecipeUrl, @CreatedAt, @ImageUrl, @ImageData, @ImageMimeType, @Instructions);
(@Name, @Description, @ProteinType, @CarbType, @RecipeUrl, @CreatedAt, @ImageUrl, @ImageData, @ImageMimeType, @Instructions, @Category, @IsAvailable);
SELECT LAST_INSERT_ID();";
}
else
@@ -321,7 +325,9 @@ namespace Aberwyn.Data
ImageUrl = @ImageUrl,
ImageData = @ImageData,
ImageMimeType = @ImageMimeType,
Instructions = @Instructions
Instructions = @Instructions,
Category = @Category,
IsAvailable = @IsAvailable
WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", meal.Id);
}
@@ -336,6 +342,8 @@ namespace Aberwyn.Data
cmd.Parameters.AddWithValue("@ImageData", (object?)meal.ImageData ?? DBNull.Value);
cmd.Parameters.AddWithValue("@ImageMimeType", meal.ImageMimeType ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("@Instructions", meal.Instructions ?? "");
cmd.Parameters.AddWithValue("@Category", meal.Category ?? "");
cmd.Parameters.AddWithValue("@IsAvailable", meal.IsAvailable ? 1 : 0);
if (meal.Id == 0)
{
@@ -348,6 +356,7 @@ namespace Aberwyn.Data
}
}
public void UpdateWeeklyMenu(MenuViewModel menuData)
{
if (menuData == null || menuData.WeeklyMenus == null)
@@ -479,12 +488,12 @@ namespace Aberwyn.Data
connection.Open();
string query = @"
SELECT m.Id, m.Name, m.Category, m.Description, m.ImageUrl, m.ImageData, m.ImageMimeType,
i.Id AS IngredientId, i.Quantity, i.Item
FROM Meals m
LEFT JOIN Ingredients i ON m.Id = i.MealId
WHERE m.Category = @category
ORDER BY m.Name, i.Id";
SELECT m.Id, m.Name, m.Category, m.Description, m.ImageUrl, m.ImageData, m.ImageMimeType, m.IsAvailable,
i.Id AS IngredientId, i.Quantity, i.Item
FROM Meals m
LEFT JOIN Ingredients i ON m.Id = i.MealId
WHERE m.Category = @category
ORDER BY m.Name, i.Id";
using var cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@category", category);
@@ -507,7 +516,9 @@ namespace Aberwyn.Data
ImageUrl = reader.IsDBNull(reader.GetOrdinal("ImageUrl")) ? null : reader.GetString("ImageUrl"),
ImageData = reader.IsDBNull(reader.GetOrdinal("ImageData")) ? null : (byte[])reader["ImageData"],
ImageMimeType = reader.IsDBNull(reader.GetOrdinal("ImageMimeType")) ? null : reader.GetString("ImageMimeType"),
Ingredients = new List<Ingredient>()
Ingredients = new List<Ingredient>(),
IsAvailable = reader.IsDBNull(reader.GetOrdinal("IsAvailable")) ? true : reader.GetBoolean(reader.GetOrdinal("IsAvailable")),
};
}

View File

@@ -0,0 +1,451 @@
// <auto-generated />
using System;
using Aberwyn.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Aberwyn.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20250524173316_AddAppSettings")]
partial class AddAppSettings
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.36")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Aberwyn.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime(6)");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Aberwyn.Models.AppSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("AppSettings");
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BudgetPeriodId")
.HasColumnType("int");
b.Property<string>("Color")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BudgetPeriodId");
b.ToTable("BudgetCategories");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65,30)");
b.Property<int>("BudgetCategoryId")
.HasColumnType("int");
b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsExpense")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BudgetCategoryId");
b.ToTable("BudgetItems");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("Month")
.HasColumnType("int");
b.Property<int>("Order")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("BudgetPeriods");
});
modelBuilder.Entity("Aberwyn.Models.PizzaOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CustomerName")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("IngredientsJson")
.HasColumnType("longtext");
b.Property<DateTime>("OrderedAt")
.HasColumnType("datetime(6)");
b.Property<string>("PizzaName")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("PizzaOrders");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Auth")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Endpoint")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("P256DH")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("PushSubscribers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("RoleId")
.HasColumnType("varchar(255)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.HasOne("Aberwyn.Models.BudgetPeriod", "BudgetPeriod")
.WithMany("Categories")
.HasForeignKey("BudgetPeriodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BudgetPeriod");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{
b.HasOne("Aberwyn.Models.BudgetCategory", "BudgetCategory")
.WithMany("Items")
.HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BudgetCategory");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Navigation("Categories");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddAppSettings : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AppSettings",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Key = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Value = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_AppSettings", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AppSettings");
}
}
}

View File

@@ -0,0 +1,516 @@
// <auto-generated />
using System;
using Aberwyn.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Aberwyn.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20250526121643_AddBudgetDefinitions")]
partial class AddBudgetDefinitions
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.36")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Aberwyn.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime(6)");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Aberwyn.Models.AppSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("AppSettings");
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BudgetCategoryDefinitionId")
.HasColumnType("int");
b.Property<int>("BudgetPeriodId")
.HasColumnType("int");
b.Property<string>("Color")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BudgetCategoryDefinitionId");
b.HasIndex("BudgetPeriodId");
b.ToTable("BudgetCategories");
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategoryDefinition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("BudgetCategoryDefinition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65,30)");
b.Property<int>("BudgetCategoryId")
.HasColumnType("int");
b.Property<int?>("BudgetItemDefinitionId")
.HasColumnType("int");
b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsExpense")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("Order")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BudgetCategoryId");
b.HasIndex("BudgetItemDefinitionId");
b.ToTable("BudgetItems");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItemDefinition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("DefaultCategory")
.HasColumnType("longtext");
b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsExpense")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("BudgetItemDefinition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("Month")
.HasColumnType("int");
b.Property<int>("Order")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("BudgetPeriods");
});
modelBuilder.Entity("Aberwyn.Models.PizzaOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CustomerName")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("IngredientsJson")
.HasColumnType("longtext");
b.Property<DateTime>("OrderedAt")
.HasColumnType("datetime(6)");
b.Property<string>("PizzaName")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("PizzaOrders");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Auth")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Endpoint")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("P256DH")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("PushSubscribers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("RoleId")
.HasColumnType("varchar(255)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.HasOne("Aberwyn.Models.BudgetCategoryDefinition", "Definition")
.WithMany()
.HasForeignKey("BudgetCategoryDefinitionId");
b.HasOne("Aberwyn.Models.BudgetPeriod", "BudgetPeriod")
.WithMany("Categories")
.HasForeignKey("BudgetPeriodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("BudgetPeriod");
b.Navigation("Definition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{
b.HasOne("Aberwyn.Models.BudgetCategory", "BudgetCategory")
.WithMany("Items")
.HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.BudgetItemDefinition", "Definition")
.WithMany()
.HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetCategory");
b.Navigation("Definition");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Navigation("Categories");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,118 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddBudgetDefinitions : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "BudgetItemDefinitionId",
table: "BudgetItems",
type: "int",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "BudgetCategoryDefinitionId",
table: "BudgetCategories",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "BudgetCategoryDefinition",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Color = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_BudgetCategoryDefinition", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "BudgetItemDefinition",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
DefaultCategory = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
IsExpense = table.Column<bool>(type: "tinyint(1)", nullable: false),
IncludeInSummary = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BudgetItemDefinition", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_BudgetItems_BudgetItemDefinitionId",
table: "BudgetItems",
column: "BudgetItemDefinitionId");
migrationBuilder.CreateIndex(
name: "IX_BudgetCategories_BudgetCategoryDefinitionId",
table: "BudgetCategories",
column: "BudgetCategoryDefinitionId");
migrationBuilder.AddForeignKey(
name: "FK_BudgetCategories_BudgetCategoryDefinition_BudgetCategoryDefi~",
table: "BudgetCategories",
column: "BudgetCategoryDefinitionId",
principalTable: "BudgetCategoryDefinition",
principalColumn: "Id");
migrationBuilder.AddForeignKey(
name: "FK_BudgetItems_BudgetItemDefinition_BudgetItemDefinitionId",
table: "BudgetItems",
column: "BudgetItemDefinitionId",
principalTable: "BudgetItemDefinition",
principalColumn: "Id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_BudgetCategories_BudgetCategoryDefinition_BudgetCategoryDefi~",
table: "BudgetCategories");
migrationBuilder.DropForeignKey(
name: "FK_BudgetItems_BudgetItemDefinition_BudgetItemDefinitionId",
table: "BudgetItems");
migrationBuilder.DropTable(
name: "BudgetCategoryDefinition");
migrationBuilder.DropTable(
name: "BudgetItemDefinition");
migrationBuilder.DropIndex(
name: "IX_BudgetItems_BudgetItemDefinitionId",
table: "BudgetItems");
migrationBuilder.DropIndex(
name: "IX_BudgetCategories_BudgetCategoryDefinitionId",
table: "BudgetCategories");
migrationBuilder.DropColumn(
name: "BudgetItemDefinitionId",
table: "BudgetItems");
migrationBuilder.DropColumn(
name: "BudgetCategoryDefinitionId",
table: "BudgetCategories");
}
}
}

View File

@@ -83,12 +83,34 @@ namespace Aberwyn.Migrations
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Aberwyn.Models.AppSetting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("AppSettings");
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BudgetCategoryDefinitionId")
.HasColumnType("int");
b.Property<int>("BudgetPeriodId")
.HasColumnType("int");
@@ -105,11 +127,32 @@ namespace Aberwyn.Migrations
b.HasKey("Id");
b.HasIndex("BudgetCategoryDefinitionId");
b.HasIndex("BudgetPeriodId");
b.ToTable("BudgetCategories");
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategoryDefinition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("BudgetCategoryDefinition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{
b.Property<int>("Id")
@@ -122,6 +165,9 @@ namespace Aberwyn.Migrations
b.Property<int>("BudgetCategoryId")
.HasColumnType("int");
b.Property<int?>("BudgetItemDefinitionId")
.HasColumnType("int");
b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)");
@@ -139,9 +185,35 @@ namespace Aberwyn.Migrations
b.HasIndex("BudgetCategoryId");
b.HasIndex("BudgetItemDefinitionId");
b.ToTable("BudgetItems");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItemDefinition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("DefaultCategory")
.HasColumnType("longtext");
b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsExpense")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("BudgetItemDefinition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Property<int>("Id")
@@ -344,6 +416,10 @@ namespace Aberwyn.Migrations
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.HasOne("Aberwyn.Models.BudgetCategoryDefinition", "Definition")
.WithMany()
.HasForeignKey("BudgetCategoryDefinitionId");
b.HasOne("Aberwyn.Models.BudgetPeriod", "BudgetPeriod")
.WithMany("Categories")
.HasForeignKey("BudgetPeriodId")
@@ -351,6 +427,8 @@ namespace Aberwyn.Migrations
.IsRequired();
b.Navigation("BudgetPeriod");
b.Navigation("Definition");
});
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
@@ -361,7 +439,13 @@ namespace Aberwyn.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.BudgetItemDefinition", "Definition")
.WithMany()
.HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetCategory");
b.Navigation("Definition");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>

View File

@@ -0,0 +1,10 @@
namespace Aberwyn.Models
{
public class AppSetting
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
}

View File

@@ -20,7 +20,8 @@ namespace Aberwyn.Models
public string Color { get; set; } // t.ex. "red", "green", "yellow"
public int BudgetPeriodId { get; set; }
public int Order { get; set; }
public int? BudgetCategoryDefinitionId { get; set; }
public BudgetCategoryDefinition? Definition { get; set; }
[JsonIgnore]
[ValidateNever]
public BudgetPeriod BudgetPeriod { get; set; }
@@ -36,6 +37,11 @@ namespace Aberwyn.Models
public bool IsExpense { get; set; } // true = utgift, false = inkomst/spar
public bool IncludeInSummary { get; set; } = true;
public int Order { get; set; } //
public int? BudgetItemDefinitionId { get; set; }
[JsonIgnore]
[ValidateNever]
public BudgetItemDefinition? Definition { get; set; }
public int BudgetCategoryId { get; set; }
@@ -82,4 +88,20 @@ namespace Aberwyn.Models
{
public List<BudgetItem> BudgetItems { get; set; } = new List<BudgetItem>();
}
public class BudgetItemDefinition
{
public int Id { get; set; }
public string Name { get; set; } // t.ex. "Däck", "Elräkning", "Drivmedel"
public string? DefaultCategory { get; set; } // valfritt, kan föreslå "Bilar"
public bool IsExpense { get; set; }
public bool IncludeInSummary { get; set; }
}
public class BudgetCategoryDefinition
{
public int Id { get; set; }
public string Name { get; set; } // t.ex. "Bilar", "Räkningar", "Semester"
public string Color { get; set; } // standardfärg, kan modifieras per period
}
}

View File

@@ -44,6 +44,7 @@ namespace Aberwyn.Models
public string CarbType { get; set; }
public string RecipeUrl { get; set; }
public string ImageUrl { get; set; }
public bool IsAvailable { get; set; }
public DateTime CreatedAt { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; } // t.ex. "image/jpeg"
@@ -63,7 +64,7 @@ namespace Aberwyn.Models
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public bool IsAvailable { get; set; }
public string? ImageUrl { get; set; }
public string? ImageData { get; set; } // base64
public string? ImageMimeType { get; set; }
@@ -75,6 +76,7 @@ namespace Aberwyn.Models
Id = meal.Id,
Name = meal.Name,
Category = meal.Category,
IsAvailable = meal.IsAvailable,
ImageUrl = meal.ImageUrl,
ImageMimeType = meal.ImageMimeType,
ImageData = meal.ImageData != null ? Convert.ToBase64String(meal.ImageData) : null

View File

@@ -18,5 +18,13 @@ namespace Aberwyn.Models
public DateTime OrderedAt { get; set; } = DateTime.Now;
}
public class PizzaAdminViewModel
{
public List<PizzaOrder> ActiveOrders { get; set; }
public List<PizzaOrder> CompletedOrders { get; set; }
public List<Meal> AvailablePizzas { get; set; }
public bool RestaurantIsOpen { get; set; }
}
}

View File

@@ -66,23 +66,23 @@
</button>
</div>
</div>
<div class="item-list">
<div ng-repeat="item in cat.items track by item.id">
<div drop-placeholder
category="cat"
index="$index"
on-drop-item="handleItemPreciseDrop(data, cat, $index)">
</div>
<div drop-placeholder
category="cat"
index="$index"
on-drop-item="handleItemPreciseDrop(data, cat, $index)">
</div>
<div class="item-row"
draggable-item
item="item"
category="cat"
on-item-drop="handleItemDrop(event, data, cat)"
ng-class="{ dragging: dragInProgress && draggedItemId === item.id }">
<i class="fa fa-grip-lines" ng-show="cat.editing" style="opacity: 0.5; padding-right: 6px;"></i>
<i class="fa fa-grip-lines drag-handle"
ng-show="cat.editing"
style="opacity: 0.5; padding-right: 6px; cursor: grab;"></i>
<input type="text" ng-model="item.name" ng-if="cat.editing" />
<span ng-if="!cat.editing">{{ item.name }}</span>
@@ -90,9 +90,31 @@
<input type="number" ng-model="item.amount" ng-if="cat.editing" />
<span class="amount" ng-if="!cat.editing">{{ item.amount | number:0 }}</span>
<button class="icon-button danger" ng-if="cat.editing" ng-click="deleteItem(cat, item)">
<i class="fa fa-trash"></i>
</button>
<!-- 3-pricksmeny -->
<div class="item-menu-container" ng-if="cat.editing" style="position: relative;">
<button class="icon-button" ng-click="openItemMenu($event, item)">
<i class="fa fa-ellipsis-v"></i>
</button>
<div class="item-floating-menu" ng-show="menuVisible" ng-style="menuStyle">
<button ng-click="deleteItem(menuItem.category, menuItem)">🗑 Ta bort</button>
<hr>
<button
ng-click="setItemType(menuItem, 'expense')"
ng-class="{ 'disabled': menuItem.isExpense }">
<span ng-if="menuItem.isExpense">✔️</span> 💸 Utgift
</button>
<button
ng-click="setItemType(menuItem, 'income')"
ng-class="{ 'disabled': !menuItem.isExpense && menuItem.includeInSummary }">
<span ng-if="!menuItem.isExpense && menuItem.includeInSummary">✔️</span> 💰 Inkomst
</button>
<button
ng-click="setItemType(menuItem, 'saving')"
ng-class="{ 'disabled': !menuItem.isExpense && !menuItem.includeInSummary }">
<span ng-if="!menuItem.isExpense && !menuItem.includeInSummary">✔️</span> 🏦 Sparande
</button>
</div>
</div>
</div>
</div>
@@ -106,16 +128,14 @@
<i class="fa fa-plus" style="padding-right: 6px; opacity: 0.7;"></i>
<input type="text" ng-model="cat.newItemName" placeholder="Ny post" />
<input type="number" ng-model="cat.newItemAmount" placeholder="Belopp" />
<button class="icon-button" ng-click="addItem(cat)"><i class="fa fa-plus"></i></button>
</div>
<div class="item-row total-row">
<div>Summa</div>
<div class="amount">{{ getCategorySum(cat) | number:0 }}</div>
</div>
</div>
</div>
<div class="item-row total-row">
<div>Summa</div>
<div class="amount">{{ getCategorySum(cat) | number:0 }}</div>
</div>
<div class="no-data" ng-if="!loading && budget && budget.categories.length === 0">
Det finns ingen budgetdata för vald månad ({{ selectedMonth }}/{{ selectedYear }}).
<button ng-click="copyPreviousMonthSafe()">[Test] Kopiera föregående</button>
@@ -125,6 +145,6 @@
<link rel="stylesheet" href="~/css/budget.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
<script src="~/js/budget.js"></script>
<script src="~/js/budget-dragdrop.js"></script>

View File

@@ -1,147 +1,72 @@
@using Newtonsoft.Json
@using Newtonsoft.Json.Serialization
@model PizzaAdminViewModel
@{
ViewData["Title"] = "Pizza Admin";
var activeOrders = ViewBag.ActiveOrders as List<PizzaOrder> ?? new List<PizzaOrder>();
var completedOrders = ViewBag.CompletedOrders as List<PizzaOrder> ?? new List<PizzaOrder>();
var availablePizzas = Model.AvailablePizzas as List<Meal> ?? new List<Meal>();
var restaurantOpen = ViewBag.RestaurantOpen as bool? ?? true;
}
<style>
.card {
border-radius: 12px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
transition: transform 0.2s ease-in-out;
background-color: #f8f9fa;
flex: 1 1 260px;
min-width: 240px;
max-width: 280px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0;
overflow: hidden;
}
<link rel="stylesheet" href="~/css/pizza-admin.css" />
.card-header {
font-weight: bold;
padding: 10px 12px;
color: white;
}
<div class="admin-grid">
<!-- Vänster: Beställningar (allt i partial) -->
<div class="main-orders">
@await Html.PartialAsync("_PizzaAdminPartial", Model)
</div>
.card-body {
padding: 12px;
flex-grow: 1;
background-color: #ffffff;
}
<!-- Höger: Restaurangstatus + Tillgängliga pizzor -->
<div class="available-pizzas">
<h2>Restaurangstatus</h2>
<form id="restaurantStatusForm">
<label class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="isOpenSwitch" name="isOpen" @(restaurantOpen ? "checked" : "") />
<span class="ms-2" id="statusLabel">@(restaurantOpen ? "Restaurangen är öppen" : "Restaurangen är stängd")</span>
</label>
</form>
.border-info .card-header {
background-color: #0dcaf0;
}
.border-warning .card-header {
background-color: #ffc107;
color: #333;
}
.border-success .card-header {
background-color: #28a745;
}
.card .btn {
font-weight: 600;
flex: 1 1 auto;
}
.card ul {
margin-bottom: 0;
padding-left: 1.2rem;
}
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 16px;
justify-content: flex-start;
}
@@media only screen and (max-width: 600px) {
.card {
width: 100% !important;
}
}
</style>
<h2 class="mt-4">Aktiva beställningar</h2>
<div class="card-grid">
@foreach (var order in activeOrders)
{
var ingredients = new List<string>();
try
{
if (!string.IsNullOrEmpty(order.IngredientsJson))
{
ingredients = System.Text.Json.JsonSerializer.Deserialize<List<string>>(order.IngredientsJson);
}
}
catch
{
ingredients = order.IngredientsJson.Split('\n').ToList();
}
var cardClass = order.Status switch
{
"Confirmed" => "border-warning",
"Ready" => "border-success",
_ => "border-info"
};
<div class="card @cardClass">
<div class="card-header">@order.CustomerName</div>
<div class="card-body">
<div class="fw-bold mb-1">@order.PizzaName</div>
<ul class="mb-2">
@foreach (var ing in ingredients)
<h3 class="mt-4">Tillgängliga pizzor</h3>
<form method="post" asp-action="UpdatePizzaAvailability">
<ul class="list-group mb-4">
@foreach (var pizza in Model.AvailablePizzas)
{
<li>@ing</li>
<li class="list-group-item d-flex justify-content-between align-items-center">
@pizza.Name
<label class="form-check form-switch m-0">
<input class="form-check-input" type="checkbox" name="availableIds" value="@pizza.Id" @(pizza.IsAvailable ? "checked" : "") />
</label>
</li>
}
</ul>
<form id="form-@order.Id" method="post" asp-action="UpdatePizzaOrder">
<input type="hidden" name="id" value="@order.Id" />
<input type="hidden" name="ingredientsJson" value='@System.Text.Json.JsonSerializer.Serialize(ingredients)' />
<div class="d-flex gap-2">
@if (order.Status == "Unconfirmed")
{
<input type="hidden" name="status" value="Confirmed" />
<button type="submit" class="btn btn-sm btn-outline-primary">Confirm</button>
}
else if (order.Status == "Confirmed")
{
<input type="hidden" name="status" value="Finished" />
<button type="submit" class="btn btn-sm btn-outline-success">✔ Mark as Finished</button>
}
<button type="submit" formaction="@Url.Action("UpdatePizzaOrder", new { status = "Neka", id = order.Id })" class="btn btn-sm btn-outline-danger">Neka</button>
</div>
</form>
</div>
<button type="submit" class="btn btn-outline-primary">Spara tillgänglighet</button>
</form>
</div>
}
</div>
<h2 class="mt-5">Färdiga pizzor</h2>
@if (completedOrders.Any())
{
<ul class="list-group">
@foreach (var order in completedOrders)
{
<li class="list-group-item">
@order.CustomerName @order.PizzaName
</li>
}
</ul>
}
else
{
<div class="text-muted">Inga pizzor är klara ännu.</div>
@section Scripts {
<script>
const switchInput = document.getElementById("isOpenSwitch");
const label = document.getElementById("statusLabel");
switchInput.addEventListener("change", function () {
const isOpen = this.checked;
fetch("/FoodMenu/ToggleRestaurant", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `isOpen=${isOpen}`
}).then(() => {
label.textContent = isOpen ? "Restaurangen är öppen" : "Restaurangen är stängd";
});
});
setInterval(() => {
fetch("/FoodMenu/PizzaAdminPartial")
.then(r => r.text())
.then(html => {
const dom = new DOMParser().parseFromString(html, 'text/html');
const newContent = dom.getElementById("ordersContainer").innerHTML;
document.getElementById("ordersContainer").innerHTML = newContent;
});
}, 8000);
</script>
}

View File

@@ -15,6 +15,14 @@ var showForm = previousOrder == null || (forceShow && !justOrdered);
<link rel="stylesheet" href="~/css/pizza.css" />
<div class="pizza-container">
@if (!(ViewBag.RestaurantIsOpen as bool? ?? true))
{
<div class="alert alert-warning text-center mt-5">
🛑 <strong>Restaurangen är stängd just nu.</strong><br />
Kom tillbaka senare för att lägga din beställning.
</div>
return;
}
@if (TempData["Success"] != null)
{

View File

@@ -0,0 +1,79 @@
@using Aberwyn.Models
@using Newtonsoft.Json
@model PizzaAdminViewModel
<div id="ordersContainer">
<div class="card-grid">
@foreach (var order in Model.ActiveOrders)
{
var ingredients = new List<string>();
try
{
if (!string.IsNullOrEmpty(order.IngredientsJson))
{
ingredients = System.Text.Json.JsonSerializer.Deserialize<List<string>>(order.IngredientsJson);
}
}
catch
{
ingredients = order.IngredientsJson?.Split('\n').ToList() ?? new List<string>();
}
var cardClass = order.Status switch
{
"Confirmed" => "border-warning",
"Finished" => "border-success",
_ => "border-info"
};
<div class="card @cardClass">
<div class="card-header">@order.CustomerName @order.PizzaName</div>
<div class="card-body">
<ul class="mb-2">
@foreach (var ing in ingredients)
{
<li>@ing</li>
}
</ul>
<form id="form-@order.Id" method="post" asp-action="UpdatePizzaOrder">
<input type="hidden" name="id" value="@order.Id" />
<input type="hidden" name="ingredientsJson" value='@System.Text.Json.JsonSerializer.Serialize(ingredients)' />
<div class="d-flex gap-2">
@if (order.Status == "Unconfirmed")
{
<input type="hidden" name="status" value="Confirmed" />
<button type="submit" class="btn btn-sm btn-outline-primary">Bekräfta</button>
}
else if (order.Status == "Confirmed")
{
<input type="hidden" name="status" value="Finished" />
<button type="submit" class="btn btn-sm btn-outline-success">✔ Klar</button>
}
<button type="submit" formaction="@Url.Action("UpdatePizzaOrder", new { status = "Neka", id = order.Id })" class="btn btn-sm btn-outline-danger">Neka</button>
</div>
</form>
</div>
</div>
}
</div>
<h3 class="mt-4">Klara beställningar</h3>
<div class="completed-orders-grid">
@foreach (var order in Model.CompletedOrders)
{
var tooltip = string.Join(", ", JsonConvert.DeserializeObject<List<string>>(order.IngredientsJson ?? "[]"));
<div class="completed-order-box" title="@tooltip">
<form class="restore-form" method="post" asp-action="UpdatePizzaOrder">
<input type="hidden" name="id" value="@order.Id" />
<input type="hidden" name="status" value="Confirmed" />
<input type="hidden" name="ingredientsJson" value='@order.IngredientsJson' />
<button type="submit" class="btn btn-sm btn-outline-warning">↩️</button>
</form>
<strong>@order.CustomerName</strong>
<span>@order.PizzaName</span>
</div>
}
</div>
</div>

View File

@@ -10,7 +10,7 @@
<link rel="stylesheet" href="~/css/menu.css" />
</head>
<body ng-controller="MealMenuController" ng-init="viewMode='list'">
<body ng-controller="MealMenuController">
<div class="meal-menu-page">
<div class="menu-header">
<h1>Veckomeny</h1>

View File

@@ -33,11 +33,18 @@
<li><a asp-controller="Budget" asp-action="Index"><i class="fas fa-wallet"></i> Budget</a></li>
}
<li><a asp-controller="Home" asp-action="Menu"><i class="fas fa-utensils"></i> Veckomeny</a></li>
@if (ViewBag.RestaurantIsOpen as bool? == true)
{
<li><a asp-controller="FoodMenu" asp-action="PizzaOrder"><i class="fas fa-pizza-slice"></i> Beställ pizza</a></li>
}
@if (User.IsInRole("Admin") || User.IsInRole("Chef"))
{
<li><a asp-controller="FoodMenu" asp-action="Veckomeny"><i class="fas fa-calendar-week"></i> Administrera Veckomeny</a></li>
<li><a asp-controller="FoodMenu" asp-action="MealAdmin"><i class="fas fa-list"></i> Måltider</a></li>
<li><a asp-controller="FoodMenu" asp-action="PizzaAdmin"><i class="fas fa-list"></i> Pizza Admin</a></li>
}
@if (User.IsInRole("Admin"))
{
<li><a asp-controller="Admin" asp-action="Index"><i class="fas fa-cog"></i> Adminpanel</a></li>

View File

@@ -37,7 +37,6 @@ else
Logga in
</button>
</form>
<a href="/Identity/Account/Register" style="padding: 8px 12px; display: block;">Registrera dig</a>
</div>
</div>
</div>

View File

@@ -125,28 +125,52 @@ body {
.budget-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 12px;
margin-bottom: 24px;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap:10px;
align-items: stretch;
}
.budget-card {
display: flex;
flex-direction: column;
width: 100%;
height: 350px;
position: relative;
overflow-x: hidden;
overflow-y: visible;
border: 1px solid var(--border-color);
border-radius: 12px;
background-color: var(--bg-card);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
overflow: hidden;
}
.item-list {
flex: 1 1 auto;
flex-grow: 1;
overflow-y: auto;
padding: 8px 12px;
background: rgba(255, 0, 0, 0.05); /* tillfällig bakgrund för felsökning */
padding: 2px 8px;
display: flex;
flex-direction: column;
}
.item-row:last-child {
margin-bottom: 5px;
}
.card-header {
border-radius: 12px 12px 0 0;
}
.total-row {
padding: 2px 8px;
font-weight: bold;
font-size: 13px;
background: #f1f5f9;
border-top: 1px solid var(--border-color);
border-radius: 0 0 12px 12px;
flex-shrink: 0;
}
.card-header {
position: sticky;
@@ -188,22 +212,51 @@ body {
flex-wrap: nowrap;
justify-content: space-between;
align-items: center;
gap: 8px;
gap: 0px;
font-size: 13px;
}
.item-list::-webkit-scrollbar {
width: 6px;
}
.item-row input[type="text"],
.item-row input[type="number"] {
flex: 1;
padding: 5px 6px;
font-size: 13px;
border: 1px solid var(--border-color);
border-radius: 6px;
background-color: #ffffff;
color: var(--text-main);
font-weight: 500;
min-width: 120px;
}
.item-list::-webkit-scrollbar-thumb {
background-color: rgba(100, 116, 139, 0.2);
border-radius: 3px;
}
.item-list::-webkit-scrollbar-track {
background: transparent;
}
/* === För Firefox === */
.item-list {
scrollbar-width: thin;
scrollbar-color: rgba(100, 116, 139, 0.2) transparent;
}
.item-row input[type="text"] {
flex: 1;
padding: 5px 6px;
font-size: 13px;
border: 1px solid var(--border-color);
border-radius: 6px;
background-color: #ffffff;
color: var(--text-main);
font-weight: 500;
min-width: 70px;
}
.item-row input[type="number"] {
flex: 1;
padding: 5px 6px;
font-size: 13px;
border: 1px solid var(--border-color);
border-radius: 6px;
background-color: #ffffff;
color: var(--text-main);
font-weight: 500;
max-width: 60px;
}
.amount {
min-width: 70px;
@@ -211,17 +264,6 @@ body {
font-weight: 600;
}
.total-row {
position: sticky;
bottom: 0;
padding: 8px 12px;
font-weight: bold;
font-size: 13px;
background: var(--bg-card);
border-top: 1px solid var(--border-color);
z-index: 1;
}
.icon-button {
@@ -232,26 +274,21 @@ body {
padding: 4px;
transition: color 0.2s;
}
.icon-button:hover {
color: #000000;
}
.icon-button.danger {
.icon-button:hover {
color: #000000;
}
.icon-button.danger {
color: var(--btn-delete);
}
.icon-button.danger:hover {
color: #b91c1c;
}
.icon-button.edit {
color: var(--btn-edit);
}
.icon-button.confirm {
color: var(--btn-check);
}
.icon-button.danger:hover {
color: #b91c1c;
}
.icon-button.edit {
color: var(--btn-edit);
}
.icon-button.confirm {
color: var(--btn-check);
}
.dropdown-menu {
position: absolute;
@@ -284,7 +321,7 @@ body {
font-weight: 500;
}
.dropdown-menu button:hover {
.dropdown-menu button:hover {
background-color: #e5e7eb;
}
@@ -315,38 +352,75 @@ body {
z-index: 9999;
font-weight: 500;
}
.toast.show {
opacity: 1;
transform: translateY(0);
}
.toast.error {
background: #ef4444;
}
.toast.show {
opacity: 1;
transform: translateY(0);
}
.toast.error {
background: #ef4444;
}
/* === Dropzones === */
.drop-placeholder {
height: 12px;
transition: background-color 0.2s ease;
background-color: transparent;
height: 0px;
transition: all 0.2s ease;
margin: 0;
}
.drop-placeholder.drag-over {
border-top: 3px solid #3B82F6; /* blå rand */
background-color: rgba(59, 130, 246, 0.15); /* ljusblå fyllning */
height: 12px;
border-top: 3px solid #3B82F6;
height: 40px; /* gör det mer tydligt när man drar */
transition: height 0.2s ease;
}
/* Gör att man ser var man kan släppa */
.drop-zone.active-drop-target {
background-color: rgba(34, 197, 94, 0.15); /* svagt grön basfärg */
height: 12px;
background-color: rgba(22, 163, 74, 0.1); /* svagt grön basfärg */
}
.drop-zone.drag-over {
border: 2px dashed #16a34a; /* grön */
background-color: rgba(22, 163, 74, 0.1);
}
.item-floating-menu {
position: fixed !important; /* viktig för att den inte ska följa DOM-flödet */
z-index: 9999 !important; /* se till att inget annat ligger över */
background: #1F2C3C;
color: #fff;
border: 1px solid #444;
border-radius: 6px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
padding: 4px 0px 4px 0;
min-width: 20px;
max-width: 130px;
display: block;
}
.item-floating-menu button {
background: none;
border: none;
color: #fff;
text-align: left;
padding: 8px 16px;
width: 100%;
cursor: pointer;
}
.item-floating-menu button:hover {
background: #333;
}
.item-floating-menu button.disabled {
color: #aaa;
pointer-events: none;
font-style: italic;
}

View File

@@ -0,0 +1,181 @@
.admin-grid {
display: flex;
gap: 24px;
align-items: flex-start;
flex-wrap: nowrap;
}
.main-orders {
flex: 3;
display: flex;
flex-direction: column;
gap: 16px;
}
.available-pizzas {
flex: 1;
background-color: #f1f5f9;
padding: 16px;
border-radius: 12px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
min-width: 280px;
}
.card {
border-radius: 10px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
background: #f9fafb; /* Ljus bakgrund generellt */
overflow: hidden;
min-width: 220px;
max-width: 260px;
display: flex;
flex-direction: column;
border: 1px solid #dee2e6;
transition: box-shadow 0.2s ease;
}
.card.border-info {
border-left: 6px solid #0dcaf0;
background-color: #e6f9fd; /* ljusblå ton */
}
.card.border-warning {
border-left: 6px solid #ffc107;
background-color: #fff9e6; /* ljusgul ton */
}
.card.border-success {
border-left: 6px solid #28a745;
background-color: #e6f9ec; /* ljusgrön ton */
}
.card.border-inprogress {
border-left: 6px solid #fd7e14;
background-color: #fff3e6; /* ljusorange ton */
}
.card-header {
font-weight: 700;
font-size: 0.95rem;
background-color: rgba(0, 0, 0, 0.05); /* fallback */
padding: 10px 12px;
color: #1a202c;
display: flex;
flex-direction: column;
gap: 4px;
}
.border-info .card-header {
background-color: #0dcaf0;
color: #fff;
}
.border-warning .card-header {
background-color: #ffc107;
color: #333;
}
.border-success .card-header {
background-color: #28a745;
color: #fff;
}
.border-inprogress .card-header {
background-color: #fd7e14;
color: #fff;
}
.card-header .pizza-name {
font-size: 0.85rem;
font-weight: 500;
opacity: 0.9;
}
.card-body {
padding: 10px 12px;
font-size: 0.85rem;
display: flex;
flex-direction: column;
gap: 10px;
}
.card-body ul {
margin: 0;
padding-left: 1.2rem;
list-style: disc;
}
.card .btn {
font-size: 0.8rem;
padding: 4px 8px;
}
/* Klara beställningar smalare liststil */
#ordersContainer ul.list-group {
margin-top: 12px;
}
#ordersContainer ul.list-group li {
background: #ffffff;
border: 1px solid #ddd;
border-radius: 6px;
margin-bottom: 6px;
padding: 8px 12px;
font-size: 0.9rem;
display: flex;
justify-content: space-between;
align-items: center;
}
#ordersContainer ul.list-group li form {
margin: 0;
}
/* Responsiv */
@media only screen and (max-width: 900px) {
.admin-grid {
flex-direction: column;
}
.available-pizzas {
width: 100%;
}
}
.completed-orders-grid {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 16px;
}
.completed-order-box {
background-color: #e2e8f0;
border-radius: 8px;
padding: 8px 10px;
font-size: 0.85rem;
min-width: 160px;
max-width: 180px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
display: flex;
flex-direction: column;
position: relative;
}
.completed-order-box strong {
font-weight: 600;
display: block;
margin-bottom: 4px;
}
.restore-form {
position: absolute;
top: 6px;
right: 6px;
}
.restore-form button {
padding: 2px 6px;
font-size: 0.75rem;
line-height: 1;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

View File

@@ -9,51 +9,53 @@ app.directive('draggableItem', function () {
onItemDrop: '&'
},
link: function (scope, element) {
const row = element[0];
const handle = row.querySelector('.drag-handle');
function isEditing() {
return scope.category && scope.category.editing;
}
function updateDraggableAttr() {
element[0].setAttribute('draggable', isEditing() ? 'true' : 'false');
element[0].classList.toggle('draggable-enabled', isEditing());
// Gör handtaget till draggable om editing är aktivt
scope.$watch('category.editing', function (editing) {
if (handle) handle.setAttribute('draggable', editing ? 'true' : 'false');
});
if (handle) {
handle.addEventListener('dragstart', function (e) {
if (!isEditing()) {
e.preventDefault();
return;
}
e.dataTransfer.setData('text/plain', JSON.stringify({
type: 'item',
itemId: scope.item.id,
fromCategoryId: scope.category.id
}));
const ghost = row.cloneNode(true);
ghost.style.position = 'absolute';
ghost.style.top = '-9999px';
ghost.style.left = '-9999px';
ghost.style.width = `${row.offsetWidth}px`;
ghost.style.opacity = '0.7';
document.body.appendChild(ghost);
e.dataTransfer.setDragImage(ghost, 0, 0);
setTimeout(() => document.body.removeChild(ghost), 0);
document.querySelectorAll('.drop-zone').forEach(el => el.classList.add('active-drop-target'));
});
handle.addEventListener('dragend', function () {
document.querySelectorAll('.drop-zone').forEach(el => el.classList.remove('active-drop-target'));
});
}
updateDraggableAttr();
scope.$watch('category.editing', updateDraggableAttr);
element[0].addEventListener('dragstart', function (e) {
if (!isEditing()) {
e.preventDefault();
return;
}
e.dataTransfer.setData('text/plain', JSON.stringify({
type: 'item',
fromCategoryId: scope.category.id,
itemId: scope.item.id
}));
const ghost = element[0].cloneNode(true);
ghost.style.position = 'absolute';
ghost.style.top = '-9999px';
ghost.style.left = '-9999px';
ghost.style.width = element[0].offsetWidth + 'px';
ghost.style.opacity = '0.7';
document.body.appendChild(ghost);
e.dataTransfer.setDragImage(ghost, 0, 0);
setTimeout(() => document.body.removeChild(ghost), 0);
document.querySelectorAll('.drop-zone').forEach(el => el.classList.add('active-drop-target'));
});
element[0].addEventListener('dragend', function () {
document.querySelectorAll('.drop-zone').forEach(el => el.classList.remove('active-drop-target'));
});
}
};
});
app.directive('dropPlaceholder', function () {
return {
restrict: 'A',
@@ -85,36 +87,30 @@ app.directive('dropPlaceholder', function () {
e.preventDefault();
element[0].classList.add('drag-over');
label.style.display = 'block';
});
element[0].addEventListener('dragleave', function () {
element[0].classList.remove('drag-over');
label.style.display = 'none';
});
element[0].addEventListener('drop', function (e) {
if (!isEditing()) return;
e.preventDefault();
element[0].classList.remove('drag-over');
label.style.display = 'none';
const dataText = e.dataTransfer.getData('text/plain');
try {
const data = JSON.parse(dataText);
if (data.type !== 'item') return;
const data = JSON.parse(dataText);
if (data.type !== 'item') return;
scope.$apply(() => {
scope.onDropItem({
data: data,
targetCategory: scope.category,
targetIndex: scope.index
});
scope.$apply(() => {
scope.onDropItem({
data: data,
targetCategory: scope.category,
targetIndex: scope.index
});
} catch (err) {
console.error("Error parsing drop data:", err);
}
});
});
}
};
});
@@ -181,22 +177,49 @@ app.directive('draggableCategory', function () {
const header = element[0].querySelector('.card-header');
if (!header) return;
function updateDraggableAttr() {
header.setAttribute('draggable', scope.category.allowDrag ? 'true' : 'false');
function isDragEnabled() {
return scope.category && scope.category.editing && scope.category.allowDrag;
}
scope.$watch('category.allowDrag', updateDraggableAttr);
function updateDraggableAttr() {
header.setAttribute('draggable', isDragEnabled() ? 'true' : 'false');
}
scope.$watchGroup(['category.editing', 'category.allowDrag'], updateDraggableAttr);
updateDraggableAttr();
header.addEventListener('dragstart', function (e) {
if (!scope.category.allowDrag) {
if (!isDragEnabled()) {
e.preventDefault();
return;
}
// Endast tillåt drag från just headern, inte från t.ex. knappar
if (e.target !== header) {
e.preventDefault();
return;
}
e.dataTransfer.setData('text/plain', JSON.stringify({
type: 'category',
categoryId: scope.category.id
}));
const ghost = element[0].cloneNode(true);
ghost.style.position = 'absolute';
ghost.style.top = '-9999px';
ghost.style.left = '-9999px';
ghost.style.width = element[0].offsetWidth + 'px';
ghost.style.opacity = '0.7';
document.body.appendChild(ghost);
e.dataTransfer.setDragImage(ghost, 0, 0);
setTimeout(() => document.body.removeChild(ghost), 0);
document.querySelectorAll('.drop-zone').forEach(el => el.classList.add('active-drop-target'));
});
header.addEventListener('dragend', function () {
document.querySelectorAll('.drop-zone').forEach(el => el.classList.remove('active-drop-target'));
});
element[0].addEventListener('dragover', function (e) {
@@ -206,6 +229,7 @@ app.directive('draggableCategory', function () {
element[0].addEventListener('drop', function (e) {
e.preventDefault();
element[0].classList.remove('drag-over');
const data = JSON.parse(e.dataTransfer.getData('text/plain'));
if (data.type !== 'category') return;

View File

@@ -24,6 +24,50 @@ app.controller('BudgetController', function ($scope, $http) {
e.stopPropagation();
$scope.menuOpen = !$scope.menuOpen;
};
$scope.menuVisible = false;
$scope.menuItem = null;
$scope.menuStyle = {};
$scope.openItemMenu = function ($event, item) {
const rect = $event.currentTarget.getBoundingClientRect();
console.log("Menu position:", rect);
$scope.menuItem = item;
$scope.menuItem.category = $scope.budget.categories.find(c => c.items.includes(item));
$scope.menuStyle = {
top: `${rect.bottom + 4}px`,
left: `${rect.left}px`
};
$scope.menuVisible = true;
};
$scope.setItemType = function (item, type) {
if (type === 'expense') {
item.isExpense = true;
item.includeInSummary = true;
} else if (type === 'income') {
item.isExpense = false;
item.includeInSummary = true;
} else if (type === 'saving') {
item.isExpense = false;
item.includeInSummary = false;
}
$scope.menuVisible = false;
};
// Klick utanför stänger popup
document.addEventListener('click', function (e) {
const menu = document.querySelector('.item-floating-menu');
if (menu && !$scope.menuVisible) return;
const isInside = menu?.contains(e.target);
const isButton = e.target.closest('.icon-button');
if (!isInside && !isButton) {
$scope.$apply(() => $scope.menuVisible = false);
}
});
document.addEventListener('click', function () {
$scope.$apply(() => {
@@ -117,8 +161,6 @@ app.controller('BudgetController', function ($scope, $http) {
});
}
category.editing = false;
const payload = {
id: category.id,
name: category.name,
@@ -135,8 +177,13 @@ app.controller('BudgetController', function ($scope, $http) {
};
$http.put(`/api/budget/category/${category.id}`, payload)
.then(() => $scope.showToast("Kategori sparad!"))
.catch(() => $scope.showToast("Fel vid sparande av kategori", true));
.then(() => {
$scope.showToast("Kategori sparad!");
category.editing = false; // ✅ flytta hit
})
.catch(() => {
$scope.showToast("Fel vid sparande av kategori", true);
});
};
$scope.deleteCategory = function (category) {
@@ -390,6 +437,30 @@ app.controller('BudgetController', function ($scope, $http) {
$scope.showToast("Fel vid omplacering", true);
});
};
$scope.updateItemType = function (item) {
if (item.type === 'income') {
item.isExpense = false;
item.includeInSummary = true;
} else if (item.type === 'expense') {
item.isExpense = true;
item.includeInSummary = true;
} else if (item.type === 'saving') {
item.isExpense = false;
item.includeInSummary = false;
}
};
$scope.setItemType = function (item, type) {
if (type === 'income') {
item.isExpense = false;
item.includeInSummary = true;
} else if (type === 'expense') {
item.isExpense = true;
item.includeInSummary = true;
} else if (type === 'saving') {
item.isExpense = false;
item.includeInSummary = false;
}
};
$scope.createNewCategory = function () {
const defaultName = "Ny kategori";
const newOrder = $scope.budget.categories.length; // sist i listan
@@ -424,6 +495,68 @@ app.controller('BudgetController', function ($scope, $http) {
$scope.showToast("Fel vid skapande av kategori", true);
});
};
$scope.addItem = function (category) {
if (!category.newItemName || !category.newItemAmount) return;
const tempId = `temp-${Date.now()}-${Math.random()}`; // temporärt ID
const newItem = {
id: tempId,
name: category.newItemName,
amount: parseFloat(category.newItemAmount),
isExpense: true,
includeInSummary: true,
budgetCategoryId: category.id
};
category.items.push(newItem);
category.newItemName = "";
category.newItemAmount = "";
};
$scope.deleteItem = function (category, item) {
console.log("Försöker ta bort:", item);
if (!item.id || item.id.toString().startsWith("temp-")) {
// Ta bort direkt om det är ett nytt (osparat) item
category.items = category.items.filter(i => i !== item);
$scope.showToast("Ospard post togs bort");
return;
}
if (!confirm("Vill du ta bort denna post?")) return;
$http.delete(`/api/budget/item/${item.id}`)
.then(() => {
category.items = category.items.filter(i => i.id !== item.id);
$scope.showToast("Post borttagen!");
})
.catch(err => {
console.error("Fel vid borttagning av item:", err);
$scope.showToast("Kunde inte ta bort posten", true);
});
};
$scope.handleItemDrop = function (event, data, targetCategory) {
console.log("Item drop received:", data, "to", targetCategory);
// Hitta källkategorin
const sourceCat = $scope.budget.categories.find(c => c.id === data.fromCategoryId);
if (!sourceCat) return;
const itemIndex = sourceCat.items.findIndex(i => i.id === data.itemId);
if (itemIndex === -1) return;
const [movedItem] = sourceCat.items.splice(itemIndex, 1);
targetCategory.items.push(movedItem);
$scope.$applyAsync();
};
$scope.handleItemPreciseDrop = function (data, targetCategory, targetIndex) {
console.log("Precise drop at index", targetIndex);
const sourceCat = $scope.budget.categories.find(c => c.id === data.fromCategoryId);
if (!sourceCat) return;
const itemIndex = sourceCat.items.findIndex(i => i.id === data.itemId);
if (itemIndex === -1) return;
const [movedItem] = sourceCat.items.splice(itemIndex, 1);
targetCategory.items.splice(targetIndex, 0, movedItem);
$scope.$applyAsync();
};
$scope.loadBudget();

View File

@@ -7,7 +7,8 @@ angular.module('mealMenuApp', ['ngSanitize'])
.controller('MealMenuController', function ($scope, $http, $sce) {
console.log("Controller initierad");
$scope.viewMode = 'list';
const savedView = localStorage.getItem('mealViewMode');
$scope.viewMode = savedView === 'card' || savedView === 'list' ? savedView : 'card';
$scope.tooltip = {};
$scope.meals = [];
$scope.menu = {};
@@ -15,10 +16,6 @@ angular.module('mealMenuApp', ['ngSanitize'])
$scope.selectedWeek = getWeek(today);
$scope.selectedYear = today.getFullYear();
$scope.daysOfWeek = ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"];
const savedViewMode = localStorage.getItem('mealViewMode');
if (savedViewMode === 'list' || savedViewMode === 'card') {
$scope.viewMode = savedViewMode;
}
$scope.loadMeals = function () {
console.log("Hämtar måltider...");
@@ -131,12 +128,11 @@ angular.module('mealMenuApp', ['ngSanitize'])
$scope.viewMode = $scope.viewMode === 'list' ? 'card' : 'list';
localStorage.setItem('mealViewMode', $scope.viewMode); // ← spara läget
setTimeout(() => {
const btn = document.getElementById('toggle-view');
if (btn) {
btn.textContent = $scope.getViewIcon();
}
$timeout(() => {
const viewBtn = document.getElementById('toggle-view');
if (viewBtn) viewBtn.textContent = $scope.getViewIcon();
}, 0);
};
@@ -174,8 +170,5 @@ document.addEventListener("DOMContentLoaded", function () {
}
// Initiera ikon för vy
const scope = angular.element(document.body).scope();
if (viewBtn && scope) {
viewBtn.textContent = scope.viewMode === 'list' ? '🗒️' : '▣';
}
});