Compare commits

..

67 Commits

Author SHA1 Message Date
elias
fb24ffbf03 Merge branch 'master' of http://192.168.1.9:3000/Tai/Aberwyn
All checks were successful
continuous-integration/drone/push Build is passing
2025-08-03 21:52:25 +02:00
elias
274f98baa4 Test 2025-08-03 21:47:02 +02:00
elias
80ffad6d86 Torrent 2025-08-03 21:46:06 +02:00
Elias Jansson
5b0a8386ad Fixed leftover
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-24 11:18:51 +02:00
Elias Jansson
4b8c54d38d Category fix and movie 0.1
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-24 10:59:33 +02:00
Elias Jansson
cc96802637 Budget tests
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-21 15:16:31 +02:00
Elias Jansson
95811ce3f8 More css and button fixes
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-07 15:47:26 +02:00
Elias Jansson
4a7a2c30c9 Meal CSS fix
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-07 15:33:49 +02:00
Elias Jansson
8ebbb803e8 Meal rating and some fixes to meals
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-07 15:22:12 +02:00
elias
380978959b Lab changes
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-07 09:37:56 +02:00
Elias Jansson
072369fa17 Meal lab v0.1
All checks were successful
continuous-integration/drone/push Build is passing
2025-07-03 22:00:56 +02:00
Elias Jansson
45994a9439 Today menu api
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-25 09:19:16 +02:00
Elias Jansson
3ef872ac8c Recipe publishing
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-24 17:20:08 +02:00
Elias Jansson
051ef625ba Changes Kök to Mat
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 12:46:42 +02:00
Elias Jansson
07f6451c5a Drone session persistance fixes
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 12:43:53 +02:00
Elias Jansson
979b05f2ca Test 6
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 12:32:24 +02:00
Elias Jansson
aefc653e22 Test 5
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:28:01 +02:00
Elias Jansson
4f14918b02 Test 4
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:26:31 +02:00
Elias Jansson
f8a33123d0 Test 3
Some checks failed
continuous-integration/drone/push Build encountered an error
2025-06-19 12:25:12 +02:00
Elias Jansson
95bb989e07 Test 2
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:23:45 +02:00
Elias Jansson
004ac0c696 Test
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:21:42 +02:00
Elias Jansson
f0642e4587 More optimization
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:20:51 +02:00
Elias Jansson
2504fab3e7 Drone optimization
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 12:18:56 +02:00
Elias Jansson
a4229594bf Another drone optimization
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 12:16:58 +02:00
Elias Jansson
55a254457b drone multiline removal
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 11:10:58 +02:00
Elias Jansson
67670cc380 Drone
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 11:09:27 +02:00
Elias Jansson
e26a809122 docker login 192.168.1.9:3000 -u ${GITEA_USERNAME} -p ${GITEA_TOKEN}
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 11:07:46 +02:00
Elias Jansson
b1f20de393 Drone test
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-19 11:01:45 +02:00
Elias Jansson
c84699fd16 Drone test
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 10:55:11 +02:00
Elias Jansson
46299cb7f2 Drone fix
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-19 09:33:55 +02:00
Elias Jansson
9f40b3f8a0 Optimizing drone compiling
Some checks failed
continuous-integration/drone/push Build encountered an error
2025-06-19 09:32:38 +02:00
Elias Jansson
6cb2ebf3c8 Mobile fix for paymentstatus
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-18 23:35:22 +02:00
Elias Jansson
871fe3a070 Budget paymentdue
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-18 23:26:41 +02:00
Elias Jansson
22ae26d488 Notifications
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-15 22:32:13 +02:00
Elias Jansson
b785051a89 Notifications
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-15 22:15:31 +02:00
elias
0e58ffb735 Pizza fixes and removed school menu since summer
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-15 20:48:05 +02:00
elias
76656bb6a8 Lots of fixes
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-15 10:49:04 +02:00
Elias Jansson
113cce73ad New manifest with correct color
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-13 15:50:50 +02:00
Elias Jansson
fb62f076a0 Mostly css changes and welcome page thumbnails
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-13 15:46:57 +02:00
Elias Jansson
6a43435950 Layout fixad
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-13 10:41:00 +02:00
Elias Jansson
f71be26ae4 Layout fix
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-12 13:23:58 +02:00
Elias Jansson
d1e4901eee Layout ändringar och meal fixar
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-12 13:00:52 +02:00
Elias Jansson
fc78ec0813 Meal fix
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-11 13:51:45 +02:00
Tai
57bea7b54c Meal updates
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-11 13:06:08 +02:00
Elias Jansson
465f9afc99 Bunch of fixes and session extensions
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-10 18:59:04 +02:00
Elias Jansson
e3eb2dc7cb Budget page improvements
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-09 16:11:59 +02:00
elias
256ce76af1 Pizza notice
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-06 12:57:49 +02:00
elias
b286fed88a Ny meals!
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-05 23:23:36 +02:00
elias
bc77e39c72 Optimized menu
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-05 20:15:11 +02:00
elias
eba00ffbf2 Todo fixes
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-05 00:20:17 +02:00
Elias Jansson
c44fbfdca9 Woohoo working version gooo
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-04 18:01:05 +02:00
Elias Jansson
84c6c45a0b Another attempt
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-04 11:51:08 +02:00
Elias Jansson
83a71a6f1d Setup.json password usage
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-04 09:42:03 +02:00
Elias Jansson
fcd27943bf Drone fix
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-04 09:08:36 +02:00
Elias Jansson
acbb72de3f DRONE
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-03 23:12:15 +02:00
Elias Jansson
c4efcc249b Drone
Some checks failed
continuous-integration/drone/push Build encountered an error
2025-06-03 23:05:53 +02:00
Elias Jansson
4da4a34443 Passwordfix
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 22:47:17 +02:00
Elias Jansson
77d3c741b1 Stringbuilder to handle passwords
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 22:35:37 +02:00
Elias Jansson
e626daa7bc Gogogo
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 22:11:17 +02:00
Elias Jansson
fe8e54b868 Git
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 21:57:44 +02:00
Elias Jansson
908bc469c6 Setup!
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 21:36:16 +02:00
Elias Jansson
3d6aa2d424 Use old db
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 00:26:13 +02:00
Elias Jansson
fd6759e3d0 Gogogo
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 00:19:40 +02:00
Elias Jansson
4c60508d6d Fixes!
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-03 00:04:28 +02:00
Elias Jansson
628f25a8be More
All checks were successful
continuous-integration/drone/push Build is passing
2025-06-02 23:52:17 +02:00
Elias Jansson
2e1e0f4670 Clearing up proj file
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-02 23:48:43 +02:00
Elias Jansson
a33ed400f1 Dockerfile fix
Some checks failed
continuous-integration/drone/push Build is failing
2025-06-02 23:40:47 +02:00
109 changed files with 16490 additions and 1313 deletions

View File

@@ -2,30 +2,27 @@ kind: pipeline
type: docker type: docker
name: default name: default
steps: volumes:
- name: build-dotnet - name: dockersock
image: mcr.microsoft.com/dotnet/sdk:6.0 host:
environment: path: /var/run/docker.sock
LANG: en_US.UTF-8
LC_ALL: en_US.UTF-8
DOTNET_CLI_UI_LANGUAGE: en-US
commands:
- dotnet publish Aberwyn/Aberwyn.csproj -c Release -o out
- name: build-docker steps:
image: plugins/docker - name: docker-build
settings: image: docker:24
registry: 192.168.1.9:3000 volumes:
repo: 192.168.1.9:3000/tai/aberwyn/aberwyn - name: dockersock
username: path: /var/run/docker.sock
environment:
GITEA_USERNAME:
from_secret: gitea_username from_secret: gitea_username
password: GITEA_TOKEN:
from_secret: gitea_token from_secret: gitea_token
dockerfile: Aberwyn/Dockerfile commands:
context: . - export DOCKER_BUILDKIT=1
tags: - docker buildx create --use --driver docker-container || true
- latest - echo "$GITEA_TOKEN" | docker login 192.168.1.9:3000 -u "$GITEA_USERNAME" --password-stdin
insecure: true - docker buildx build --builder default --tag 192.168.1.9:3000/tai/aberwyn/aberwyn:latest --tag 192.168.1.9:3000/tai/aberwyn/aberwyn:${DRONE_COMMIT_SHA:0:7} --cache-from=type=registry,ref=192.168.1.9:3000/tai/aberwyn/aberwyn:buildcache --push -f Aberwyn/Dockerfile .
- name: restart-unraid-container - name: restart-unraid-container
image: appleboy/drone-ssh image: appleboy/drone-ssh
@@ -38,9 +35,11 @@ steps:
from_secret: unraid_ssh_private_key from_secret: unraid_ssh_private_key
script: script:
- docker pull 192.168.1.9:3000/tai/aberwyn/aberwyn:latest - docker pull 192.168.1.9:3000/tai/aberwyn/aberwyn:latest
- docker stop Aberwyn || true - docker stop aberwyn || true
- docker rm Aberwyn || true - docker rm aberwyn || true
- docker run -d --name='Aberwyn' --net='br0' -e TZ='Europe/Berlin' -p 80:80 192.168.1.9:3000/tai/aberwyn/aberwyn:latest - docker volume create aberwyn_config || true
- docker volume create aberwyn_keys || true
- docker run -d --name=aberwyn --net=br0 -e TZ=Europe/Berlin -p 80:80 -v aberwyn_config:/app/infrastructure -v aberwyn_keys:/root/.aspnet/DataProtection-Keys 192.168.1.9:3000/tai/aberwyn/aberwyn:latest
- name: notify-result - name: notify-result
image: alpine image: alpine

6
.gitignore vendored
View File

@@ -360,4 +360,8 @@ MigrationBackup/
.ionide/ .ionide/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd FodyWeavers.xsd
# Setupfil för Aberwyn
infrastructure/setup.json
Aberwyn/Infrastructure/setup.json

View File

@@ -11,10 +11,6 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{423CD237-7404-4355-868F-CE5861835258}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{423CD237-7404-4355-868F-CE5861835258}.Debug|Any CPU.Build.0 = Debug|Any CPU
{423CD237-7404-4355-868F-CE5861835258}.Release|Any CPU.ActiveCfg = Release|Any CPU
{423CD237-7404-4355-868F-CE5861835258}.Release|Any CPU.Build.0 = Release|Any CPU
{F5586986-B726-4E05-B31B-2E24CA5B2B89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F5586986-B726-4E05-B31B-2E24CA5B2B89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F5586986-B726-4E05-B31B-2E24CA5B2B89}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5586986-B726-4E05-B31B-2E24CA5B2B89}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F5586986-B726-4E05-B31B-2E24CA5B2B89}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5586986-B726-4E05-B31B-2E24CA5B2B89}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

@@ -4,9 +4,9 @@ name: default
steps: steps:
- name: build-dotnet - name: build-dotnet
image: mcr.microsoft.com/dotnet/sdk:6.0 image: alpine
commands: commands:
- dotnet publish Aberwyn/Aberwyn.csproj -c Release -o out - echo "Docker build will handle dotnet publish"
- name: build-docker - name: build-docker
image: plugins/docker image: plugins/docker
@@ -18,6 +18,41 @@ steps:
password: password:
from_secret: gitea_token from_secret: gitea_token
dockerfile: Aberwyn/Dockerfile dockerfile: Aberwyn/Dockerfile
context: Aberwyn context: .
tags: tags:
- latest - latest
insecure: true
- name: restart-unraid-container
image: appleboy/drone-ssh
settings:
host: 192.168.1.108
port: 22
username:
from_secret: unraid_ssh_user
key:
from_secret: unraid_ssh_private_key
script:
- docker pull 192.168.1.9:3000/tai/aberwyn/aberwyn:latest
- docker stop Aberwyn || true
- docker rm Aberwyn || true
- docker run -d --name='Aberwyn' --net='br0' -e TZ='Europe/Berlin' -p 80:80 192.168.1.9:3000/tai/aberwyn/aberwyn:latest
- name: notify-result
image: alpine
when:
status:
- success
- failure
commands:
- apk add --no-cache curl
- |
if [ "$DRONE_BUILD_STATUS" = "success" ]; then
curl -X POST http://192.168.1.196:8123/api/webhook/aberwyn_update_success
else
curl -X POST http://192.168.1.196:8123/api/webhook/aberwyn_update_failed
fi
trigger:
branch:
- master

View File

@@ -9,23 +9,9 @@
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="NewFolder\**" />
<Content Remove="NewFolder\**" />
<EmbeddedResource Remove="NewFolder\**" />
<None Remove="NewFolder\**" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Data\BudgetService.cs" />
</ItemGroup>
<ItemGroup>
<Content Remove="Views\Home\Budget.cshtml" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AngularJS.Core" Version="1.8.2" /> <PackageReference Include="AngularJS.Core" Version="1.8.2" />
<PackageReference Include="BencodeNET" Version="5.0.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.67" /> <PackageReference Include="HtmlAgilityPack" Version="1.11.67" />
<PackageReference Include="Lib.Net.Http.WebPush" Version="3.3.1" /> <PackageReference Include="Lib.Net.Http.WebPush" Version="3.3.1" />
@@ -35,6 +21,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.36" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.36" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.36" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.36"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.36">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -52,12 +39,12 @@
<!-- Övrigt --> <!-- Övrigt -->
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.18" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.18" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.9" />
<PackageReference Include="WebPush" Version="1.0.12" /> <PackageReference Include="WebPush" Version="1.0.12" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Migrations\" /> <Folder Include="Migrations\" />
<Folder Include="Views\NewFolder\" />
<Folder Include="wwwroot\images\meals\" /> <Folder Include="wwwroot\images\meals\" />
</ItemGroup> </ItemGroup>

View File

@@ -19,32 +19,13 @@
<span asp-validation-for="Input.UserName" class="text-danger"></span> <span asp-validation-for="Input.UserName" class="text-danger"></span>
</div> </div>
<div class="form-floating"> <div class="form-floating">
<input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" />
<label asp-for="Input.Password" class="form-label"></label> <label asp-for="Input.Password" class="form-label"></label>
<input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" />
<span asp-validation-for="Input.Password" class="text-danger"></span> <span asp-validation-for="Input.Password" class="text-danger"></span>
</div> </div>
<div>
<div class="checkbox">
<label asp-for="Input.RememberMe" class="form-label">
<input class="form-check-input" asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
</div>
<div> <div>
<button id="login-submit" type="submit" class="w-100 btn btn-lg btn-primary">Log in</button> <button id="login-submit" type="submit" class="w-100 btn btn-lg btn-primary">Log in</button>
</div> </div>
<div>
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
<p>
<a id="resend-confirmation" asp-page="./ResendEmailConfirmation">Resend email confirmation</a>
</p>
</div>
</form> </form>
</section> </section>
</div> </div>

View File

@@ -62,7 +62,7 @@ namespace Aberwyn.Areas.Identity.Pages.Account
public class InputModel public class InputModel
{ {
[Required] [Required]
[Display(Name = "Användarnamn")] [Display(Name = "Username")]
public string UserName { get; set; } public string UserName { get; set; }
[Required] [Required]
@@ -99,7 +99,7 @@ namespace Aberwyn.Areas.Identity.Pages.Account
{ {
// This doesn't count login failures towards account lockout // This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true // To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: false); var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, isPersistent: true, lockoutOnFailure: false);
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation("User logged in."); _logger.LogInformation("User logged in.");

View File

@@ -11,6 +11,7 @@ namespace Aberwyn.Controllers
[Authorize(Roles = "Admin")] [Authorize(Roles = "Admin")]
public class AdminController : Controller public class AdminController : Controller
{ {
private readonly MenuService _menuService;
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager; private readonly RoleManager<IdentityRole> _roleManager;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
@@ -18,12 +19,14 @@ namespace Aberwyn.Controllers
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
public AdminController( public AdminController(
MenuService menuService,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager, RoleManager<IdentityRole> roleManager,
IConfiguration configuration, IConfiguration configuration,
IHostEnvironment env, IHostEnvironment env,
ApplicationDbContext context) ApplicationDbContext context)
{ {
_menuService = menuService;
_userManager = userManager; _userManager = userManager;
_roleManager = roleManager; _roleManager = roleManager;
_configuration = configuration; _configuration = configuration;
@@ -102,54 +105,20 @@ namespace Aberwyn.Controllers
} }
[HttpPost] [HttpPost]
[Authorize(Roles = "Admin")] [Authorize(Roles = "Admin")]
public IActionResult ImportMealsFromProd() public IActionResult ImportMenusFromCustom(string dbHost, int dbPort, string dbName, string dbUser, string dbPassword)
{ {
var prodService = MenuService.CreateWithConfig(_configuration, _env, useProdDb: true); var connStr = $"Server={dbHost};Port={dbPort};Database={dbName};Uid={dbUser};Pwd={dbPassword};";
var devService = new MenuService(_context); // injicerad context används var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
var prodMeals = prodService.GetMealsDetailed(); using var customContext = new ApplicationDbContext(optionsBuilder.Options);
var sourceService = new MenuService(customContext);
foreach (var meal in prodMeals)
{
// Kopiera utan ID (för att undvika konflikt) och spara
var newMeal = new Meal
{
Name = meal.Name,
Description = meal.Description,
ProteinType = meal.ProteinType,
Category = meal.Category,
CarbType = meal.CarbType,
RecipeUrl = meal.RecipeUrl,
ImageUrl = meal.ImageUrl,
IsAvailable = meal.IsAvailable,
CreatedAt = meal.CreatedAt,
Instructions = meal.Instructions,
ImageData = meal.ImageData,
ImageMimeType = meal.ImageMimeType,
Ingredients = meal.Ingredients.Select(i => new Ingredient
{
Quantity = i.Quantity,
Item = i.Item
}).ToList()
};
devService.SaveOrUpdateMealWithIngredients(newMeal);
}
return Content("Import klar!");
}
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult ImportMenusFromProd()
{
var prodService = MenuService.CreateWithConfig(_configuration, _env, useProdDb: true);
var devService = new MenuService(_context); var devService = new MenuService(_context);
var allProdMenus = prodService.GetAllWeeklyMenus(); var sourceMenus = sourceService.GetAllWeeklyMenus();
var allMeals = devService.GetMeals(); var devMeals = devService.GetMeals();
foreach (var menu in allProdMenus) foreach (var menu in sourceMenus)
{ {
var newMenu = new WeeklyMenu var newMenu = new WeeklyMenu
{ {
@@ -163,34 +132,99 @@ namespace Aberwyn.Controllers
}; };
if (!string.IsNullOrEmpty(menu.BreakfastMealName)) if (!string.IsNullOrEmpty(menu.BreakfastMealName))
newMenu.BreakfastMealId = allMeals.FirstOrDefault(m => m.Name == menu.BreakfastMealName)?.Id; newMenu.BreakfastMealId = devMeals.FirstOrDefault(m => m.Name == menu.BreakfastMealName)?.Id;
if (!string.IsNullOrEmpty(menu.LunchMealName)) if (!string.IsNullOrEmpty(menu.LunchMealName))
newMenu.LunchMealId = allMeals.FirstOrDefault(m => m.Name == menu.LunchMealName)?.Id; newMenu.LunchMealId = devMeals.FirstOrDefault(m => m.Name == menu.LunchMealName)?.Id;
if (!string.IsNullOrEmpty(menu.DinnerMealName)) if (!string.IsNullOrEmpty(menu.DinnerMealName))
newMenu.DinnerMealId = allMeals.FirstOrDefault(m => m.Name == menu.DinnerMealName)?.Id; newMenu.DinnerMealId = devMeals.FirstOrDefault(m => m.Name == menu.DinnerMealName)?.Id;
_context.WeeklyMenus.Add(newMenu); _context.WeeklyMenus.Add(newMenu);
} }
_context.SaveChanges(); _context.SaveChanges();
TempData["Message"] = "Import av veckomenyer klar."; TempData["Message"] = $"✅ Import av veckomenyer från extern databas klar ({sourceMenus.Count}).";
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult GenerateThumbnails()
{
var count = _menuService.GenerateMissingThumbnails();
return Ok($"{count} thumbnails skapades.");
}
[HttpPost] [HttpPost]
[Authorize(Roles = "Admin")] [Authorize(Roles = "Admin")]
public IActionResult ImportBudgetFromProd() public IActionResult ImportMealsFromCustom(string dbHost, int dbPort, string dbName, string dbUser, string dbPassword)
{ {
// Hämta connection till produktion var connStr = $"Server={dbHost};Port={dbPort};Database={dbName};Uid={dbUser};Pwd={dbPassword};";
using var prodContext = ApplicationDbContextFactory.CreateWithConfig(_configuration, _env, useProdDb: true); var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr), mySqlOptions => mySqlOptions.CommandTimeout(180));
using var customContext = new ApplicationDbContext(optionsBuilder.Options);
// Importera definitioner först var customService = new MenuService(customContext);
var prodCategoryDefs = prodContext.BudgetCategoryDefinitions.ToList(); var devService = new MenuService(_context);
var prodItemDefs = prodContext.BudgetItemDefinitions.ToList();
foreach (var def in prodCategoryDefs) try
{
var importedMeals = customService.GetMealsDetailed(); // Ska inkludera Ingredients
foreach (var meal in importedMeals)
{
var newMeal = new Meal
{
Id = meal.Id, // 👈 Viktigt!
Name = meal.Name,
Description = meal.Description,
ProteinType = meal.ProteinType,
Category = meal.Category,
CarbType = meal.CarbType,
RecipeUrl = meal.RecipeUrl,
ImageUrl = meal.ImageUrl,
IsAvailable = meal.IsAvailable,
CreatedAt = meal.CreatedAt,
Instructions = meal.Instructions,
ImageData = meal.ImageData,
ImageMimeType = meal.ImageMimeType,
Ingredients = meal.Ingredients.Select(i => new Ingredient
{
MealId = meal.Id, // 👈 Koppla till rätt måltid
Quantity = i.Quantity,
Item = i.Item
}).ToList()
};
devService.SaveOrUpdateMealWithIngredients(newMeal);
}
TempData["Message"] = $"✅ {importedMeals.Count} måltider importerade från extern databas.";
}
catch (Exception ex)
{
TempData["Message"] = $"❌ Fel vid import: {ex.Message}";
}
return RedirectToAction("Index");
}
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult ImportBudgetFromCustom(string dbHost, int dbPort, string dbName, string dbUser, string dbPassword)
{
var connStr = $"Server={dbHost};Port={dbPort};Database={dbName};Uid={dbUser};Pwd={dbPassword};";
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
using var sourceContext = new ApplicationDbContext(optionsBuilder.Options);
var categoryDefs = sourceContext.BudgetCategoryDefinitions.ToList();
var itemDefs = sourceContext.BudgetItemDefinitions.ToList();
foreach (var def in categoryDefs)
{ {
if (!_context.BudgetCategoryDefinitions.Any(d => d.Name == def.Name)) if (!_context.BudgetCategoryDefinitions.Any(d => d.Name == def.Name))
{ {
@@ -199,11 +233,10 @@ namespace Aberwyn.Controllers
Name = def.Name, Name = def.Name,
Color = def.Color ?? "#cccccc" Color = def.Color ?? "#cccccc"
}); });
} }
} }
foreach (var def in prodItemDefs) foreach (var def in itemDefs)
{ {
if (!_context.BudgetItemDefinitions.Any(d => d.Name == def.Name)) if (!_context.BudgetItemDefinitions.Any(d => d.Name == def.Name))
{ {
@@ -211,19 +244,17 @@ namespace Aberwyn.Controllers
} }
} }
_context.SaveChanges(); // Se till att ID:n finns för FK:n nedan _context.SaveChanges();
// Ladda definitioner i minnet för snabb lookup
var devCategoryDefs = _context.BudgetCategoryDefinitions.ToList(); var devCategoryDefs = _context.BudgetCategoryDefinitions.ToList();
var devItemDefs = _context.BudgetItemDefinitions.ToList(); var devItemDefs = _context.BudgetItemDefinitions.ToList();
// Importera budgetperioder med kategorier och items var periods = sourceContext.BudgetPeriods
var prodPeriods = prodContext.BudgetPeriods
.Include(p => p.Categories) .Include(p => p.Categories)
.ThenInclude(c => c.Items) .ThenInclude(c => c.Items)
.ToList(); .ToList();
foreach (var period in prodPeriods) foreach (var period in periods)
{ {
var exists = _context.BudgetPeriods var exists = _context.BudgetPeriods
.Any(p => p.Year == period.Year && p.Month == period.Month); .Any(p => p.Year == period.Year && p.Month == period.Month);
@@ -259,11 +290,13 @@ namespace Aberwyn.Controllers
} }
_context.SaveChanges(); _context.SaveChanges();
TempData["Message"] = "✅ Import av budgetdata från produktion är klar."; TempData["Message"] = $"✅ Import av budgetdata från extern databas klar ({periods.Count} månader).";
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
//Todo //Todo
[HttpGet] [HttpGet]
@@ -285,16 +318,31 @@ namespace Aberwyn.Controllers
[HttpPost] [HttpPost]
public IActionResult AddTodoTask([FromBody] TodoTask task) public IActionResult AddTodoTask([FromBody] TodoTask task)
{ {
if (string.IsNullOrWhiteSpace(task?.Title)) try
return BadRequest("Titel krävs"); {
if (string.IsNullOrWhiteSpace(task?.Title))
return BadRequest("Titel krävs");
task.CreatedAt = DateTime.UtcNow; task.CreatedAt = DateTime.UtcNow;
_context.TodoTasks.Add(task);
_context.SaveChanges();
return Json(task); task.Status ??= "ideas";
task.Tags ??= "";
task.AssignedTo ??= null;
task.Description ??= "";
_context.TodoTasks.Add(task);
_context.SaveChanges();
return Json(task);
}
catch (Exception ex)
{
// 👇 Returnera hela stacktracen som JSON för felsökning
return StatusCode(500, ex.ToString());
}
} }
[HttpPost] [HttpPost]
public IActionResult UpdateTodoTask([FromBody] TodoTask task) public IActionResult UpdateTodoTask([FromBody] TodoTask task)
{ {
@@ -305,18 +353,41 @@ namespace Aberwyn.Controllers
existing.Title = task.Title; existing.Title = task.Title;
existing.Status = task.Status; existing.Status = task.Status;
existing.Priority = task.Priority; existing.Priority = task.Priority;
existing.Description = task.Description;
existing.Tags = task.Tags;
existing.AssignedTo = task.AssignedTo;
existing.IsArchived = task.IsArchived;
_context.SaveChanges(); _context.SaveChanges();
return Ok(); return Ok();
} }
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult TestDbConnection(string dbHost, int dbPort, string dbName, string dbUser, string dbPassword)
{
var connStr = $"Server={dbHost};Port={dbPort};Database={dbName};Uid={dbUser};Pwd={dbPassword};";
try
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
using var context = new ApplicationDbContext(builder.Options);
context.Database.OpenConnection();
context.Database.CloseConnection();
return Json(new { success = true, message = "✅ Anslutning lyckades!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = $"❌ Anslutning misslyckades: {ex.Message}" });
}
}
} }
public class AdminUserViewModel
public class AdminUserViewModel
{ {
public string UserId { get; set; } public string UserId { get; set; }
public string Email { get; set; } public string Email { get; set; }

View File

@@ -43,8 +43,8 @@ namespace Aberwyn.Controllers
var dto = new BudgetDto var dto = new BudgetDto
{ {
Id = period.Id, Id = period.Id,
Year = period.Year, Year = period.Year ?? 0,
Month = period.Month, Month = period.Month ?? 0,
Categories = period.Categories Categories = period.Categories
.OrderBy(cat => cat.Order) .OrderBy(cat => cat.Order)
.Select(cat => new BudgetCategoryDto .Select(cat => new BudgetCategoryDto
@@ -61,7 +61,8 @@ namespace Aberwyn.Controllers
Amount = i.Amount, Amount = i.Amount,
IsExpense = i.IsExpense, IsExpense = i.IsExpense,
IncludeInSummary = i.IncludeInSummary, IncludeInSummary = i.IncludeInSummary,
BudgetItemDefinitionId = i.BudgetItemDefinitionId BudgetItemDefinitionId = i.BudgetItemDefinitionId,
PaymentStatus = i.PaymentStatus
}).ToList() }).ToList()
}).ToList() }).ToList()
}; };
@@ -74,6 +75,72 @@ namespace Aberwyn.Controllers
} }
} }
[HttpGet("byname/{name}")]
public async Task<IActionResult> GetBudgetByName(string name)
{
var period = await _context.BudgetPeriods
.Include(p => p.Categories)
.ThenInclude(c => c.Items)
.FirstOrDefaultAsync(p => p.Name != null && p.Name.ToLower() == name.ToLower());
if (period == null)
{
return Ok(new BudgetDto
{
Name = name,
Categories = new List<BudgetCategoryDto>()
});
}
var dto = new BudgetDto
{
Id = period.Id,
Name = period.Name,
Year = period.Year ?? 0,
Month = period.Month ?? 0,
Categories = period.Categories
.OrderBy(cat => cat.Order)
.Select(cat => new BudgetCategoryDto
{
Id = cat.Id,
Name = cat.Name,
Color = cat.Color,
Items = cat.Items
.OrderBy(i => i.Order)
.Select(i => new BudgetItemDto
{
Id = i.Id,
Name = i.Name,
Amount = i.Amount,
IsExpense = i.IsExpense,
IncludeInSummary = i.IncludeInSummary,
BudgetItemDefinitionId = i.BudgetItemDefinitionId,
PaymentStatus = i.PaymentStatus
}).ToList()
}).ToList()
};
return Ok(dto);
}
[HttpPut("updatePaymentStatus")]
public IActionResult UpdatePaymentStatus([FromBody] PaymentStatusUpdateDto dto)
{
if (dto == null)
return BadRequest("dto is null");
var item = _context.BudgetItems.Find(dto.ItemId);
if (item == null) return NotFound();
item.PaymentStatus = (PaymentStatus)dto.Status;
_context.SaveChanges();
return Ok();
}
[HttpPut("category/{id}")] [HttpPut("category/{id}")]
public async Task<IActionResult> UpdateCategory(int id, [FromBody] BudgetCategoryDto updatedCategory) public async Task<IActionResult> UpdateCategory(int id, [FromBody] BudgetCategoryDto updatedCategory)
{ {
@@ -183,11 +250,37 @@ namespace Aberwyn.Controllers
[HttpPost] [HttpPost]
public async Task<IActionResult> CreatePeriod([FromBody] BudgetPeriod newPeriod) public async Task<IActionResult> CreatePeriod([FromBody] BudgetPeriod newPeriod)
{ {
_context.BudgetPeriods.Add(newPeriod); if (!string.IsNullOrWhiteSpace(newPeriod.Name))
await _context.SaveChangesAsync(); {
return CreatedAtAction(nameof(GetBudget), new { year = newPeriod.Year, month = newPeriod.Month }, newPeriod); var existingNamed = await _context.BudgetPeriods
.FirstOrDefaultAsync(p => p.Name != null && p.Name.ToLower() == newPeriod.Name.ToLower());
if (existingNamed != null)
return Conflict("En budget med detta namn finns redan.");
_context.BudgetPeriods.Add(newPeriod);
await _context.SaveChangesAsync();
return Ok(new { id = newPeriod.Id });
}
if (newPeriod.Year.HasValue && newPeriod.Month.HasValue)
{
var existing = await _context.BudgetPeriods
.FirstOrDefaultAsync(p => p.Year == newPeriod.Year && p.Month == newPeriod.Month);
if (existing != null)
return Conflict("En budget för denna månad finns redan.");
_context.BudgetPeriods.Add(newPeriod);
await _context.SaveChangesAsync();
return Ok(new { id = newPeriod.Id });
}
return BadRequest("Varken namn eller år/månad angivet.");
} }
[HttpPut("item/{id}")] [HttpPut("item/{id}")]
public async Task<IActionResult> UpdateItem(int id, [FromBody] BudgetItem updatedItem) public async Task<IActionResult> UpdateItem(int id, [FromBody] BudgetItem updatedItem)
{ {
@@ -314,19 +407,12 @@ namespace Aberwyn.Controllers
return BadRequest("Ogiltig data."); return BadRequest("Ogiltig data.");
var period = await _context.BudgetPeriods var period = await _context.BudgetPeriods
.FirstOrDefaultAsync(p => p.Year == newCategoryDto.Year && p.Month == newCategoryDto.Month); .FirstOrDefaultAsync(p => p.Id == newCategoryDto.BudgetPeriodId);
if (period == null) if (period == null)
{ return NotFound("Kunde inte hitta angiven budgetperiod.");
period = new BudgetPeriod
{
Year = newCategoryDto.Year,
Month = newCategoryDto.Month
};
_context.BudgetPeriods.Add(period);
await _context.SaveChangesAsync();
}
// 🔁 fortsätt som tidigare…
var definition = await _context.BudgetCategoryDefinitions var definition = await _context.BudgetCategoryDefinitions
.FirstOrDefaultAsync(d => d.Name.ToLower() == newCategoryDto.Name.ToLower()); .FirstOrDefaultAsync(d => d.Name.ToLower() == newCategoryDto.Name.ToLower());
@@ -356,6 +442,8 @@ namespace Aberwyn.Controllers
return Ok(new { id = category.Id }); return Ok(new { id = category.Id });
} }
[HttpDelete("category/{id}")] [HttpDelete("category/{id}")]
public async Task<IActionResult> DeleteCategory(int id) public async Task<IActionResult> DeleteCategory(int id)
{ {

View File

@@ -3,13 +3,31 @@ using Microsoft.AspNetCore.Mvc;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
[Authorize(Roles = "Budget")]
public class BudgetController : Controller public class BudgetController : Controller
{ {
[Authorize(Roles = "Budget")] [Route("budget/{year:int}/{month:int}")]
public IActionResult Index() public IActionResult Index(int year, int month)
{ {
ViewData["HideSidebar"] = true; ViewBag.Year = year;
ViewBag.Month = month;
return View(); return View();
} }
[Route("budget/{name}")]
public IActionResult Index(string name)
{
ViewBag.BudgetName = name;
return View();
}
// För fallback när ingen månad/år anges
[Route("budget")]
public IActionResult Index()
{
var now = DateTime.Now;
return RedirectToAction("Index", new { year = now.Year, month = now.Month });
}
} }
} }

View File

@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace Aberwyn.Controllers
{
public class ErrorController : Controller
{
[Route("Error/{statusCode}")]
public IActionResult HttpStatusCodeHandler(int statusCode)
{
ViewData["ErrorCode"] = statusCode;
return View("Error");
}
[Route("Error")]
public IActionResult Error()
{
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
ViewData["Exception"] = exceptionFeature?.Error;
return View("Error");
}
}
}

View File

@@ -10,6 +10,8 @@ using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Aberwyn.Services;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
@@ -19,25 +21,29 @@ namespace Aberwyn.Controllers
private readonly IHostEnvironment _env; private readonly IHostEnvironment _env;
private readonly MenuService _menuService; private readonly MenuService _menuService;
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private readonly PushNotificationService _notificationService;
private readonly PizzaNotificationService _pizzaNotifier;
public FoodMenuController(MenuService menuService, IConfiguration configuration, IHostEnvironment env, ApplicationDbContext context) public FoodMenuController(MenuService menuService, IConfiguration configuration, IHostEnvironment env, ApplicationDbContext context, PushNotificationService notificationService, PizzaNotificationService pizzaNotificationService)
{ {
_menuService = menuService; _menuService = menuService;
_configuration = configuration; _configuration = configuration;
_env = env; _env = env;
_context = context; _context = context;
_notificationService = notificationService;
_pizzaNotifier = pizzaNotificationService;
} }
[HttpGet] [HttpGet]
public IActionResult PizzaOrder() public IActionResult PizzaOrder()
{ {
var pizzas = _menuService.GetMealsByCategory("Pizza") var meals = _menuService.GetMealsByCategoryName("Pizza", onlyAvailable: true);
.Where(p => p.IsAvailable) Console.WriteLine("Pizzas: ", meals);
.ToList(); var dtoList = meals.Select(m => MealListDto.FromMeal(m)).ToList();
ViewBag.Pizzas = dtoList;
ViewBag.Pizzas = pizzas; ViewBag.RestaurantIsOpen = GetRestaurantStatus();
ViewBag.RestaurantIsOpen = GetRestaurantStatus();
int? lastId = HttpContext.Session.GetInt32("LastPizzaOrderId"); int? lastId = HttpContext.Session.GetInt32("LastPizzaOrderId");
if (lastId.HasValue) if (lastId.HasValue)
@@ -53,6 +59,7 @@ namespace Aberwyn.Controllers
} }
[HttpGet] [HttpGet]
public IActionResult EditPizzaOrder(int id) public IActionResult EditPizzaOrder(int id)
{ {
@@ -82,11 +89,11 @@ namespace Aberwyn.Controllers
[HttpPost] [HttpPost]
public IActionResult PizzaOrder(string customerName, string pizzaName, string ingredients, int? orderId) public async Task<IActionResult> PizzaOrder(string customerName, string pizzaName, string ingredients, int? orderId)
{ {
if (string.IsNullOrWhiteSpace(customerName) || string.IsNullOrWhiteSpace(pizzaName)) if (string.IsNullOrWhiteSpace(customerName) || string.IsNullOrWhiteSpace(pizzaName))
{ {
TempData["Error"] = "Fyll i b<EFBFBD>de namn och pizza!"; TempData["Error"] = "Fyll i både namn och pizza!";
return RedirectToAction("PizzaOrder"); return RedirectToAction("PizzaOrder");
} }
@@ -102,10 +109,10 @@ namespace Aberwyn.Controllers
order.CustomerName = customerName.Trim(); order.CustomerName = customerName.Trim();
order.PizzaName = pizzaName.Trim(); order.PizzaName = pizzaName.Trim();
order.IngredientsJson = ingredients; order.IngredientsJson = ingredients;
order.Status = "Unconfirmed";// <20>terst<73>ll status om du vill order.Status = "Unconfirmed";
_context.SaveChanges(); _context.SaveChanges();
TempData["Success"] = $"Din best<EFBFBD>llning har uppdaterats!"; TempData["Success"] = $"Din beställning har uppdaterats!";
return RedirectToAction("PizzaOrder"); return RedirectToAction("PizzaOrder");
} }
} }
@@ -123,11 +130,11 @@ namespace Aberwyn.Controllers
_context.PizzaOrders.Add(order); _context.PizzaOrders.Add(order);
_context.SaveChanges(); _context.SaveChanges();
TempData["ForceShowForm"] = "true"; TempData["ForceShowForm"] = "true";
await _pizzaNotifier.NotifyPizzaSubscribersAsync(order.PizzaName, order.CustomerName);
HttpContext.Session.SetInt32("LastPizzaOrderId", order.Id); HttpContext.Session.SetInt32("LastPizzaOrderId", order.Id);
TempData["Success"] = $"Tack {order.CustomerName}! Din pizza <EFBFBD>r best<EFBFBD>lld!"; TempData["Success"] = $"Tack {order.CustomerName}! Din pizza är beställd!";
return RedirectToAction("PizzaOrder"); return RedirectToAction("PizzaOrder");
} }
@@ -152,10 +159,14 @@ namespace Aberwyn.Controllers
var allMeals = _menuService.GetMeals(); var allMeals = _menuService.GetMeals();
var categories = _menuService.GetMealCategories();
var pizzaCategory = categories.FirstOrDefault(c => c.Name.Equals("Pizza", StringComparison.OrdinalIgnoreCase));
viewModel.AvailablePizzas = allMeals viewModel.AvailablePizzas = allMeals
.Where(m => m.Category == "Pizza") .Where(m => m.MealCategoryId == pizzaCategory?.Id)
.OrderBy(m => m.Name) .OrderBy(m => m.Name)
.ToList(); .ToList();
ViewBag.RestaurantIsOpen = GetRestaurantStatus(); ViewBag.RestaurantIsOpen = GetRestaurantStatus();
@@ -167,19 +178,42 @@ namespace Aberwyn.Controllers
[HttpPost] [HttpPost]
[Authorize(Roles = "Chef")] [Authorize(Roles = "Chef")]
public IActionResult UpdatePizzaOrder(int id, string status, string ingredientsJson) public async Task<IActionResult> UpdatePizzaOrder(int id, string status, string ingredientsJson)
{ {
var order = _context.PizzaOrders.FirstOrDefault(p => p.Id == id); var order = await _context.PizzaOrders.FirstOrDefaultAsync(p => p.Id == id);
if (order != null) if (order == null)
return RedirectToAction("PizzaAdmin");
order.Status = status;
order.IngredientsJson = ingredientsJson;
await _context.SaveChangesAsync();
// Skicka pushnotiser till kopplade prenumeranter
var subscribers = await _context.PushSubscribers
.Where(s => s.PizzaOrderId == id)
.ToListAsync();
var payload = $@"{{
""title"": ""Din pizza! 🍕"",
""body"": ""Statusuppdatering: {status}""
}}";
foreach (var sub in subscribers)
{ {
order.Status = status; try
order.IngredientsJson = ingredientsJson; {
_context.SaveChanges(); _notificationService.SendNotification(sub.Endpoint, sub.P256DH, sub.Auth, payload);
}
catch (Exception ex)
{
Console.WriteLine($"❌ Kunde inte skicka notis till {sub.Endpoint}: {ex.Message}");
}
} }
return RedirectToAction("PizzaAdmin"); return RedirectToAction("PizzaAdmin");
} }
[Authorize(Roles = "Chef")] [Authorize(Roles = "Chef")]
public IActionResult Veckomeny(int? week, int? year) public IActionResult Veckomeny(int? week, int? year)
{ {

View File

@@ -27,7 +27,14 @@ namespace Aberwyn.Controllers
{ {
var isOpen = _context.AppSettings.FirstOrDefault(x => x.Key == "RestaurantIsOpen")?.Value == "True"; var isOpen = _context.AppSettings.FirstOrDefault(x => x.Key == "RestaurantIsOpen")?.Value == "True";
ViewBag.RestaurantIsOpen = isOpen; ViewBag.RestaurantIsOpen = isOpen;
return View();
var now = DateTime.Now;
var showDate = now.Hour >= 20 ? now.Date.AddDays(1) : now.Date;
var todaysMenu = _menuService.GetMenuForDate(showDate);
ViewBag.ShowDate = showDate;
return View(todaysMenu);
} }
public IActionResult Privacy() public IActionResult Privacy()

View File

@@ -2,6 +2,8 @@
using Aberwyn.Models; using Aberwyn.Models;
using Aberwyn.Data; using Aberwyn.Data;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
@@ -10,28 +12,48 @@ namespace Aberwyn.Controllers
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env; private readonly IHostEnvironment _env;
private readonly MenuService _menuService; private readonly MenuService _menuService;
public MealController(MenuService menuService, IConfiguration configuration, IHostEnvironment env)
public MealController(IConfiguration configuration, IHostEnvironment env)
{ {
_menuService = menuService;
_configuration = configuration; _configuration = configuration;
_env = env; _env = env;
} }
[HttpGet] [HttpGet("/meal")]
public IActionResult View(int id, bool edit = false) public IActionResult Index()
{ {
var service = _menuService; return View("Index");
var meal = service.GetMealById(id); }
[HttpGet]
public IActionResult View(int? id, bool edit = false)
{
Meal meal;
ViewData["IsEditing"] = edit; // → här if (id.HasValue)
if (meal == null)
{ {
return NotFound(); meal = _menuService.GetMealById(id.Value);
if (meal == null)
return NotFound();
} }
else
{
meal = new Meal
{
Name = "",
Description = "",
Ingredients = new List<Ingredient>(),
IsAvailable = true,
CreatedAt = DateTime.Now
};
}
ViewBag.Categories = _menuService.GetMealCategories()
.Where(c => c.IsActive)
.OrderBy(c => c.Name)
.ToList();
ViewData["IsEditing"] = edit;
return View("View", meal); return View("View", meal);
} }
[HttpGet] [HttpGet]
[Route("Meal/Tooltip/{id}")] [Route("Meal/Tooltip/{id}")]
public IActionResult Tooltip(int id) public IActionResult Tooltip(int id)
@@ -69,6 +91,15 @@ namespace Aberwyn.Controllers
return StatusCode(500, $"<pre>{ex.Message}</pre>"); return StatusCode(500, $"<pre>{ex.Message}</pre>");
} }
} }
[HttpGet("Meal/Thumbnail/{id}")]
public IActionResult Thumbnail(int id)
{
var meal = _menuService.GetMealById(id);
if (meal == null || meal.ThumbnailData == null)
return NotFound();
return File(meal.ThumbnailData, "image/webp"); // eller image/jpeg om du använder det
}
@@ -92,6 +123,8 @@ namespace Aberwyn.Controllers
ImageFile.CopyTo(ms); ImageFile.CopyTo(ms);
meal.ImageData = ms.ToArray(); meal.ImageData = ms.ToArray();
meal.ImageMimeType = ImageFile.ContentType; meal.ImageMimeType = ImageFile.ContentType;
meal.ThumbnailData = GenerateThumbnail(ImageFile);
} }
else else
{ {
@@ -110,8 +143,21 @@ namespace Aberwyn.Controllers
} }
private byte[] GenerateThumbnail(IFormFile file)
{
using var image = SixLabors.ImageSharp.Image.Load(file.OpenReadStream());
image.Mutate(x => x.Resize(new ResizeOptions
{
Mode = ResizeMode.Max,
Size = new Size(300, 300) // eller vad du vill för korten
}));
using var ms = new MemoryStream();
image.SaveAsWebp(ms); // kräver ImageSharp.Webp-paketet
return ms.ToArray();
}
[HttpPost] [HttpPost]
@@ -121,5 +167,123 @@ namespace Aberwyn.Controllers
//service.DeleteMeal(id); //service.DeleteMeal(id);
return RedirectToAction("Edit"); // eller tillbaka till lista return RedirectToAction("Edit"); // eller tillbaka till lista
} }
[Authorize(Roles = "Admin,Chef")]
[HttpGet("/meal/categories")]
public IActionResult Categories()
{
var categories = _menuService.GetMealCategories()
.Select(cat => {
cat.MealCount = _menuService.GetMealCountForCategory(cat.Id);
return cat;
}).ToList();
return View("MealCategories", categories);
}
[Authorize(Roles = "Admin,Chef")]
[HttpPost("/meal/categories/save")]
public IActionResult SaveCategory(MealCategory category)
{
_menuService.SaveOrUpdateCategory(category);
return RedirectToAction("Categories");
}
[Authorize(Roles = "Admin,Chef")]
[HttpPost("/meal/categories/delete")]
public IActionResult DeleteCategory(int id)
{
_menuService.DeleteCategory(id);
return RedirectToAction("Categories");
}
[HttpGet("/meal/lab")]
public IActionResult Lab(int? id)
{
if (id.HasValue)
{
var entry = _menuService.GetRecipeLabEntryById(id.Value);
if (entry == null) return NotFound();
// Hämta versioner först när vi vet att entry finns
entry.Versions = _menuService.GetLabVersionsForEntry(id.Value);
return View("Lab", entry);
}
// Skapa ett tomt labb-entry för formulär
var newEntry = new RecipeLabEntry
{
Title = "",
Inspiration = "",
Notes = "",
Tags = ""
};
return View("Lab", newEntry);
} }
// Lägg till dessa actions i din MealController
[HttpPost("/meal/lab/save")]
public IActionResult SaveLabEntry(RecipeLabEntry entry)
{
if (entry.Id == 0)
{
// Ny entry
entry.CreatedAt = DateTime.Now;
_menuService.AddLabEntry(entry);
}
else
{
// Uppdatera befintlig
_menuService.UpdateLabEntry(entry);
}
return RedirectToAction("Lab", new { id = entry.Id });
}
[HttpPost("/meal/lab/create")]
public IActionResult CreateLabEntry(RecipeLabEntry entry)
{
entry.CreatedAt = DateTime.Now;
_menuService.AddLabEntry(entry);
return RedirectToAction("Lab", new { id = entry.Id });
}
[HttpPost("/meal/lab/save-ingredients")]
public IActionResult SaveLabIngredients(int RecipeLabEntryId, List<LabIngredient> Ingredients)
{
_menuService.SaveIngredientsForLabEntry(RecipeLabEntryId, Ingredients);
return RedirectToAction("Lab", new { id = RecipeLabEntryId });
}
[HttpPost("/meal/lab/addversion")]
public IActionResult AddLabVersion(RecipeLabVersion version)
{
if (!ModelState.IsValid)
return RedirectToAction("Lab", new { id = version.RecipeLabEntryId });
var entry = _menuService.GetRecipeLabEntryById(version.RecipeLabEntryId);
if (entry == null) return NotFound();
version.CreatedAt = DateTime.Now;
// Kopiera nuvarande ingredienser
var copiedIngredients = entry.Ingredients
.Select(i => new LabVersionIngredient
{
Quantity = i.Quantity,
Item = i.Item
})
.ToList();
_menuService.SaveLabVersionWithIngredients(version, copiedIngredients);
return RedirectToAction("Lab", new { id = version.RecipeLabEntryId });
}
}
} }

View File

@@ -4,6 +4,8 @@ using Aberwyn.Data;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using System.Net.Http.Headers;
using System.Text.Json;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
@@ -25,15 +27,61 @@ namespace Aberwyn.Controllers
return Ok(menu ?? new List<WeeklyMenu>()); return Ok(menu ?? new List<WeeklyMenu>());
} }
[HttpGet("getPublishedMeals")]
public IActionResult GetPublishedMeals([FromQuery] bool includeUnpublished = false)
{
var meals = _menuService.GetMeals()
.Where(m => includeUnpublished || m.IsPublished)
.Select(m => new {
m.Id,
m.Name,
m.Description,
ThumbnailData = m.ThumbnailData != null ? Convert.ToBase64String(m.ThumbnailData) : null
})
.ToList();
return Ok(meals);
}
[HttpGet("getMeals")] [HttpGet("getMeals")]
public IActionResult GetMeals() public IActionResult GetMeals()
{ {
var meals = _menuService.GetMealsDetailed(); // Hämtar med ImageData var meals = _menuService.GetMealsSlim(true);
var mealDtos = meals.Select(MealDto.FromMeal).ToList(); var mealDtos = meals.Select(m => MealDto.FromMeal(m, includeThumbnail: true)).ToList(); // 👈 fix
return Ok(mealDtos); return Ok(mealDtos);
} }
[HttpGet("getWeeklyMenu")]
public IActionResult GetWeeklyMenu(int weekNumber, int year)
{
var menuDtos = _menuService.GetWeeklyMenuDto(weekNumber, year);
Console.WriteLine("Hämtar meals: " + menuDtos);
return Ok(menuDtos);
}
[HttpGet("today")]
public IActionResult GetTodayMenu()
{
var today = DateTime.Today;
var menu = _menuService.GetMenuForDate(today);
if (menu == null)
return NotFound(new { message = "Ingen meny hittades för idag." });
return Ok(new
{
date = today.ToString("yyyy-MM-dd"),
lunch = menu.LunchMealName ?? "",
dinner = menu.DinnerMealName ?? "",
breakfast = menu.BreakfastMealName ?? ""
});
}
[HttpPut("menu")] [HttpPut("menu")]
public IActionResult SaveMenu([FromBody] MenuViewModel weeklyMenu) public IActionResult SaveMenu([FromBody] MenuViewModel weeklyMenu)
{ {
@@ -55,5 +103,44 @@ namespace Aberwyn.Controllers
return StatusCode(500, "Failed to add meal."); return StatusCode(500, "Failed to add meal.");
} }
#region Skolmat
[HttpGet("skolmat")]
public async Task<IActionResult> GetSkolmat(int week, [FromQuery] string sensor = "sensor.engelbrektsskolan")
{
var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3M2Q5ODIyYzU4ZWI0MjM4OWEyMGQ2MWQ2MWVhOWYzYyIsImlhdCI6MTc0OTE1MzY1MCwiZXhwIjoyMDY0NTEzNjUwfQ.8C_dKm7P1BbFVJKc_wT76YnQqiZxkP9EzrsLbfD0Ml8";
var client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.1.196:8123/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var res = await client.GetAsync($"/api/states/{sensor}");
if (!res.IsSuccessStatusCode)
return StatusCode((int)res.StatusCode, $"Kunde inte hämta data för {sensor}");
var json = await res.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(json);
var attr = doc.RootElement.GetProperty("attributes");
if (!attr.TryGetProperty("calendar", out var calendar))
return NotFound("Ingen kalender hittades i attributen");
if (!calendar.TryGetProperty(week.ToString(), out var weekData))
return NotFound("Ingen skolmat för vecka " + week);
var result = new List<object>();
foreach (var day in weekData.EnumerateArray())
{
var weekday = day.GetProperty("weekday").GetString();
var date = day.GetProperty("date").GetString();
var courses = day.GetProperty("courses").EnumerateArray().Select(c => c.GetString()).ToList();
result.Add(new { weekday, date, courses });
}
return Ok(result);
}
#endregion
} }
} }

View File

@@ -0,0 +1,79 @@
using Aberwyn.Data;
using Aberwyn.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Aberwyn.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MealRatingApiController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public MealRatingApiController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
[HttpGet("{mealId}")]
public async Task<IActionResult> GetRating(int mealId)
{
var user = await _userManager.GetUserAsync(User);
if (user == null) return Unauthorized();
var rating = await _context.MealRatings
.FirstOrDefaultAsync(r => r.MealId == mealId && r.UserId == user.Id);
return Ok(rating?.Rating ?? 0);
}
[HttpGet("average/{mealId}")]
public async Task<IActionResult> GetAverageRating(int mealId)
{
var ratings = await _context.MealRatings
.Where(r => r.MealId == mealId)
.ToListAsync();
if (ratings.Count == 0)
return Ok(0);
var avg = ratings.Average(r => r.Rating);
return Ok(avg);
}
[HttpPost]
public async Task<IActionResult> SetRating([FromBody] MealRatingDto model)
{
var user = await _userManager.GetUserAsync(User);
if (user == null) return Unauthorized();
var existing = await _context.MealRatings
.FirstOrDefaultAsync(r => r.MealId == model.MealId && r.UserId == user.Id);
if (existing != null)
{
existing.Rating = model.Rating;
existing.CreatedAt = DateTime.UtcNow;
}
else
{
_context.MealRatings.Add(new MealRating
{
MealId = model.MealId,
UserId = user.Id,
Rating = model.Rating,
CreatedAt = DateTime.UtcNow
});
}
await _context.SaveChangesAsync();
return Ok();
}
}
}

View File

@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Mvc;
namespace Aberwyn.Controllers
{
public class MovieController : Controller
{
[HttpGet("/movie/search")]
public IActionResult Search()
{
return View();
}
}
}

View File

@@ -2,6 +2,7 @@
using Aberwyn.Data; using Aberwyn.Data;
using Aberwyn.Models; using Aberwyn.Models;
using System.Linq; using System.Linq;
using Aberwyn.Services;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
@@ -9,11 +10,14 @@ namespace Aberwyn.Controllers
{ {
private readonly MenuService _menuService; private readonly MenuService _menuService;
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private readonly PizzaNotificationService _pizzaNotifier;
public PizzaController(MenuService menuService, ApplicationDbContext context) public PizzaController(PizzaNotificationService pizzaNotifier,MenuService menuService, ApplicationDbContext context)
{ {
_menuService = menuService; _menuService = menuService;
_context = context; _context = context;
_pizzaNotifier = pizzaNotifier;
} }
[HttpGet] [HttpGet]
@@ -50,6 +54,7 @@ namespace Aberwyn.Controllers
_context.PizzaOrders.Add(order); _context.PizzaOrders.Add(order);
_context.SaveChanges(); _context.SaveChanges();
_pizzaNotifier.NotifyPizzaSubscribersAsync(pizzaName, customerName);
TempData["Success"] = "Beställningen har lagts!"; TempData["Success"] = "Beställningen har lagts!";
return RedirectToAction("Order"); return RedirectToAction("Order");

View File

@@ -3,6 +3,9 @@ using Aberwyn.Models;
using Lib.Net.Http.WebPush; using Lib.Net.Http.WebPush;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Aberwyn.Services;
namespace Aberwyn.Controllers namespace Aberwyn.Controllers
{ {
@@ -12,41 +15,95 @@ namespace Aberwyn.Controllers
{ {
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private readonly PushNotificationService _notificationService; private readonly PushNotificationService _notificationService;
private readonly UserManager<ApplicationUser> _userManager;
private readonly PizzaNotificationService _pizzaNotifier;
public PushController(ApplicationDbContext context, PushNotificationService notificationService)
public PushController(ApplicationDbContext context,
PushNotificationService notificationService,
UserManager<ApplicationUser> userManager,
PizzaNotificationService pizzaNotifier)
{ {
_context = context; _context = context;
_notificationService = notificationService; _notificationService = notificationService;
_userManager = userManager;
_pizzaNotifier = pizzaNotifier;
} }
[HttpPost("notify-pizza")]
public async Task<IActionResult> NotifyPizza()
{
var count = await _pizzaNotifier.NotifyPizzaSubscribersAsync("Capricciosa", User.Identity.Name);
[HttpPost("subscribe")] return Ok(new { message = $"Skickade pizzanotiser till {count} användare." });
public async Task<IActionResult> Subscribe([FromBody] PushSubscription subscription) }
[HttpPost("subscribe-user")]
public async Task<IActionResult> SubscribeUser([FromBody] PushSubscription subscription)
{ {
var user = await _userManager.GetUserAsync(User);
if (user == null) return Unauthorized();
var existing = await _context.PushSubscribers var existing = await _context.PushSubscribers
.FirstOrDefaultAsync(s => s.Endpoint == subscription.Endpoint); .FirstOrDefaultAsync(s => s.Endpoint == subscription.Endpoint);
if (existing == null) if (existing == null)
{ {
var newSubscriber = new PushSubscriber var newSub = new PushSubscriber
{ {
Endpoint = subscription.Endpoint, Endpoint = subscription.Endpoint,
P256DH = subscription.Keys["p256dh"], P256DH = subscription.Keys["p256dh"],
Auth = subscription.Keys["auth"] Auth = subscription.Keys["auth"],
UserId = user.Id
}; };
_context.PushSubscribers.Add(newSub);
_context.PushSubscribers.Add(newSubscriber);
} }
else else
{ {
existing.P256DH = subscription.Keys["p256dh"]; existing.P256DH = subscription.Keys["p256dh"];
existing.Auth = subscription.Keys["auth"]; existing.Auth = subscription.Keys["auth"];
existing.UserId = user.Id;
} }
await _context.SaveChangesAsync();
await _context.SaveChangesAsync();
return Ok(); return Ok();
} }
[HttpPost("subscribe")]
public async Task<IActionResult> Subscribe([FromBody] PushSubscriptionWithOrder dto)
{
var existing = await _context.PushSubscribers
.FirstOrDefaultAsync(s => s.Endpoint == dto.Subscription.Endpoint);
if (existing == null)
{
var newSub = new PushSubscriber
{
Endpoint = dto.Subscription.Endpoint,
P256DH = dto.Subscription.Keys["p256dh"],
Auth = dto.Subscription.Keys["auth"],
PizzaOrderId = dto.PizzaOrderId
};
_context.PushSubscribers.Add(newSub);
}
else
{
existing.P256DH = dto.Subscription.Keys["p256dh"];
existing.Auth = dto.Subscription.Keys["auth"];
existing.PizzaOrderId = dto.PizzaOrderId; // uppdatera kopplingen
}
await _context.SaveChangesAsync();
return Ok();
}
public class PushSubscriptionWithOrder
{
public PushSubscription Subscription { get; set; }
public int PizzaOrderId { get; set; }
}
[HttpGet("vapid-public-key")] [HttpGet("vapid-public-key")]
public IActionResult GetVapidKey([FromServices] IConfiguration config) public IActionResult GetVapidKey([FromServices] IConfiguration config)
{ {
@@ -62,7 +119,12 @@ namespace Aberwyn.Controllers
return BadRequest("Titel och meddelande krävs."); return BadRequest("Titel och meddelande krävs.");
} }
var subscribers = await _context.PushSubscribers.ToListAsync(); var subscribers = await _context.PushSubscribers
.Include(s => s.User)
.ThenInclude(u => u.Preferences)
.Where(s => s.User != null && s.User.Preferences.NotifyPizza)
.ToListAsync();
var payload = $"{{\"title\":\"{message.Title}\",\"body\":\"{message.Body}\"}}"; var payload = $"{{\"title\":\"{message.Title}\",\"body\":\"{message.Body}\"}}";
int successCount = 0; int successCount = 0;
@@ -82,6 +144,24 @@ namespace Aberwyn.Controllers
return Ok($"Skickade notiser till {successCount} användare."); return Ok($"Skickade notiser till {successCount} användare.");
} }
[HttpPost("unsubscribe")]
public async Task<IActionResult> Unsubscribe([FromBody] PushUnsubscribeDto dto)
{
var sub = await _context.PushSubscribers.FirstOrDefaultAsync(s => s.Endpoint == dto.Endpoint);
if (sub != null)
{
_context.PushSubscribers.Remove(sub);
await _context.SaveChangesAsync();
}
return Ok();
}
public class PushUnsubscribeDto
{
public string Endpoint { get; set; }
}
} }
} }

View File

@@ -22,43 +22,5 @@ namespace Aberwyn.Controllers
_context = context; _context = context;
} }
[HttpPost]
public async Task<IActionResult> GetReport([FromBody] BudgetReportRequestDto request)
{
var start = new DateTime(request.StartYear, request.StartMonth, 1);
var end = new DateTime(request.EndYear, request.EndMonth, 1);
var items = await _context.BudgetItems
.Include(i => i.BudgetItemDefinition)
.Include(i => i.BudgetCategory)
.ThenInclude(c => c.BudgetPeriod)
.Where(i =>
i.BudgetCategory.BudgetPeriod.Year * 12 + i.BudgetCategory.BudgetPeriod.Month >= start.Year * 12 + start.Month &&
i.BudgetCategory.BudgetPeriod.Year * 12 + i.BudgetCategory.BudgetPeriod.Month <= end.Year * 12 + end.Month &&
request.DefinitionIds.Contains(i.BudgetItemDefinitionId ?? -1))
.ToListAsync();
var grouped = items
.GroupBy(i => new { i.BudgetCategory.BudgetPeriod.Year, i.BudgetCategory.BudgetPeriod.Month })
.Select(g => new BudgetReportResultDto
{
Year = g.Key.Year,
Month = g.Key.Month,
Definitions = g
.GroupBy(i => new { i.BudgetItemDefinitionId, i.BudgetItemDefinition.Name })
.Select(dg => new DefinitionSumDto
{
DefinitionId = dg.Key.BudgetItemDefinitionId ?? 0,
DefinitionName = dg.Key.Name,
TotalAmount = dg.Sum(x => x.Amount)
}).ToList()
})
.OrderBy(r => r.Year).ThenBy(r => r.Month)
.ToList();
return Ok(grouped);
}
} }
} }

View File

@@ -0,0 +1,78 @@
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
namespace Aberwyn.Controllers
{
[ApiController]
[Route("api/setup")]
public class SetupApiController : ControllerBase
{
[HttpPost("testdb")]
public IActionResult TestDbConnection([FromBody] DbTestRequest request)
{
try
{
var builder = new MySqlConnectionStringBuilder
{
Server = request.Host,
Port = uint.Parse(request.Port),
UserID = request.User,
Password = request.Pass,
Database = "information_schema"
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
conn.Open();
// Kontrollera om databasen redan finns
var checkCmd = new MySqlCommand("SELECT SCHEMA_NAME FROM SCHEMATA WHERE SCHEMA_NAME = @dbName", conn);
checkCmd.Parameters.AddWithValue("@dbName", request.Db);
var exists = checkCmd.ExecuteScalar();
if (exists != null)
{
return Ok(new
{
success = true,
message = "Anslutning OK och databasen finns redan."
});
}
// Testa skapa en temporär databas
var testDbName = $"testcheck_{Guid.NewGuid():N}".Substring(0, 12);
var createCmd = new MySqlCommand($"CREATE DATABASE `{testDbName}`", conn);
createCmd.ExecuteNonQuery();
var dropCmd = new MySqlCommand($"DROP DATABASE `{testDbName}`", conn);
dropCmd.ExecuteNonQuery();
return Ok(new
{
success = true,
message = "Anslutning OK. Databasen finns inte, men CREATE DATABASE är tillåten."
});
}
}
catch (Exception ex)
{
return Ok(new
{
success = false,
message = ex.Message
});
}
}
public class DbTestRequest
{
public string Host { get; set; }
public string Port { get; set; }
public string Db { get; set; }
public string User { get; set; }
public string Pass { get; set; }
}
}
}

View File

@@ -0,0 +1,170 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using MySql.Data.MySqlClient;
using System.Text.Json;
using Aberwyn.Data;
using Aberwyn.Models;
namespace Aberwyn.Controllers
{
[Route("setup")]
public class SetupController : Controller
{
private readonly IWebHostEnvironment _env;
private readonly ILogger<SetupController> _logger;
public SetupController(IWebHostEnvironment env, ILogger<SetupController> logger)
{
_env = env;
_logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
ViewBag.IsSetupMode = true;
base.OnActionExecuting(context);
}
[HttpGet]
public IActionResult Index() => View(new SetupSettings());
[Authorize(Roles = "Admin")]
[HttpPost("reset")]
public IActionResult Reset()
{
var path = Path.Combine(_env.ContentRootPath, "infrastructure", "setup.json");
var resetSettings = new SetupSettings
{
IsConfigured = false,
DbHost = "",
DbPort = 3306,
DbName = "",
DbUser = "",
DbPassword = "",
AdminUsername = "admin",
AdminEmail = "admin@localhost",
AdminPassword = "Admin123!"
};
var json = JsonSerializer.Serialize(resetSettings, new JsonSerializerOptions { WriteIndented = true });
System.IO.File.WriteAllText(path, json);
return RedirectToAction("Index");
}
[HttpPost("")]
public async Task<IActionResult> Setup([FromBody] SetupSettings model)
{
if (!ModelState.IsValid)
{
var allErrors = ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => new { Field = e.Key, Errors = e.Value.Errors.Select(x => x.ErrorMessage) });
return BadRequest(new { error = "Modellen är ogiltig", details = allErrors });
}
try
{
// Bygg connection string säkert
var baseConnBuilder = new MySqlConnectionStringBuilder
{
Server = model.DbHost,
Port = (uint)model.DbPort,
UserID = model.DbUser,
Password = model.DbPassword,
Database = "information_schema"
};
// Kontrollera om databasen redan finns
using (var conn = new MySqlConnection(baseConnBuilder.ConnectionString))
{
conn.Open();
var cmd = new MySqlCommand("SELECT SCHEMA_NAME FROM SCHEMATA WHERE SCHEMA_NAME = @dbName", conn);
cmd.Parameters.AddWithValue("@dbName", model.DbName);
var exists = cmd.ExecuteScalar();
if (exists == null)
{
try
{
var createCmd = new MySqlCommand($"CREATE DATABASE `{model.DbName}`", conn);
createCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
_logger.LogError(ex, "Kunde inte skapa databasen.");
return BadRequest(new { error = "Databasen finns inte och kunde inte skapas.", details = ex.Message });
}
}
}
// Bygg EF-connection
var efConnBuilder = new MySqlConnectionStringBuilder
{
Server = model.DbHost,
Port = (uint)model.DbPort,
UserID = model.DbUser,
Password = model.DbPassword,
Database = model.DbName
};
var tempProvider = SetupService.BuildTemporaryServices(efConnBuilder.ConnectionString);
using var scope = tempProvider.CreateScope();
// Skapa databastabeller
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await db.Database.MigrateAsync();
// Sätt konfig-flagga tidigt
model.IsConfigured = true;
// Spara setup.json
var filePath = Path.Combine(_env.ContentRootPath, "infrastructure", "setup.json");
var json = JsonSerializer.Serialize(model, new JsonSerializerOptions { WriteIndented = true });
System.IO.File.WriteAllText(filePath, json);
// Roller och admin
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roles = { "Admin", "Chef", "Budget" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
await roleManager.CreateAsync(new IdentityRole(role));
}
var existingUser = await userManager.FindByNameAsync(model.AdminUsername);
if (existingUser == null)
{
var adminUser = new ApplicationUser
{
UserName = model.AdminUsername,
Email = model.AdminEmail,
EmailConfirmed = true
};
var result = await userManager.CreateAsync(adminUser, model.AdminPassword);
if (!result.Succeeded)
return BadRequest(new { error = "Kunde inte skapa administratör", details = result.Errors });
await userManager.AddToRoleAsync(adminUser, "Admin");
}
return Ok(new { message = "Installation slutförd!" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Fel vid installation.");
return BadRequest(new { error = "Fel vid installation", details = ex.Message });
}
}
public IActionResult SetupComplete() => View();
}
}

View File

@@ -0,0 +1,99 @@
using Microsoft.AspNetCore.Mvc;
public class TorrentController : Controller
{
private readonly ITorrentService _torrentService;
private readonly ILogger<TorrentController> _logger;
public TorrentController(ITorrentService torrentService, ILogger<TorrentController> logger)
{
_torrentService = torrentService;
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
return View(new TorrentUploadViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload(TorrentUploadViewModel model)
{
if (model.TorrentFile == null || model.TorrentFile.Length == 0)
{
ModelState.AddModelError("TorrentFile", "Vänligen välj en torrent-fil");
return View("Index", model);
}
if (!model.TorrentFile.FileName.EndsWith(".torrent", StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError("TorrentFile", "Endast .torrent filer är tillåtna");
return View("Index", model);
}
if (model.TorrentFile.Length > 10 * 1024 * 1024) // 10MB limit
{
ModelState.AddModelError("TorrentFile", "Filen är för stor (max 10MB)");
return View("Index", model);
}
try
{
// Parsa torrent-filen
var torrentInfo = await _torrentService.ParseTorrentAsync(model.TorrentFile);
if (!string.IsNullOrEmpty(torrentInfo.ErrorMessage))
{
ModelState.AddModelError("", torrentInfo.ErrorMessage);
return View("Index", model);
}
// Försök hämta tracker-statistik
torrentInfo = await _torrentService.FetchTrackerStatsAsync(torrentInfo);
model.TorrentInfo = torrentInfo;
model.ShowResults = true;
return View("Index", model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Fel vid uppladdning av torrent");
ModelState.AddModelError("", "Ett oväntat fel inträffade");
return View("Index", model);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RefreshStats(string infoHash, string scrapeUrl)
{
try
{
var torrentInfo = new TorrentInfo
{
InfoHash = infoHash,
ScrapeUrl = scrapeUrl,
InfoHashBytes = Convert.FromHexString(infoHash.Replace("%", ""))
};
var updatedInfo = await _torrentService.FetchTrackerStatsAsync(torrentInfo);
return Json(new
{
success = updatedInfo.HasTrackerData,
seeders = updatedInfo.Seeders,
leechers = updatedInfo.Leechers,
completed = updatedInfo.Completed,
error = updatedInfo.ErrorMessage
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Fel vid uppdatering av tracker-stats");
return Json(new { success = false, error = "Fel vid uppdatering" });
}
}
}

View File

@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Aberwyn.Models;
using System.Threading.Tasks;
using Aberwyn.Data;
namespace Aberwyn.Controllers
{
[Authorize]
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public UserController(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
{
_userManager = userManager;
_context = context;
}
[HttpGet]
public async Task<IActionResult> Profile()
{
var user = await _userManager.GetUserAsync(User);
var prefs = await _context.UserPreferences.FindAsync(user.Id) ?? new UserPreferences();
var model = new UserProfileViewModel
{
Name = user.UserName,
Email = user.Email,
NotifyPizza = prefs.NotifyPizza,
NotifyMenu = prefs.NotifyMenu,
NotifyBudget = prefs.NotifyBudget
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> SaveProfile(UserProfileViewModel model)
{
var user = await _userManager.GetUserAsync(User);
var prefs = await _context.UserPreferences.FindAsync(user.Id);
if (prefs == null)
{
prefs = new UserPreferences { UserId = user.Id };
_context.UserPreferences.Add(prefs);
}
prefs.NotifyPizza = model.NotifyPizza;
prefs.NotifyMenu = model.NotifyMenu;
prefs.NotifyBudget = model.NotifyBudget;
await _context.SaveChangesAsync();
return RedirectToAction("Profile");
}
}
}

View File

@@ -16,7 +16,20 @@ namespace Aberwyn.Data
base.OnModelCreating(builder); base.OnModelCreating(builder);
builder.Entity<WeeklyMenu>().ToTable("WeeklyMenu"); builder.Entity<WeeklyMenu>().ToTable("WeeklyMenu");
builder.Entity<MealCategory>().HasData(
new MealCategory
{
Id = 1,
Name = "Pizza",
Slug = "pizza",
Icon = "🍕",
Color = "#f97316",
IsActive = true,
DisplayOrder = 1
}
);
} }
public DbSet<BudgetPeriod> BudgetPeriods { get; set; } public DbSet<BudgetPeriod> BudgetPeriods { get; set; }
@@ -31,6 +44,15 @@ namespace Aberwyn.Data
public DbSet<Meal> Meals { get; set; } public DbSet<Meal> Meals { get; set; }
public DbSet<WeeklyMenu> WeeklyMenus { get; set; } public DbSet<WeeklyMenu> WeeklyMenus { get; set; }
public DbSet<Ingredient> Ingredients { get; set; } public DbSet<Ingredient> Ingredients { get; set; }
public DbSet<UserPreferences> UserPreferences { get; set; }
public DbSet<StoredPushSubscription> PushSubscriptions { get; set; }
public DbSet<MealCategory> MealCategories { get; set; }
public DbSet<RecipeLabEntry> RecipeLabEntries { get; set; }
public DbSet<RecipeLabVersion> RecipeLabVersions { get; set; }
public DbSet<LabIngredient> LabIngredients { get; set; }
public DbSet<LabVersionIngredient> LabVersionIngredients { get; set; }
public DbSet<MealRating> MealRatings { get; set; }
} }
} }

View File

@@ -1,8 +1,11 @@
using Microsoft.EntityFrameworkCore; using Aberwyn.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System; using System;
using System.IO; using System.IO;
using System.Text.Json;
using static Aberwyn.Data.SetupService;
namespace Aberwyn.Data namespace Aberwyn.Data
{ {
@@ -10,47 +13,51 @@ namespace Aberwyn.Data
{ {
public ApplicationDbContext CreateDbContext(string[] args) public ApplicationDbContext CreateDbContext(string[] args)
{ {
var basePath = Directory.GetCurrentDirectory(); var setup = LoadSetup();
var config = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Development.json", optional: true)
.AddEnvironmentVariables()
.Build();
var connectionString = config.GetConnectionString("DefaultConnection"); var csBuilder = new MySqlConnector.MySqlConnectionStringBuilder
File.WriteAllText("connection-log.txt", $"Connection string: {connectionString}");
Console.WriteLine($"Anslutningssträng: {connectionString}");
if (string.IsNullOrEmpty(connectionString))
{ {
throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); Server = setup.DbHost,
} Port = (uint)setup.DbPort,
Database = setup.DbName,
UserID = setup.DbUser,
Password = setup.DbPassword,
AllowUserVariables = true
};
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>(); var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseMySql( optionsBuilder.UseMySql(csBuilder.ConnectionString, new MySqlServerVersion(new Version(8, 0, 36)));
connectionString,
new MySqlServerVersion(new Version(8, 0, 36)));
return new ApplicationDbContext(optionsBuilder.Options); return new ApplicationDbContext(optionsBuilder.Options);
} }
public static ApplicationDbContext CreateWithConfig(IConfiguration config, IHostEnvironment env, bool useProdDb = false)
public static ApplicationDbContext CreateWithConfig(IHostEnvironment env, bool useProdDb = false)
{ {
var connectionString = useProdDb var setup = SetupLoader.Load(env);
? config.GetConnectionString("ProdConnection") // <--- FIX HÄR var connStr = SetupLoader.GetConnectionString(setup);
: config.GetConnectionString("DefaultConnection");
if (string.IsNullOrWhiteSpace(connectionString))
throw new InvalidOperationException("Connection string saknas.");
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>(); var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 36))); optionsBuilder.UseMySql(connStr, new MySqlServerVersion(new Version(8, 0, 36)));
return new ApplicationDbContext(optionsBuilder.Options); return new ApplicationDbContext(optionsBuilder.Options);
} }
private static SetupSettings LoadSetup()
{
var basePath = Directory.GetCurrentDirectory();
var setupPath = Path.Combine(basePath, "infrastructure", "setup.json");
if (!File.Exists(setupPath))
throw new FileNotFoundException("setup.json saknas i infrastructure-mappen.");
var json = File.ReadAllText(setupPath);
var setup = JsonSerializer.Deserialize<SetupSettings>(json);
if (setup == null || !setup.IsConfigured)
throw new InvalidOperationException("setup.json är inte korrekt konfigurerad.");
return setup;
}
} }
} }

View File

@@ -1,148 +0,0 @@
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using Aberwyn.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; // Add this namespace
namespace Aberwyn.Data
{
public class BudgetService
{
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env; // Add this field
public BudgetService(IConfiguration configuration, IHostEnvironment env) // Update constructor
{
_configuration = configuration;
_env = env; // Initialize the environment field
}
public MySqlConnection GetConnection()
{
var connectionString = _env.IsDevelopment() // Use the injected environment variable
? _configuration.GetConnectionString("DefaultConnection")
: _configuration.GetConnectionString("ProductionConnection");
return new MySqlConnection(connectionString);
}
public bool UpdateBudgetItem(BudgetItem item)
{
using (var connection = GetConnection())
{
connection.Open();
string query = @"
UPDATE tblBudgetItems
SET Name = @name, Amount = @amount
WHERE idtblBudgetItems = @id";
using (var cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@name", item.Name);
cmd.Parameters.AddWithValue("@amount", item.Amount);
cmd.Parameters.AddWithValue("@id", item.ID);
return cmd.ExecuteNonQuery() > 0; // Returns true if one or more rows are updated
}
}
}
public List<BudgetItem> GetBudgetItems(int month, int year)
{
var budgetItems = new List<BudgetItem>();
using (var connection = GetConnection())
{
connection.Open();
string query = @"
SELECT
b.idtblBudgetItems AS id,
b.Name AS item_name,
b.Amount AS amount,
c1.Name AS category,
b.Month,
b.Year,
b.Description AS description
FROM tblBudgetItems b
LEFT JOIN tblCategories c1 ON b.Category = c1.idtblCategories
WHERE b.Month = @month AND b.Year = @year";
using (var cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@month", month);
cmd.Parameters.AddWithValue("@year", year);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
budgetItems.Add(new BudgetItem
{
ID = reader.GetInt32("id"),
Name = reader.GetString("item_name"), // Updated alias
Amount = reader.GetDecimal("amount"),
Category = reader.GetString("category"),
Month = reader.GetInt32("Month"),
Year = reader.GetInt32("Year"),
Description = reader.IsDBNull(reader.GetOrdinal("description"))
? null
: reader.GetString("description")
});
}
}
}
}
return budgetItems;
}
public bool AddBudgetItem(BudgetItem item)
{
using (var connection = GetConnection())
{
connection.Open();
string query = @"
INSERT INTO tblBudgetItems (Name, Amount, Category, Month, Year)
VALUES (@name, @amount, @category, @month, @year)";
using (var cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("@name", item.Name);
cmd.Parameters.AddWithValue("@amount", item.Amount);
cmd.Parameters.AddWithValue("@category", item.Category);
cmd.Parameters.AddWithValue("@month", item.Month);
cmd.Parameters.AddWithValue("@year", item.Year);
return cmd.ExecuteNonQuery() > 0; // Returns true if a row was inserted
}
}
}*/
// New method to fetch all categories
public List<string> GetCategories()
{
var categories = new List<string>();
using (var connection = GetConnection())
{
connection.Open();
string query = "SELECT Name FROM tblCategories"; // Adjust based on your table structure
using (var cmd = new MySqlCommand(query, connection))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
categories.Add(reader.GetString("Name"));
}
}
}
}
return categories;
}
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Aberwyn.Models; using Aberwyn.Models;
@@ -6,10 +7,16 @@ namespace Aberwyn.Data
{ {
public static class IdentityDataInitializer public static class IdentityDataInitializer
{ {
public static async Task SeedData(IServiceProvider serviceProvider) public static async Task<IdentityResult> SeedData(IServiceProvider serviceProvider, SetupSettings? setup = null)
{ {
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var config = serviceProvider.GetService<IConfiguration>();
if (setup == null && config != null)
{
setup = config.GetSection("SetupSettings").Get<SetupSettings>() ?? new SetupSettings();
}
string[] roles = { "Admin", "Chef", "Budget" }; string[] roles = { "Admin", "Chef", "Budget" };
@@ -19,26 +26,38 @@ namespace Aberwyn.Data
await roleManager.CreateAsync(new IdentityRole(role)); await roleManager.CreateAsync(new IdentityRole(role));
} }
string adminUsername = "admin"; var existingUser = await userManager.FindByEmailAsync(setup.AdminEmail);
string adminEmail = "admin@localhost"; if (existingUser == null)
string password = "Admin123!";
if (await userManager.FindByEmailAsync(adminEmail) == null)
{ {
var user = new ApplicationUser var user = new ApplicationUser
{ {
UserName = adminUsername, UserName = setup.AdminUsername,
Email = adminEmail, Email = setup.AdminEmail,
EmailConfirmed = true EmailConfirmed = true
}; };
var result = await userManager.CreateAsync(user, password); var result = await userManager.CreateAsync(user, setup.AdminPassword);
if (result.Succeeded)
await userManager.AddToRoleAsync(user, "Admin");
return result;
}
else
{
var token = await userManager.GeneratePasswordResetTokenAsync(existingUser);
var result = await userManager.ResetPasswordAsync(existingUser, token, setup.AdminPassword);
if (result.Succeeded) if (result.Succeeded)
{ {
await userManager.AddToRoleAsync(user, "Admin"); var rolesForUser = await userManager.GetRolesAsync(existingUser);
if (!rolesForUser.Contains("Admin"))
await userManager.AddToRoleAsync(existingUser, "Admin");
} }
return result;
} }
} }
} }
} }

View File

@@ -1,8 +1,11 @@
// Nya versionen av MenuService med Entity Framework // Nya versionen av MenuService med Entity Framework
using Aberwyn.Models; using Aberwyn.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Webp;
using SixLabors.ImageSharp.Processing;
using System.Globalization; using System.Globalization;
using static Aberwyn.Data.SetupService;
namespace Aberwyn.Data namespace Aberwyn.Data
{ {
@@ -16,20 +19,47 @@ public class MenuService
_context = context; _context = context;
} }
// Detta är en alternativ konstruktör används manuellt vid t.ex. import public static MenuService CreateWithSetup(IHostEnvironment env)
public static MenuService CreateWithConfig(IConfiguration config, IHostEnvironment env, bool useProdDb = false) {
{ var setup = SetupLoader.Load(env);
var builder = new DbContextOptionsBuilder<ApplicationDbContext>(); var connStr = SetupLoader.GetConnectionString(setup);
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
var context = new ApplicationDbContext(builder.Options);
return new MenuService(context);
}
public List<WeeklyMenuDto> GetWeeklyMenuDto(int weekNumber, int year)
{
var query = from wm in _context.WeeklyMenus
where wm.WeekNumber == weekNumber && wm.Year == year
join mDinner in _context.Meals on wm.DinnerMealId equals mDinner.Id into dinnerJoin
from mDinner in dinnerJoin.DefaultIfEmpty()
join mLunch in _context.Meals on wm.LunchMealId equals mLunch.Id into lunchJoin
from mLunch in lunchJoin.DefaultIfEmpty()
join mBreakfast in _context.Meals on wm.BreakfastMealId equals mBreakfast.Id into breakfastJoin
from mBreakfast in breakfastJoin.DefaultIfEmpty()
select new WeeklyMenuDto
{
Id = wm.Id,
DayOfWeek = wm.DayOfWeek,
WeekNumber = wm.WeekNumber,
Year = wm.Year,
BreakfastMealId = wm.BreakfastMealId,
LunchMealId = wm.LunchMealId,
DinnerMealId = wm.DinnerMealId,
BreakfastMealName = mBreakfast.Name,
LunchMealName = mLunch.Name,
DinnerMealName = mDinner.Name,
DinnerMealThumbnail = mDinner.ThumbnailData
};
return query.ToList();
}
var connStr = useProdDb
? config.GetConnectionString("ProdConnection")
: config.GetConnectionString("DefaultConnection");
builder.UseMySql(connStr, ServerVersion.AutoDetect(connStr));
var context = new ApplicationDbContext(builder.Options);
return new MenuService(context);
}
public void UpdateWeeklyMenu(MenuViewModel model) public void UpdateWeeklyMenu(MenuViewModel model)
{ {
var existing = _context.WeeklyMenus var existing = _context.WeeklyMenus
@@ -47,7 +77,30 @@ public class MenuService
} }
public void SaveMeal2(Meal meal)
{
if (string.IsNullOrWhiteSpace(meal?.Name)) return;
meal.Name = meal.Name.Trim();
meal.CreatedAt = meal.CreatedAt == default ? DateTime.Now : meal.CreatedAt;
var existing = _context.Meals
.AsNoTracking()
.FirstOrDefault(m => m.Id == meal.Id);
if (existing == null)
{
// Nytt objekt försök behålla ID:t från prod
_context.Entry(meal).State = EntityState.Added;
}
else
{
// Befintlig uppdatera
_context.Meals.Update(meal);
}
_context.SaveChanges();
}
public void SaveMeal(Meal meal) public void SaveMeal(Meal meal)
{ {
@@ -57,15 +110,90 @@ public class MenuService
meal.CreatedAt = meal.CreatedAt == default ? DateTime.Now : meal.CreatedAt; meal.CreatedAt = meal.CreatedAt == default ? DateTime.Now : meal.CreatedAt;
if (meal.Id == 0) if (meal.Id == 0)
{
// Ny måltid
_context.Meals.Add(meal); _context.Meals.Add(meal);
}
else else
_context.Meals.Update(meal); {
// Uppdatera existerande utan tracking-krockar
var existing = _context.Meals
.Include(m => m.Ingredients)
.FirstOrDefault(m => m.Id == meal.Id);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(meal);
// OBS: Ingredienser hanteras separat
}
}
_context.SaveChanges(); _context.SaveChanges();
} }
public List<WeeklyMenu> GetAllWeeklyMenus()
public int GenerateMissingThumbnails()
{ {
var updatedCount = 0;
var meals = _context.Meals
.Where(m => m.ImageData != null && m.ThumbnailData == null)
.ToList();
foreach (var meal in meals)
{
using var ms = new MemoryStream(meal.ImageData);
using var image = Image.Load(ms);
image.Mutate(x => x.Resize(new ResizeOptions
{
Mode = ResizeMode.Max,
Size = new Size(300, 300)
}));
using var outStream = new MemoryStream();
var encoder = new WebpEncoder
{
Quality = 75
};
image.Save(outStream, encoder);
meal.ThumbnailData = outStream.ToArray();
updatedCount++;
}
_context.SaveChanges();
return updatedCount;
}
public List<Meal> GetMealsSlim(bool includeThumbnail = false)
{
if (includeThumbnail)
{
return _context.Meals
.Select(m => new Meal
{
Id = m.Id,
Name = m.Name,
Description = m.Description,
ThumbnailData = m.ThumbnailData
})
.ToList();
}
else
{
return _context.Meals
.Select(m => new Meal
{
Id = m.Id,
Name = m.Name,
Description = m.Description
})
.ToList();
}
}
public List<WeeklyMenu> GetAllWeeklyMenus()
{
var menus = _context.WeeklyMenus.ToList(); var menus = _context.WeeklyMenus.ToList();
var allMeals = _context.Meals.ToDictionary(m => m.Id, m => m.Name); var allMeals = _context.Meals.ToDictionary(m => m.Id, m => m.Name);
@@ -100,10 +228,17 @@ public List<WeeklyMenu> GetAllWeeklyMenus()
{ {
var existing = _context.Ingredients.Where(i => i.MealId == mealId); var existing = _context.Ingredients.Where(i => i.MealId == mealId);
_context.Ingredients.RemoveRange(existing); _context.Ingredients.RemoveRange(existing);
foreach (var ing in ingredients)
{
ing.MealId = mealId;
}
_context.Ingredients.AddRange(ingredients); _context.Ingredients.AddRange(ingredients);
_context.SaveChanges(); _context.SaveChanges();
} }
public List<Meal> GetMeals() public List<Meal> GetMeals()
{ {
return _context.Meals.ToList(); return _context.Meals.ToList();
@@ -112,10 +247,12 @@ public List<WeeklyMenu> GetAllWeeklyMenus()
public List<Meal> GetMealsDetailed() public List<Meal> GetMealsDetailed()
{ {
return _context.Meals return _context.Meals
.Include(m => m.Ingredients) // 🧠 detta behövs!
.OrderByDescending(m => m.CreatedAt) .OrderByDescending(m => m.CreatedAt)
.ToList(); .ToList();
} }
public Meal GetMealById(int id) public Meal GetMealById(int id)
{ {
var meal = _context.Meals var meal = _context.Meals
@@ -141,6 +278,8 @@ public List<WeeklyMenu> GetAllWeeklyMenus()
public void SaveOrUpdateMealWithIngredients(Meal meal) public void SaveOrUpdateMealWithIngredients(Meal meal)
{ {
var isNew = meal.Id == 0;
SaveMeal(meal); SaveMeal(meal);
if (meal.Ingredients != null && meal.Ingredients.Count > 0) if (meal.Ingredients != null && meal.Ingredients.Count > 0)
@@ -149,41 +288,123 @@ public List<WeeklyMenu> GetAllWeeklyMenus()
} }
} }
public List<Meal> GetMealsByCategory(string category) public List<Meal> GetMealsByCategory(string category)
{ {
return _context.Meals return _context.Meals
.Where(m => m.Category == category) //.Where(m => m.Category == category)
.Include(m => m.Ingredients) .Include(m => m.Ingredients)
.OrderBy(m => m.Name) .OrderBy(m => m.Name)
.ToList(); .ToList();
} }
public List<WeeklyMenu> GetWeeklyMenu(int weekNumber, int year) public List<WeeklyMenu> GetWeeklyMenu(int weekNumber, int year)
{ {
var menus = _context.WeeklyMenus var menus = _context.WeeklyMenus
.Where(m => m.WeekNumber == weekNumber && m.Year == year) .Where(m => m.WeekNumber == weekNumber && m.Year == year)
.ToList(); .ToList();
var mealIds = menus
.SelectMany(w => new int?[] { w.BreakfastMealId, w.LunchMealId, w.DinnerMealId })
.Where(id => id.HasValue)
.Select(id => id.Value)
.Distinct()
.ToList();
var allMeals = _context.Meals
.Where(m => mealIds.Contains(m.Id))
.Select(m => new {
m.Id,
m.Name,
m.ThumbnailData // Vi tar med detta även om det bara används för middag
})
.ToList()
.ToDictionary(m => m.Id, m => m);
var allMeals = _context.Meals.ToDictionary(m => m.Id, m => m.Name);
foreach (var wm in menus) foreach (var wm in menus)
{ {
wm.BreakfastMealName = wm.BreakfastMealId.HasValue && allMeals.TryGetValue(wm.BreakfastMealId.Value, out var breakfast) if (wm.BreakfastMealId.HasValue && allMeals.TryGetValue(wm.BreakfastMealId.Value, out var breakfast))
? breakfast wm.BreakfastMealName = breakfast.Name;
: null;
wm.LunchMealName = wm.LunchMealId.HasValue && allMeals.TryGetValue(wm.LunchMealId.Value, out var lunch) if (wm.LunchMealId.HasValue && allMeals.TryGetValue(wm.LunchMealId.Value, out var lunch))
? lunch wm.LunchMealName = lunch.Name;
: null;
wm.DinnerMealName = wm.DinnerMealId.HasValue && allMeals.TryGetValue(wm.DinnerMealId.Value, out var dinner) if (wm.DinnerMealId.HasValue && allMeals.TryGetValue(wm.DinnerMealId.Value, out var dinner))
? dinner {
: null; wm.DinnerMealName = dinner.Name;
}
} }
return menus;
return menus;
}
public WeeklyMenu? GetMenuForDate(DateTime date)
{
int week = ISOWeek.GetWeekOfYear(date);
int year = date.Year;
int dayOfWeek = (int)date.DayOfWeek;
if (dayOfWeek == 0) dayOfWeek = 7;
var menu = _context.WeeklyMenus
.FirstOrDefault(w => w.WeekNumber == week && w.Year == year && w.DayOfWeek == dayOfWeek);
if (menu != null)
{
var mealIds = new[] { menu.BreakfastMealId, menu.LunchMealId, menu.DinnerMealId }
.Where(id => id.HasValue)
.Select(id => id.Value)
.Distinct()
.ToList();
var allMeals = _context.Meals
.Where(m => mealIds.Contains(m.Id))
.ToDictionary(m => m.Id);
if (menu.BreakfastMealId is int bId && allMeals.TryGetValue(bId, out var breakfast))
{
menu.BreakfastMealName = breakfast.Name;
menu.BreakfastThumbnail = breakfast.ThumbnailData;
}
if (menu.LunchMealId is int lId && allMeals.TryGetValue(lId, out var lunch))
{
menu.LunchMealName = lunch.Name;
menu.LunchThumbnail = lunch.ThumbnailData;
}
if (menu.DinnerMealId is int dId && allMeals.TryGetValue(dId, out var dinner))
{
menu.DinnerMealName = dinner.Name;
menu.DinnerThumbnail = dinner.ThumbnailData;
}
}
return menu;
}
public List<Meal> GetMealsByCategoryName(string categoryName, string? searchTerm = null, bool onlyAvailable = false)
{
var query = _context.Meals
.Include(m => m.Category)
.Include(m => m.Ingredients)
.Where(m => m.Category != null && m.Category.Name == categoryName);
if (onlyAvailable)
query = query.Where(m => m.IsAvailable);
if (!string.IsNullOrWhiteSpace(searchTerm))
{
string lowered = searchTerm.Trim().ToLower();
query = query.Where(m => m.Name.ToLower().Contains(lowered));
}
return query
.OrderBy(m => m.Name)
.ToList();
} }
public List<WeeklyMenu> GetMenuEntriesByDateRange(DateTime startDate, DateTime endDate) public List<WeeklyMenu> GetMenuEntriesByDateRange(DateTime startDate, DateTime endDate)
{ {
var results = new List<WeeklyMenu>(); var results = new List<WeeklyMenu>();
@@ -214,5 +435,126 @@ public List<WeeklyMenu> GetAllWeeklyMenus()
} }
return results; return results;
} }
public List<MealCategory> GetMealCategories()
{
return _context.MealCategories.OrderBy(c => c.DisplayOrder).ToList();
}
public int GetMealCountForCategory(int categoryId)
{
return _context.Meals.Count(m => m.MealCategoryId == categoryId);
}
public void SaveOrUpdateCategory(MealCategory cat)
{
if (cat.Id == 0)
{
_context.MealCategories.Add(cat);
}
else
{
var existing = _context.MealCategories.Find(cat.Id);
if (existing != null)
{
existing.Name = cat.Name;
existing.Slug = cat.Slug;
existing.Description = cat.Description;
existing.Icon = cat.Icon;
existing.Color = cat.Color;
existing.IsActive = cat.IsActive;
existing.DisplayOrder = cat.DisplayOrder;
}
}
_context.SaveChanges();
}
#region Lab
public void DeleteCategory(int id)
{
var cat = _context.MealCategories.Find(id);
if (cat != null)
{
_context.MealCategories.Remove(cat);
_context.SaveChanges();
}
}
public RecipeLabEntry? GetRecipeLabEntryById(int id)
{
return _context.RecipeLabEntries
.Include(e => e.Versions)
.FirstOrDefault(e => e.Id == id);
}
public void AddVersionToLabEntry(RecipeLabVersion version)
{
_context.RecipeLabVersions.Add(version);
_context.SaveChanges();
}
public void AddLabEntry(RecipeLabEntry entry)
{
_context.RecipeLabEntries.Add(entry);
_context.SaveChanges();
}
public void SaveLabVersionWithIngredients(RecipeLabVersion version, List<LabVersionIngredient> ingredients)
{
_context.RecipeLabVersions.Add(version);
_context.SaveChanges(); // så vi får ett ID
foreach (var ing in ingredients)
{
ing.RecipeLabVersionId = version.Id;
}
_context.LabVersionIngredients.AddRange(ingredients);
_context.SaveChanges();
}
// Lägg till dessa metoder i din MenuService klass
public void UpdateLabEntry(RecipeLabEntry entry)
{
var existing = _context.RecipeLabEntries.Find(entry.Id);
if (existing != null)
{
existing.Title = entry.Title;
existing.Inspiration = entry.Inspiration;
existing.Notes = entry.Notes;
existing.Tags = entry.Tags;
_context.SaveChanges();
}
}
public RecipeLabEntry GetRecipeLabEntryWithIngredients(int id)
{
return _context.RecipeLabEntries
.Include(e => e.Versions)
.Include(e => e.Ingredients)
.FirstOrDefault(e => e.Id == id);
}
public void SaveIngredientsForLabEntry(int labEntryId, List<LabIngredient> ingredients)
{
var existing = _context.LabIngredients
.Where(i => i.RecipeLabEntryId == labEntryId)
.ToList();
_context.LabIngredients.RemoveRange(existing);
foreach (var ing in ingredients)
ing.RecipeLabEntryId = labEntryId;
_context.LabIngredients.AddRange(ingredients);
_context.SaveChanges();
}
public List<RecipeLabVersion> GetLabVersionsForEntry(int entryId)
{
return _context.RecipeLabVersions
.Where(v => v.RecipeLabEntryId == entryId)
.Include(v => v.Ingredients)
.OrderByDescending(v => v.CreatedAt)
.ToList();
}
#endregion
} }
} }

View File

@@ -0,0 +1,76 @@
using Aberwyn.Data;
using Microsoft.EntityFrameworkCore;
using WebPush;
namespace Aberwyn.Services
{
public class PizzaNotificationService
{
private readonly ApplicationDbContext _context;
private readonly PushNotificationService _push;
public PizzaNotificationService(ApplicationDbContext context, PushNotificationService push)
{
Console.WriteLine("🍕 PizzaNotificationService constructor körs!");
_context = context;
_push = push;
}
public async Task<int> NotifyPizzaSubscribersAsync(string pizzaName = null, string userName = null)
{
var title = "Ny pizzabeställning 🍕";
var body = "En pizza har precis beställts!";
if (!string.IsNullOrWhiteSpace(pizzaName))
body = $"Pizzan '{pizzaName}' har precis beställts!";
if (!string.IsNullOrWhiteSpace(userName))
body += $" (av {userName})";
var payload = $@"{{""title"":""{title}"",""body"":""{body}""}}";
var subscribers = await _context.PushSubscribers
.Include(s => s.User)
.ThenInclude(u => u.Preferences)
.Where(s => s.User != null &&
s.User.Preferences != null &&
s.User.Preferences.NotifyPizza &&
!string.IsNullOrEmpty(s.Endpoint) &&
s.Endpoint.StartsWith("https://"))
.ToListAsync();
var allSubscribers = await _context.PushSubscribers
.Include(s => s.User)
.ThenInclude(u => u.Preferences)
.ToListAsync();
foreach (var s in allSubscribers)
{
Console.WriteLine($"🔍 Sub: {s.Endpoint}, User: {s.User?.UserName}, NotifyPizza: {s.User?.Preferences?.NotifyPizza}");
}
int successCount = 0;
foreach (var sub in subscribers)
{
try
{
_push.SendNotification(sub.Endpoint, sub.P256DH, sub.Auth, payload);
successCount++;
}
catch (WebPushException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Gone || ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
Console.WriteLine($"🗑️ Ogiltig prenumeration tas bort: {sub.Endpoint}");
_context.PushSubscribers.Remove(sub);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine($"❌ Misslyckades att skicka till {sub.Endpoint}: {ex.Message}");
}
}
return successCount;
}
}
}

View File

@@ -0,0 +1,73 @@
using Aberwyn.Models;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System.IO;
using System.Text.Json;
using Microsoft.Extensions.Hosting;
namespace Aberwyn.Data
{
// SetupService.cs
public class SetupService
{
private readonly IWebHostEnvironment _env;
private readonly string _filePath;
public SetupService(IWebHostEnvironment env)
{
_env = env;
_filePath = Path.Combine(_env.ContentRootPath, "infrastructure", "setup.json");
}
public SetupSettings GetSetup()
{
if (!File.Exists(_filePath))
return new SetupSettings { IsConfigured = false };
var json = File.ReadAllText(_filePath);
return JsonSerializer.Deserialize<SetupSettings>(json) ?? new SetupSettings { IsConfigured = false };
}
internal static IServiceProvider BuildTemporaryServices(string connectionString)
{
var services = new ServiceCollection();
// Konfigurera EF + Identity
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Lägg till en tom konfiguration för att undvika null
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
// Valfritt: Lägg till loggning om något kräver det
services.AddLogging();
return services.BuildServiceProvider();
}
public static class SetupLoader
{
public static SetupSettings Load(IHostEnvironment env)
{
var path = Path.Combine(env.ContentRootPath, "infrastructure", "setup.json");
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<SetupSettings>(json)!;
}
public static string GetConnectionString(SetupSettings setup)
{
return $"server={setup.DbHost};port={setup.DbPort};database={setup.DbName};user={setup.DbUser};password={setup.DbPassword}";
}
}
}
}

View File

@@ -0,0 +1,159 @@
using BencodeNET.Parsing;
using BencodeNET.Torrents;
using BencodeNET.Objects;
using System.Text;
public interface ITorrentService
{
Task<TorrentInfo> ParseTorrentAsync(IFormFile file);
Task<TorrentInfo> FetchTrackerStatsAsync(TorrentInfo info);
}
public class TorrentService : ITorrentService
{
private readonly HttpClient _httpClient;
private readonly ILogger<TorrentService> _logger;
// Kända trackers och deras egenskaper
private readonly Dictionary<string, TrackerInfo> _knownTrackers = new()
{
["hdts-announce.ru"] = new TrackerInfo
{
Name = "HD-Torrents",
SupportsScraping = true, // Ändrat till true
RequiresAuth = false, // Kan fungera utan auth för scraping
IsPrivate = true,
Notes = "Privat tracker, scraping kan fungera utan inloggning"
}
};
public TorrentService(HttpClient httpClient, ILogger<TorrentService> logger)
{
_httpClient = httpClient;
_logger = logger;
_httpClient.Timeout = TimeSpan.FromSeconds(10);
}
public async Task<TorrentInfo> ParseTorrentAsync(IFormFile file)
{
try
{
using var stream = new MemoryStream();
await file.CopyToAsync(stream);
stream.Position = 0;
var parser = new TorrentParser();
var torrent = parser.Parse(stream);
var infoHash = torrent.GetInfoHashBytes();
var announceUrl = torrent.Trackers?.FirstOrDefault()?.FirstOrDefault()?.ToString();
return new TorrentInfo
{
FileName = torrent.DisplayName ?? file.FileName,
AnnounceUrl = announceUrl,
ScrapeUrl = ConvertAnnounceToScrape(announceUrl),
InfoHash = UrlEncodeInfoHash(infoHash),
InfoHashBytes = infoHash,
Size = torrent.TotalSize
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Fel vid parsing av torrent-fil");
return new TorrentInfo
{
FileName = file.FileName,
ErrorMessage = $"Kunde inte parsa torrent-filen: {ex.Message}"
};
}
}
public async Task<TorrentInfo> FetchTrackerStatsAsync(TorrentInfo info)
{
if (string.IsNullOrWhiteSpace(info.ScrapeUrl))
{
info.ErrorMessage = "Ingen scrape URL tillgänglig";
return info;
}
var url = $"{info.ScrapeUrl}?info_hash={info.InfoHash}";
_logger.LogInformation("Scraping tracker: {Url}", url);
try
{
var data = await _httpClient.GetByteArrayAsync(url);
var parser = new BencodeParser();
var bdict = parser.Parse<BDictionary>(data);
if (bdict.TryGetValue("files", out var filesValue) && filesValue is BDictionary files)
{
if (TryGetStatsFromFiles(files, info.InfoHash, info) ||
TryGetStatsFromFiles(files, Encoding.UTF8.GetString(info.InfoHashBytes), info))
{
info.HasTrackerData = true;
return info;
}
info.ErrorMessage = "Info hash hittades inte i tracker-svaret";
}
else
{
info.ErrorMessage = "Inget 'files' objekt i tracker-svaret";
}
}
catch (HttpRequestException ex)
{
info.ErrorMessage = $"HTTP fel: {ex.Message}";
_logger.LogWarning(ex, "HTTP fel vid tracker scraping");
}
catch (TaskCanceledException)
{
info.ErrorMessage = "Timeout vid anslutning till tracker";
_logger.LogWarning("Timeout vid tracker scraping");
}
catch (Exception ex)
{
info.ErrorMessage = $"Fel vid parsing: {ex.Message}";
_logger.LogError(ex, "Fel vid tracker scraping");
}
return info;
}
private bool TryGetStatsFromFiles(BDictionary files, string hashKey, TorrentInfo info)
{
if (files.TryGetValue(hashKey, out var hashEntry) && hashEntry is BDictionary stats)
{
info.Seeders = stats.TryGetInt("complete") ?? 0;
info.Leechers = stats.TryGetInt("incomplete") ?? 0;
info.Completed = stats.TryGetInt("downloaded") ?? 0;
return true;
}
return false;
}
private string ConvertAnnounceToScrape(string announceUrl)
{
if (string.IsNullOrEmpty(announceUrl))
return null;
return announceUrl.Replace("/announce", "/scrape");
}
private string UrlEncodeInfoHash(byte[] infoHash)
{
var sb = new StringBuilder();
foreach (byte b in infoHash)
{
sb.AppendFormat("%{0:x2}", b);
}
return sb.ToString();
}
}
public static class BDictionaryExtensions
{
public static int? TryGetInt(this BDictionary dict, string key)
{
return dict.TryGetValue(key, out var value) && value is BNumber num ? (int?)num.Value : null;
}
}

View File

@@ -1,9 +1,12 @@
# Basimage för runtime
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
# Installera svenska språkinställningar
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y locales && \ apt-get install -y locales && \
locale-gen sv_SE.UTF-8 locale-gen sv_SE.UTF-8
# Ställ in svenska som standard
ENV LANG=sv_SE.UTF-8 ENV LANG=sv_SE.UTF-8
ENV LANGUAGE=sv_SE:sv ENV LANGUAGE=sv_SE:sv
ENV LC_ALL=sv_SE.UTF-8 ENV LC_ALL=sv_SE.UTF-8
@@ -13,17 +16,30 @@ WORKDIR /app
EXPOSE 80 EXPOSE 80
EXPOSE 443 EXPOSE 443
# Byggimage med SDK
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src WORKDIR /src
COPY ["Aberwyn.csproj", "."]
# Kopiera endast .csproj först för att kunna cacha restore
COPY ["Aberwyn/Aberwyn.csproj", "Aberwyn/"]
WORKDIR /src/Aberwyn
# Restore beroenden
RUN dotnet restore "Aberwyn.csproj" RUN dotnet restore "Aberwyn.csproj"
COPY . .
RUN dotnet build "Aberwyn.csproj" -c Release -o /app/build
# Kopiera övrig kod
COPY Aberwyn/. .
# Bygg utan att köra restore igen
RUN dotnet build "Aberwyn.csproj" -c Release -o /app/build --no-restore
# Publicera utan att köra restore eller build igen
FROM build AS publish FROM build AS publish
RUN dotnet publish "Aberwyn.csproj" -c Release -o /app/publish RUN dotnet publish "Aberwyn.csproj" -c Release -o /app/publish --no-restore
# Slutgiltig image baserad på runtime
FROM base AS final FROM base AS final
WORKDIR /app WORKDIR /app
COPY --from=publish /app/publish . COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Aberwyn.dll"] ENTRYPOINT ["dotnet", "Aberwyn.dll"]

View File

@@ -2,22 +2,22 @@ version: '3.8'
services: services:
aberwyn-app: aberwyn-app:
image: aberwyn:latest image: 192.168.1.9:3000/tai/aberwyn/aberwyn:latest
build: container_name: aberwyn-app-prod
context: ../
dockerfile: Dockerfile
ports: ports:
- "8080:80" - "8080:80"
environment: environment:
ASPNETCORE_ENVIRONMENT: Production ASPNETCORE_ENVIRONMENT: Production
DB_HOST: aberwyn-mysql-prod
DB_NAME: aberwyn_prod DB_NAME: aberwyn_prod
DB_USER: aberwyn
DB_PASSWORD: 3edc4RFV
depends_on: depends_on:
- mysql - aberwyn-mysql-prod
networks: networks:
- aberwyn-net - aberwyn-net
mysql: aberwyn-mysql-prod:
image: mysql:8 image: mysql:8
container_name: aberwyn-mysql-prod container_name: aberwyn-mysql-prod
restart: always restart: always

View File

@@ -0,0 +1,11 @@
{
"AdminUsername": "admin",
"AdminEmail": "admin@localhost",
"AdminPassword": "Admin123!",
"IsConfigured": true,
"DbHost": "192.168.1.108",
"DbPort": 3306,
"DbName": "lewel_prod",
"DbUser": "lewel",
"DbPassword": "W542.Hl;)%ta"
}

View File

@@ -0,0 +1,848 @@
// <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("20250618203117_AddPaymentStatusToBudgetItem")]
partial class AddPaymentStatusToBudgetItem
{
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("BudgetCategoryDefinitions");
});
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.Property<int>("PaymentStatus")
.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<int?>("DefaultPaymentStatus")
.HasColumnType("int");
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("BudgetItemDefinitions");
});
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.Ingredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Item")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("MealId")
.HasColumnType("int");
b.Property<string>("Quantity")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("MealId");
b.ToTable("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CarbType")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<byte[]>("ImageData")
.HasColumnType("longblob");
b.Property<string>("ImageMimeType")
.HasColumnType("longtext");
b.Property<string>("ImageUrl")
.HasColumnType("longtext");
b.Property<string>("Instructions")
.HasColumnType("longtext");
b.Property<bool>("IsAvailable")
.HasColumnType("tinyint(1)");
b.Property<int?>("MealCategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("ProteinType")
.HasColumnType("longtext");
b.Property<string>("RecipeUrl")
.HasColumnType("longtext");
b.Property<byte[]>("ThumbnailData")
.HasColumnType("longblob");
b.HasKey("Id");
b.HasIndex("MealCategoryId");
b.ToTable("Meals");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.HasColumnType("longtext");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<string>("Icon")
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Slug")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("MealCategories");
b.HasData(
new
{
Id = 1,
Color = "#f97316",
DisplayOrder = 1,
Icon = "🍕",
IsActive = true,
Name = "Pizza",
Slug = "pizza"
});
});
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.Property<int?>("PizzaOrderId")
.HasColumnType("int");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("PizzaOrderId");
b.HasIndex("UserId");
b.ToTable("PushSubscribers");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", 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.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PushSubscriptions");
});
modelBuilder.Entity("Aberwyn.Models.TodoTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("AssignedTo")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsArchived")
.HasColumnType("tinyint(1)");
b.Property<int>("Priority")
.HasColumnType("int");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Tags")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("TodoTasks");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<bool>("NotifyBudget")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyMenu")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyPizza")
.HasColumnType("tinyint(1)");
b.HasKey("UserId");
b.ToTable("UserPreferences");
});
modelBuilder.Entity("Aberwyn.Models.WeeklyMenu", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BreakfastMealId")
.HasColumnType("int");
b.Property<string>("Cook")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("DayOfWeek")
.HasColumnType("int");
b.Property<int?>("DinnerMealId")
.HasColumnType("int");
b.Property<int?>("LunchMealId")
.HasColumnType("int");
b.Property<int>("WeekNumber")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("WeeklyMenu", (string)null);
});
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", null)
.WithMany("Items")
.HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.BudgetItemDefinition", "BudgetItemDefinition")
.WithMany()
.HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetItemDefinition");
});
modelBuilder.Entity("Aberwyn.Models.Ingredient", b =>
{
b.HasOne("Aberwyn.Models.Meal", null)
.WithMany("Ingredients")
.HasForeignKey("MealId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.HasOne("Aberwyn.Models.MealCategory", "Category")
.WithMany("Meals")
.HasForeignKey("MealCategoryId");
b.Navigation("Category");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.HasOne("Aberwyn.Models.PizzaOrder", "PizzaOrder")
.WithMany()
.HasForeignKey("PizzaOrderId");
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PizzaOrder");
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithOne("Preferences")
.HasForeignKey("Aberwyn.Models.UserPreferences", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
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.ApplicationUser", b =>
{
b.Navigation("Preferences")
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Navigation("Categories");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Navigation("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Navigation("Meals");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddPaymentStatusToBudgetItem : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "PaymentStatus",
table: "BudgetItems",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "DefaultPaymentStatus",
table: "BudgetItemDefinitions",
type: "int",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PaymentStatus",
table: "BudgetItems");
migrationBuilder.DropColumn(
name: "DefaultPaymentStatus",
table: "BudgetItemDefinitions");
}
}
}

View File

@@ -0,0 +1,851 @@
// <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("20250624150426_AddIsPublishedToMeals")]
partial class AddIsPublishedToMeals
{
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("BudgetCategoryDefinitions");
});
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.Property<int>("PaymentStatus")
.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<int?>("DefaultPaymentStatus")
.HasColumnType("int");
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("BudgetItemDefinitions");
});
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.Ingredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Item")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("MealId")
.HasColumnType("int");
b.Property<string>("Quantity")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("MealId");
b.ToTable("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CarbType")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<byte[]>("ImageData")
.HasColumnType("longblob");
b.Property<string>("ImageMimeType")
.HasColumnType("longtext");
b.Property<string>("ImageUrl")
.HasColumnType("longtext");
b.Property<string>("Instructions")
.HasColumnType("longtext");
b.Property<bool>("IsAvailable")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsPublished")
.HasColumnType("tinyint(1)");
b.Property<int?>("MealCategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("ProteinType")
.HasColumnType("longtext");
b.Property<string>("RecipeUrl")
.HasColumnType("longtext");
b.Property<byte[]>("ThumbnailData")
.HasColumnType("longblob");
b.HasKey("Id");
b.HasIndex("MealCategoryId");
b.ToTable("Meals");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.HasColumnType("longtext");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<string>("Icon")
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Slug")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("MealCategories");
b.HasData(
new
{
Id = 1,
Color = "#f97316",
DisplayOrder = 1,
Icon = "🍕",
IsActive = true,
Name = "Pizza",
Slug = "pizza"
});
});
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.Property<int?>("PizzaOrderId")
.HasColumnType("int");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("PizzaOrderId");
b.HasIndex("UserId");
b.ToTable("PushSubscribers");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", 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.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PushSubscriptions");
});
modelBuilder.Entity("Aberwyn.Models.TodoTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("AssignedTo")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsArchived")
.HasColumnType("tinyint(1)");
b.Property<int>("Priority")
.HasColumnType("int");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Tags")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("TodoTasks");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<bool>("NotifyBudget")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyMenu")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyPizza")
.HasColumnType("tinyint(1)");
b.HasKey("UserId");
b.ToTable("UserPreferences");
});
modelBuilder.Entity("Aberwyn.Models.WeeklyMenu", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BreakfastMealId")
.HasColumnType("int");
b.Property<string>("Cook")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("DayOfWeek")
.HasColumnType("int");
b.Property<int?>("DinnerMealId")
.HasColumnType("int");
b.Property<int?>("LunchMealId")
.HasColumnType("int");
b.Property<int>("WeekNumber")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("WeeklyMenu", (string)null);
});
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", null)
.WithMany("Items")
.HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.BudgetItemDefinition", "BudgetItemDefinition")
.WithMany()
.HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetItemDefinition");
});
modelBuilder.Entity("Aberwyn.Models.Ingredient", b =>
{
b.HasOne("Aberwyn.Models.Meal", null)
.WithMany("Ingredients")
.HasForeignKey("MealId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.HasOne("Aberwyn.Models.MealCategory", "Category")
.WithMany("Meals")
.HasForeignKey("MealCategoryId");
b.Navigation("Category");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.HasOne("Aberwyn.Models.PizzaOrder", "PizzaOrder")
.WithMany()
.HasForeignKey("PizzaOrderId");
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PizzaOrder");
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithOne("Preferences")
.HasForeignKey("Aberwyn.Models.UserPreferences", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
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.ApplicationUser", b =>
{
b.Navigation("Preferences")
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Navigation("Categories");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Navigation("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Navigation("Meals");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddIsPublishedToMeals : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsPublished",
table: "Meals",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsPublished",
table: "Meals");
}
}
}

View File

@@ -0,0 +1,949 @@
// <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("20250630123620_AddRecipeLab")]
partial class AddRecipeLab
{
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("BudgetCategoryDefinitions");
});
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.Property<int>("PaymentStatus")
.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<int?>("DefaultPaymentStatus")
.HasColumnType("int");
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("BudgetItemDefinitions");
});
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.Ingredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Item")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("MealId")
.HasColumnType("int");
b.Property<string>("Quantity")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("MealId");
b.ToTable("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CarbType")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<byte[]>("ImageData")
.HasColumnType("longblob");
b.Property<string>("ImageMimeType")
.HasColumnType("longtext");
b.Property<string>("ImageUrl")
.HasColumnType("longtext");
b.Property<string>("Instructions")
.HasColumnType("longtext");
b.Property<bool>("IsAvailable")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsPublished")
.HasColumnType("tinyint(1)");
b.Property<int?>("MealCategoryId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("ProteinType")
.HasColumnType("longtext");
b.Property<string>("RecipeUrl")
.HasColumnType("longtext");
b.Property<byte[]>("ThumbnailData")
.HasColumnType("longblob");
b.HasKey("Id");
b.HasIndex("MealCategoryId");
b.ToTable("Meals");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.HasColumnType("longtext");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<string>("Icon")
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Slug")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("MealCategories");
b.HasData(
new
{
Id = 1,
Color = "#f97316",
DisplayOrder = 1,
Icon = "🍕",
IsActive = true,
Name = "Pizza",
Slug = "pizza"
});
});
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.Property<int?>("PizzaOrderId")
.HasColumnType("int");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("PizzaOrderId");
b.HasIndex("UserId");
b.ToTable("PushSubscribers");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BaseMealId")
.HasColumnType("int");
b.Property<string>("Category")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Inspiration")
.HasColumnType("longtext");
b.Property<string>("Notes")
.HasColumnType("longtext");
b.Property<int?>("Rating")
.HasColumnType("int");
b.Property<string>("Tags")
.HasColumnType("longtext");
b.Property<string>("TestedBy")
.HasColumnType("longtext");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("BaseMealId");
b.ToTable("RecipeLabEntries");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabVersion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Ingredients")
.HasColumnType("longtext");
b.Property<string>("Instructions")
.HasColumnType("longtext");
b.Property<int>("RecipeLabEntryId")
.HasColumnType("int");
b.Property<string>("ResultNotes")
.HasColumnType("longtext");
b.Property<string>("VersionLabel")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("RecipeLabEntryId");
b.ToTable("RecipeLabVersions");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", 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.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PushSubscriptions");
});
modelBuilder.Entity("Aberwyn.Models.TodoTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("AssignedTo")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsArchived")
.HasColumnType("tinyint(1)");
b.Property<int>("Priority")
.HasColumnType("int");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Tags")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("TodoTasks");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<bool>("NotifyBudget")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyMenu")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyPizza")
.HasColumnType("tinyint(1)");
b.HasKey("UserId");
b.ToTable("UserPreferences");
});
modelBuilder.Entity("Aberwyn.Models.WeeklyMenu", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BreakfastMealId")
.HasColumnType("int");
b.Property<string>("Cook")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("DayOfWeek")
.HasColumnType("int");
b.Property<int?>("DinnerMealId")
.HasColumnType("int");
b.Property<int?>("LunchMealId")
.HasColumnType("int");
b.Property<int>("WeekNumber")
.HasColumnType("int");
b.Property<int>("Year")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("WeeklyMenu", (string)null);
});
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", null)
.WithMany("Items")
.HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Aberwyn.Models.BudgetItemDefinition", "BudgetItemDefinition")
.WithMany()
.HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetItemDefinition");
});
modelBuilder.Entity("Aberwyn.Models.Ingredient", b =>
{
b.HasOne("Aberwyn.Models.Meal", null)
.WithMany("Ingredients")
.HasForeignKey("MealId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.HasOne("Aberwyn.Models.MealCategory", "Category")
.WithMany("Meals")
.HasForeignKey("MealCategoryId");
b.Navigation("Category");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.HasOne("Aberwyn.Models.PizzaOrder", "PizzaOrder")
.WithMany()
.HasForeignKey("PizzaOrderId");
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PizzaOrder");
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.HasOne("Aberwyn.Models.Meal", "BaseMeal")
.WithMany()
.HasForeignKey("BaseMealId");
b.Navigation("BaseMeal");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabVersion", b =>
{
b.HasOne("Aberwyn.Models.RecipeLabEntry", "Entry")
.WithMany("Versions")
.HasForeignKey("RecipeLabEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Entry");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithOne("Preferences")
.HasForeignKey("Aberwyn.Models.UserPreferences", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
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.ApplicationUser", b =>
{
b.Navigation("Preferences")
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Aberwyn.Models.BudgetPeriod", b =>
{
b.Navigation("Categories");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.Navigation("Ingredients");
});
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Navigation("Meals");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.Navigation("Versions");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,95 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddRecipeLab : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "RecipeLabEntries",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Category = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Inspiration = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
BaseMealId = table.Column<int>(type: "int", nullable: true),
Notes = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Rating = table.Column<int>(type: "int", nullable: true),
TestedBy = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Tags = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RecipeLabEntries", x => x.Id);
table.ForeignKey(
name: "FK_RecipeLabEntries_Meals_BaseMealId",
column: x => x.BaseMealId,
principalTable: "Meals",
principalColumn: "Id");
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "RecipeLabVersions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
RecipeLabEntryId = table.Column<int>(type: "int", nullable: false),
VersionLabel = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Ingredients = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Instructions = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
ResultNotes = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RecipeLabVersions", x => x.Id);
table.ForeignKey(
name: "FK_RecipeLabVersions_RecipeLabEntries_RecipeLabEntryId",
column: x => x.RecipeLabEntryId,
principalTable: "RecipeLabEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_RecipeLabEntries_BaseMealId",
table: "RecipeLabEntries",
column: "BaseMealId");
migrationBuilder.CreateIndex(
name: "IX_RecipeLabVersions_RecipeLabEntryId",
table: "RecipeLabVersions",
column: "RecipeLabEntryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "RecipeLabVersions");
migrationBuilder.DropTable(
name: "RecipeLabEntries");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,80 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddLabIngredientModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "LabIngredients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
RecipeLabEntryId = table.Column<int>(type: "int", nullable: false),
Quantity = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Item = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_LabIngredients", x => x.Id);
table.ForeignKey(
name: "FK_LabIngredients_RecipeLabEntries_RecipeLabEntryId",
column: x => x.RecipeLabEntryId,
principalTable: "RecipeLabEntries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "LabVersionIngredients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
RecipeLabVersionId = table.Column<int>(type: "int", nullable: false),
Quantity = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Item = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_LabVersionIngredients", x => x.Id);
table.ForeignKey(
name: "FK_LabVersionIngredients_RecipeLabVersions_RecipeLabVersionId",
column: x => x.RecipeLabVersionId,
principalTable: "RecipeLabVersions",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_LabIngredients_RecipeLabEntryId",
table: "LabIngredients",
column: "RecipeLabEntryId");
migrationBuilder.CreateIndex(
name: "IX_LabVersionIngredients_RecipeLabVersionId",
table: "LabVersionIngredients",
column: "RecipeLabVersionId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LabIngredients");
migrationBuilder.DropTable(
name: "LabVersionIngredients");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddRecipeLabModels : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Ingredients",
table: "RecipeLabVersions");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Ingredients",
table: "RecipeLabVersions",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddMealRating : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MealRatings",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
MealId = table.Column<int>(type: "int", nullable: false),
UserId = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Rating = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MealRatings", x => x.Id);
table.ForeignKey(
name: "FK_MealRatings_Meals_MealId",
column: x => x.MealId,
principalTable: "Meals",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_MealRatings_MealId",
table: "MealRatings",
column: "MealId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MealRatings");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddNameToBudgetPeriod : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class AddNameToBudgetPeriod2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Name",
table: "BudgetPeriods",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Name",
table: "BudgetPeriods");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Aberwyn.Migrations
{
public partial class MakeYearMonthNullable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Year",
table: "BudgetPeriods",
type: "int",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<int>(
name: "Month",
table: "BudgetPeriods",
type: "int",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Year",
table: "BudgetPeriods",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "Month",
table: "BudgetPeriods",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
}
}
}

View File

@@ -181,6 +181,9 @@ namespace Aberwyn.Migrations
b.Property<int>("Order") b.Property<int>("Order")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("PaymentStatus")
.HasColumnType("int");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("BudgetCategoryId"); b.HasIndex("BudgetCategoryId");
@@ -199,6 +202,9 @@ namespace Aberwyn.Migrations
b.Property<string>("DefaultCategory") b.Property<string>("DefaultCategory")
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<int?>("DefaultPaymentStatus")
.HasColumnType("int");
b.Property<bool>("IncludeInSummary") b.Property<bool>("IncludeInSummary")
.HasColumnType("tinyint(1)"); .HasColumnType("tinyint(1)");
@@ -220,13 +226,16 @@ namespace Aberwyn.Migrations
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("Month") b.Property<int?>("Month")
.HasColumnType("int"); .HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("longtext");
b.Property<int>("Order") b.Property<int>("Order")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("Year") b.Property<int?>("Year")
.HasColumnType("int"); .HasColumnType("int");
b.HasKey("Id"); b.HasKey("Id");
@@ -258,6 +267,54 @@ namespace Aberwyn.Migrations
b.ToTable("Ingredients"); b.ToTable("Ingredients");
}); });
modelBuilder.Entity("Aberwyn.Models.LabIngredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Item")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Quantity")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("RecipeLabEntryId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RecipeLabEntryId");
b.ToTable("LabIngredients");
});
modelBuilder.Entity("Aberwyn.Models.LabVersionIngredient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Item")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Quantity")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("RecipeLabVersionId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RecipeLabVersionId");
b.ToTable("LabVersionIngredients");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b => modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -267,9 +324,6 @@ namespace Aberwyn.Migrations
b.Property<string>("CarbType") b.Property<string>("CarbType")
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<string>("Category")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt") b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)"); .HasColumnType("datetime(6)");
@@ -291,6 +345,12 @@ namespace Aberwyn.Migrations
b.Property<bool>("IsAvailable") b.Property<bool>("IsAvailable")
.HasColumnType("tinyint(1)"); .HasColumnType("tinyint(1)");
b.Property<bool>("IsPublished")
.HasColumnType("tinyint(1)");
b.Property<int?>("MealCategoryId")
.HasColumnType("int");
b.Property<string>("Name") b.Property<string>("Name")
.IsRequired() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");
@@ -301,11 +361,87 @@ namespace Aberwyn.Migrations
b.Property<string>("RecipeUrl") b.Property<string>("RecipeUrl")
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<byte[]>("ThumbnailData")
.HasColumnType("longblob");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("MealCategoryId");
b.ToTable("Meals"); b.ToTable("Meals");
}); });
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Color")
.HasColumnType("longtext");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<string>("Icon")
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Slug")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("MealCategories");
b.HasData(
new
{
Id = 1,
Color = "#f97316",
DisplayOrder = 1,
Icon = "🍕",
IsActive = true,
Name = "Pizza",
Slug = "pizza"
});
});
modelBuilder.Entity("Aberwyn.Models.MealRating", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("MealId")
.HasColumnType("int");
b.Property<int>("Rating")
.HasColumnType("int");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("MealId");
b.ToTable("MealRatings");
});
modelBuilder.Entity("Aberwyn.Models.PizzaOrder", b => modelBuilder.Entity("Aberwyn.Models.PizzaOrder", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -353,11 +489,121 @@ namespace Aberwyn.Migrations
.IsRequired() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<int?>("PizzaOrderId")
.HasColumnType("int");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("PizzaOrderId");
b.HasIndex("UserId");
b.ToTable("PushSubscribers"); b.ToTable("PushSubscribers");
}); });
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BaseMealId")
.HasColumnType("int");
b.Property<string>("Category")
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Inspiration")
.HasColumnType("longtext");
b.Property<string>("Notes")
.HasColumnType("longtext");
b.Property<int?>("Rating")
.HasColumnType("int");
b.Property<string>("Tags")
.HasColumnType("longtext");
b.Property<string>("TestedBy")
.HasColumnType("longtext");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("BaseMealId");
b.ToTable("RecipeLabEntries");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabVersion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Instructions")
.HasColumnType("longtext");
b.Property<int>("RecipeLabEntryId")
.HasColumnType("int");
b.Property<string>("ResultNotes")
.HasColumnType("longtext");
b.Property<string>("VersionLabel")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("RecipeLabEntryId");
b.ToTable("RecipeLabVersions");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", 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.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("PushSubscriptions");
});
modelBuilder.Entity("Aberwyn.Models.TodoTask", b => modelBuilder.Entity("Aberwyn.Models.TodoTask", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -365,7 +611,6 @@ namespace Aberwyn.Migrations
.HasColumnType("int"); .HasColumnType("int");
b.Property<string>("AssignedTo") b.Property<string>("AssignedTo")
.IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<DateTime>("CreatedAt") b.Property<DateTime>("CreatedAt")
@@ -398,6 +643,25 @@ namespace Aberwyn.Migrations
b.ToTable("TodoTasks"); b.ToTable("TodoTasks");
}); });
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255)");
b.Property<bool>("NotifyBudget")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyMenu")
.HasColumnType("tinyint(1)");
b.Property<bool>("NotifyPizza")
.HasColumnType("tinyint(1)");
b.HasKey("UserId");
b.ToTable("UserPreferences");
});
modelBuilder.Entity("Aberwyn.Models.WeeklyMenu", b => modelBuilder.Entity("Aberwyn.Models.WeeklyMenu", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -580,7 +844,7 @@ namespace Aberwyn.Migrations
modelBuilder.Entity("Aberwyn.Models.BudgetItem", b => modelBuilder.Entity("Aberwyn.Models.BudgetItem", b =>
{ {
b.HasOne("Aberwyn.Models.BudgetCategory", "BudgetCategory") b.HasOne("Aberwyn.Models.BudgetCategory", null)
.WithMany("Items") .WithMany("Items")
.HasForeignKey("BudgetCategoryId") .HasForeignKey("BudgetCategoryId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -590,8 +854,6 @@ namespace Aberwyn.Migrations
.WithMany() .WithMany()
.HasForeignKey("BudgetItemDefinitionId"); .HasForeignKey("BudgetItemDefinitionId");
b.Navigation("BudgetCategory");
b.Navigation("BudgetItemDefinition"); b.Navigation("BudgetItemDefinition");
}); });
@@ -604,6 +866,107 @@ namespace Aberwyn.Migrations
.IsRequired(); .IsRequired();
}); });
modelBuilder.Entity("Aberwyn.Models.LabIngredient", b =>
{
b.HasOne("Aberwyn.Models.RecipeLabEntry", "Entry")
.WithMany("Ingredients")
.HasForeignKey("RecipeLabEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Entry");
});
modelBuilder.Entity("Aberwyn.Models.LabVersionIngredient", b =>
{
b.HasOne("Aberwyn.Models.RecipeLabVersion", "Version")
.WithMany("Ingredients")
.HasForeignKey("RecipeLabVersionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Version");
});
modelBuilder.Entity("Aberwyn.Models.Meal", b =>
{
b.HasOne("Aberwyn.Models.MealCategory", "Category")
.WithMany("Meals")
.HasForeignKey("MealCategoryId");
b.Navigation("Category");
});
modelBuilder.Entity("Aberwyn.Models.MealRating", b =>
{
b.HasOne("Aberwyn.Models.Meal", "Meal")
.WithMany()
.HasForeignKey("MealId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Meal");
});
modelBuilder.Entity("Aberwyn.Models.PushSubscriber", b =>
{
b.HasOne("Aberwyn.Models.PizzaOrder", "PizzaOrder")
.WithMany()
.HasForeignKey("PizzaOrderId");
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PizzaOrder");
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.HasOne("Aberwyn.Models.Meal", "BaseMeal")
.WithMany()
.HasForeignKey("BaseMealId");
b.Navigation("BaseMeal");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabVersion", b =>
{
b.HasOne("Aberwyn.Models.RecipeLabEntry", "Entry")
.WithMany("Versions")
.HasForeignKey("RecipeLabEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Entry");
});
modelBuilder.Entity("Aberwyn.Models.StoredPushSubscription", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Aberwyn.Models.UserPreferences", b =>
{
b.HasOne("Aberwyn.Models.ApplicationUser", "User")
.WithOne("Preferences")
.HasForeignKey("Aberwyn.Models.UserPreferences", "UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{ {
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
@@ -655,6 +1018,12 @@ namespace Aberwyn.Migrations
.IsRequired(); .IsRequired();
}); });
modelBuilder.Entity("Aberwyn.Models.ApplicationUser", b =>
{
b.Navigation("Preferences")
.IsRequired();
});
modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b => modelBuilder.Entity("Aberwyn.Models.BudgetCategory", b =>
{ {
b.Navigation("Items"); b.Navigation("Items");
@@ -669,6 +1038,23 @@ namespace Aberwyn.Migrations
{ {
b.Navigation("Ingredients"); b.Navigation("Ingredients");
}); });
modelBuilder.Entity("Aberwyn.Models.MealCategory", b =>
{
b.Navigation("Meals");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabEntry", b =>
{
b.Navigation("Ingredients");
b.Navigation("Versions");
});
modelBuilder.Entity("Aberwyn.Models.RecipeLabVersion", b =>
{
b.Navigation("Ingredients");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@@ -13,9 +13,9 @@
public string Title { get; set; } public string Title { get; set; }
public string Description { get; set; } public string Description { get; set; }
public int Priority { get; set; } public int Priority { get; set; }
public string Status { get; set; } // e.g., "ideas", "doing", "done" public string Status { get; set; } = "ideas";
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public string AssignedTo { get; set; } // Ex: namn eller användarnamn public string? AssignedTo { get; set; }
public bool IsArchived { get; set; } public bool IsArchived { get; set; }
public string Tags { get; set; } // Komma-separerad t.ex. "frontend,bug" public string Tags { get; set; } // Komma-separerad t.ex. "frontend,bug"
} }

View File

@@ -4,6 +4,8 @@
public class ApplicationUser : IdentityUser public class ApplicationUser : IdentityUser
{ {
public virtual UserPreferences Preferences { get; set; }
// Lägg till egna fält om du vill, t.ex. public string DisplayName { get; set; } // Lägg till egna fält om du vill, t.ex. public string DisplayName { get; set; }
} }
} }

View File

@@ -7,9 +7,11 @@ namespace Aberwyn.Models
public class BudgetPeriod public class BudgetPeriod
{ {
public int Id { get; set; } public int Id { get; set; }
public int Year { get; set; } public int? Year { get; set; }
public int Month { get; set; } public int? Month { get; set; }
public int Order { get; set; } public int Order { get; set; }
public string? Name { get; set; }
public List<BudgetCategory> Categories { get; set; } = new(); public List<BudgetCategory> Categories { get; set; } = new();
} }
@@ -47,14 +49,24 @@ namespace Aberwyn.Models
[JsonIgnore] [JsonIgnore]
[ValidateNever] [ValidateNever]
public BudgetCategory BudgetCategory { get; set; }
public PaymentStatus PaymentStatus { get; set; } = PaymentStatus.None;
}
public enum PaymentStatus
{
None = 0,
Due = 1,
Paid = 2
} }
// DTOs/BudgetDto.cs // DTOs/BudgetDto.cs
public class BudgetDto public class BudgetDto
{ {
public int Id { get; set; } public int Id { get; set; }
public int Year { get; set; } public string? Name { get; set; }
public int Month { get; set; } public int? Year { get; set; }
public int? Month { get; set; }
public int Order { get; set; } public int Order { get; set; }
public List<BudgetCategoryDto> Categories { get; set; } = new(); public List<BudgetCategoryDto> Categories { get; set; } = new();
@@ -69,7 +81,7 @@ namespace Aberwyn.Models
public int Order { get; set; } public int Order { get; set; }
public int? BudgetCategoryDefinitionId { get; set; } public int? BudgetCategoryDefinitionId { get; set; }
public int? BudgetPeriodId { get; set; }
public int Year { get; set; } public int Year { get; set; }
public int Month { get; set; } public int Month { get; set; }
} }
@@ -84,6 +96,7 @@ namespace Aberwyn.Models
public bool IsExpense { get; set; } public bool IsExpense { get; set; }
public bool IncludeInSummary { get; set; } public bool IncludeInSummary { get; set; }
public PaymentStatus PaymentStatus { get; set; }
} }
@@ -91,6 +104,11 @@ namespace Aberwyn.Models
{ {
public List<BudgetItem> BudgetItems { get; set; } = new List<BudgetItem>(); public List<BudgetItem> BudgetItems { get; set; } = new List<BudgetItem>();
} }
public class PaymentStatusUpdateDto
{
public int ItemId { get; set; }
public PaymentStatus Status { get; set; }
}
public class BudgetItemDefinition public class BudgetItemDefinition
{ {
@@ -99,6 +117,8 @@ namespace Aberwyn.Models
public string? DefaultCategory { get; set; } // valfritt, kan föreslå "Bilar" public string? DefaultCategory { get; set; } // valfritt, kan föreslå "Bilar"
public bool IsExpense { get; set; } public bool IsExpense { get; set; }
public bool IncludeInSummary { get; set; } public bool IncludeInSummary { get; set; }
public PaymentStatus? DefaultPaymentStatus { get; set; }
} }
public class BudgetCategoryDefinition public class BudgetCategoryDefinition
{ {

View File

@@ -0,0 +1,33 @@
namespace Aberwyn.Models
{
public class StreamingService
{
public int Id { get; set; }
public string Name { get; set; } // T.ex. "Netflix", "Plex"
}
public class MediaItem
{
public int Id { get; set; }
public string TmdbId { get; set; } // TMDb ID
public string Title { get; set; }
public string Overview { get; set; }
public string PosterPath { get; set; }
public string MediaType { get; set; } // "movie" eller "tv"
public double Rating { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<MediaItemStreamingService> MediaItemStreamingServices { get; set; } = new();
}
public class MediaItemStreamingService
{
public int MediaItemId { get; set; }
public MediaItem MediaItem { get; set; }
public int StreamingServiceId { get; set; }
public StreamingService StreamingService { get; set; }
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using Aberwyn.Data; using Aberwyn.Data;
using Aberwyn.Models; using Aberwyn.Models;
@@ -12,6 +13,25 @@ namespace Aberwyn.Models
public int WeekNumber { get; set; } // Week number for the menu public int WeekNumber { get; set; } // Week number for the menu
public int Year { get; set; } // Year for the menu public int Year { get; set; } // Year for the menu
} }
public class WeeklyMenuDto
{
public int Id { get; set; }
public int DayOfWeek { get; set; }
public int WeekNumber { get; set; }
public int Year { get; set; }
public int? BreakfastMealId { get; set; }
public int? LunchMealId { get; set; }
public int? DinnerMealId { get; set; }
public string? BreakfastMealName { get; set; }
public string? LunchMealName { get; set; }
public string? DinnerMealName { get; set; }
public byte[]? DinnerMealThumbnail { get; set; }
}
public class WeeklyMenu public class WeeklyMenu
{ {
public int Id { get; set; } public int Id { get; set; }
@@ -23,6 +43,9 @@ public class WeeklyMenu
public int WeekNumber { get; set; } public int WeekNumber { get; set; }
public int Year { get; set; } public int Year { get; set; }
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
[NotMapped] public byte[]? BreakfastThumbnail { get; set; }
[NotMapped] public byte[]? LunchThumbnail { get; set; }
[NotMapped] public byte[]? DinnerThumbnail { get; set; }
[NotMapped] public string? BreakfastMealName { get; set; } [NotMapped] public string? BreakfastMealName { get; set; }
[NotMapped] public string? LunchMealName { get; set; } [NotMapped] public string? LunchMealName { get; set; }
@@ -40,26 +63,34 @@ public class WeeklyMenu
public string LunchMealName { get; set; } public string LunchMealName { get; set; }
public string DinnerMealName { get; set; } public string DinnerMealName { get; set; }
} }
public class Meal public class Meal
{ {
public int Id { get; set; } [Key]
public string Name { get; set; } // Behåll som obligatorisk [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string? Description { get; set; } public string Name { get; set; } // Behåll som obligatorisk
public string? ProteinType { get; set; }
public string? Category { get; set; }
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; } // 👈 Viktigt! public string? Description { get; set; }
public string? ImageMimeType { get; set; } // 👈 Viktigt! public string? ProteinType { get; set; }
public string? Instructions { get; set; } // 👈 Viktigt! public int? MealCategoryId { get; set; }
public List<Ingredient> Ingredients { get; set; } = new(); [ForeignKey("MealCategoryId")]
} public MealCategory? Category { get; set; }
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[]? ThumbnailData { get; set; }
public bool IsPublished { get; set; } = false;
public byte[]? ImageData { get; set; }
public string? ImageMimeType { get; set; }
public string? Instructions { get; set; }
public List<Ingredient> Ingredients { get; set; } = new();
}
public class Ingredient public class Ingredient
{ {
@@ -79,20 +110,89 @@ public class Meal
public string? ImageData { get; set; } // base64 public string? ImageData { get; set; } // base64
public string? ImageMimeType { get; set; } public string? ImageMimeType { get; set; }
public static MealDto FromMeal(Meal meal) public static MealListDto FromMeal(Meal meal, bool includeThumbnail = false)
{ {
return new MealDto return new MealListDto
{ {
Id = meal.Id, Id = meal.Id,
Name = meal.Name, Name = meal.Name,
Category = meal.Category, Description = meal.Description,
IsAvailable = meal.IsAvailable, ThumbnailData = includeThumbnail && meal.ThumbnailData != null
ImageUrl = meal.ImageUrl, ? Convert.ToBase64String(meal.ThumbnailData)
ImageMimeType = meal.ImageMimeType, : null
ImageData = meal.ImageData != null ? Convert.ToBase64String(meal.ImageData) : null
}; };
} }
} }
public class MealListDto
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string? Description { get; set; }
public string? ThumbnailData { get; set; }
public List<IngredientDto> Ingredients { get; set; } = new();
public static MealListDto FromMeal(Meal meal, bool includeThumbnail = false)
{
return new MealListDto
{
Id = meal.Id,
Name = meal.Name,
Description = meal.Description,
ThumbnailData = includeThumbnail && meal.ThumbnailData != null
? Convert.ToBase64String(meal.ThumbnailData)
: null,
Ingredients = meal.Ingredients?.Select(i => new IngredientDto
{
Item = i.Item
}).ToList() ?? new List<IngredientDto>()
};
}
public class IngredientDto
{
public string Item { get; set; } = "";
}
}
public class MealCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string? Slug { get; set; }
public string? Description { get; set; }
public string? Icon { get; set; }
public string? Color { get; set; }
public bool IsActive { get; set; } = true;
public int DisplayOrder { get; set; } = 0;
[NotMapped] // krävs om du inte har kolumnen i databasen
public int MealCount { get; set; }
public List<Meal> Meals { get; set; } = new();
}
public class MealRating
{
public int Id { get; set; }
public int MealId { get; set; }
public string UserId { get; set; }
public int Rating { get; set; }
public DateTime CreatedAt { get; set; }
public Meal Meal { get; set; }
}
public class MealRatingDto
{
public int MealId { get; set; }
public int Rating { get; set; }
}
} }

View File

@@ -6,6 +6,11 @@
public string Endpoint { get; set; } public string Endpoint { get; set; }
public string P256DH { get; set; } public string P256DH { get; set; }
public string Auth { get; set; } public string Auth { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public int? PizzaOrderId { get; set; }
public virtual PizzaOrder PizzaOrder { get; set; }
} }
public class PushMessageDto public class PushMessageDto
{ {

View File

@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Aberwyn.Models
{
public class RecipeLabEntry
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string? Category { get; set; }
public string? Inspiration { get; set; }
public int? BaseMealId { get; set; }
[ForeignKey("BaseMealId")]
public Meal? BaseMeal { get; set; }
public string? Notes { get; set; }
public int? Rating { get; set; }
public string? TestedBy { get; set; }
public string? Tags { get; set; } // "vego,snabbt"
public DateTime CreatedAt { get; set; } = DateTime.Now;
public List<LabIngredient> Ingredients { get; set; } = new();
public List<RecipeLabVersion> Versions { get; set; } = new();
}
public class RecipeLabVersion
{
[Key]
public int Id { get; set; }
public int RecipeLabEntryId { get; set; }
[ForeignKey("RecipeLabEntryId")]
public RecipeLabEntry Entry { get; set; }
public string VersionLabel { get; set; } = "v1";
public List<LabVersionIngredient> Ingredients { get; set; } = new();
public string? Instructions { get; set; }
public string? ResultNotes { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
}
public class LabIngredient
{
[Key]
public int Id { get; set; }
public int RecipeLabEntryId { get; set; }
[ForeignKey("RecipeLabEntryId")]
public RecipeLabEntry Entry { get; set; }
public string Quantity { get; set; } = "";
public string Item { get; set; } = "";
}
public class LabVersionIngredient
{
public int Id { get; set; }
public int RecipeLabVersionId { get; set; }
[ForeignKey("RecipeLabVersionId")]
public RecipeLabVersion Version { get; set; }
public string Quantity { get; set; } = "";
public string Item { get; set; } = "";
}
}

View File

@@ -0,0 +1,17 @@
namespace Aberwyn.Models
{
public class SetupSettings
{
public string AdminUsername { get; set; } = "admin";
public string AdminEmail { get; set; } = "admin@localhost";
public string AdminPassword { get; set; } = "Admin123!";
public bool IsConfigured { get; set; }
public string DbHost { get; set; }
public int DbPort { get; set; }
public string DbName { get; set; }
public string DbUser { get; set; }
public string DbPassword { get; set; }
}
}

View File

@@ -0,0 +1,29 @@
public class TorrentInfo
{
public string FileName { get; set; }
public string AnnounceUrl { get; set; }
public string ScrapeUrl { get; set; }
public string InfoHash { get; set; }
public byte[] InfoHashBytes { get; set; }
public long Size { get; set; }
public int Seeders { get; set; } = 0;
public int Leechers { get; set; } = 0;
public int Completed { get; set; } = 0;
public bool HasTrackerData { get; set; } = false;
public string ErrorMessage { get; set; }
}
public class TrackerInfo
{
public string Name { get; set; }
public bool SupportsScraping { get; set; }
public bool RequiresAuth { get; set; }
public bool IsPrivate { get; set; }
public string Notes { get; set; }
}
public class TorrentUploadViewModel
{
public IFormFile TorrentFile { get; set; }
public TorrentInfo TorrentInfo { get; set; }
public bool ShowResults { get; set; } = false;
}

View File

@@ -1,10 +0,0 @@
namespace Aberwyn.Models
{
public class User
{
public int UserID { get; set; }
public string Username { get; set; }
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,47 @@
using System.ComponentModel.DataAnnotations;
namespace Aberwyn.Models
{
public class UserModel
{
public int UserID { get; set; }
public string Username { get; set; }
public string Name { get; set; }
}
public class UserPreferences
{
[Key]
public string UserId { get; set; }
public bool NotifyPizza { get; set; }
public bool NotifyMenu { get; set; }
public bool NotifyBudget { get; set; }
public virtual ApplicationUser User { get; set; }
}
public class StoredPushSubscription
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
public string Endpoint { get; set; }
public string P256DH { get; set; }
public string Auth { get; set; }
public virtual ApplicationUser User { get; set; }
}
public class UserProfileViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public bool NotifyPizza { get; set; }
public bool NotifyMenu { get; set; }
public bool NotifyBudget { get; set; }
}
}

View File

@@ -13,9 +13,8 @@ namespace Aberwyn.Models
public List<RecentMenuEntry> RecentEntries { get; set; } = new(); public List<RecentMenuEntry> RecentEntries { get; set; } = new();
public List<WeeklyMenu> WeeklyMenus { get; set; } = new(); public List<WeeklyMenu> WeeklyMenus { get; set; } = new();
public List<User> AvailableCooks { get; set; } = new(); public List<UserModel> AvailableCooks { get; set; } = new();
// Ny lista för översikt
public List<WeeklyMenuViewModel> PreviousWeeks { get; set; } = new(); public List<WeeklyMenuViewModel> PreviousWeeks { get; set; } = new();
public class RecentMenuEntry public class RecentMenuEntry
{ {

View File

@@ -1,14 +1,13 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Aberwyn.Data; using Aberwyn.Data;
using System.Text; using System.Text;
using System.Globalization; using System.Globalization;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Aberwyn.Models; using Aberwyn.Models;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using System.Text.Json;
using Aberwyn.Services;
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) .SetBasePath(Directory.GetCurrentDirectory())
@@ -16,7 +15,6 @@ var config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables() .AddEnvironmentVariables()
.Build(); .Build();
Console.WriteLine("📦 DEBUG: laddad raw-connectionstring: " + config.GetConnectionString("DefaultConnection"));
var builder = WebApplication.CreateBuilder(new WebApplicationOptions var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{ {
@@ -24,22 +22,62 @@ var builder = WebApplication.CreateBuilder(new WebApplicationOptions
EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production" EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"
}); });
builder.Configuration.AddConfiguration(config); builder.Configuration.AddConfiguration(config);
Console.WriteLine("🌍 Miljö: " + builder.Environment.EnvironmentName);
Console.WriteLine("🔗 Connection string: " + builder.Configuration.GetConnectionString("DefaultConnection"));
// Add services to the container. // Läser setup.json eller skapar en ny tom om den inte finns
var setupFilePath = Path.Combine("infrastructure", "setup.json");
if (!File.Exists(setupFilePath))
{
var initialSettings = new SetupSettings
{
IsConfigured = false,
DbPort = 3306
};
var initialJson = JsonSerializer.Serialize(initialSettings, new JsonSerializerOptions { WriteIndented = true });
Directory.CreateDirectory(Path.GetDirectoryName(setupFilePath)!); // säkerställ att mappen finns
File.WriteAllText(setupFilePath, initialJson);
}
SetupSettings setup;
try
{
using var jsonStream = File.OpenRead(setupFilePath);
setup = JsonSerializer.Deserialize<SetupSettings>(jsonStream)!;
if (setup.IsConfigured)
{
if (string.IsNullOrWhiteSpace(setup.DbHost) ||
string.IsNullOrWhiteSpace(setup.DbName) ||
string.IsNullOrWhiteSpace(setup.DbUser) ||
string.IsNullOrWhiteSpace(setup.DbPassword))
{
throw new Exception("Databasinställningarna är ofullständiga.");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Fel vid läsning av setup.json: {ex.Message}");
setup = new SetupSettings { IsConfigured = false };
}
builder.Services.AddHttpClient<ITorrentService, TorrentService>();
builder.Services.AddScoped<ITorrentService, TorrentService>();
// Add services to the container
builder.Services.AddControllersWithViews() builder.Services.AddControllersWithViews()
.AddJsonOptions(opts => .AddJsonOptions(opts =>
{ {
// Beh<65>ll propertynamn som i C#-klassen (PascalCase)
opts.JsonSerializerOptions.PropertyNamingPolicy = null; opts.JsonSerializerOptions.PropertyNamingPolicy = null;
// Ignorera null-v<>rden vid serialisering
opts.JsonSerializerOptions.IgnoreNullValues = true; opts.JsonSerializerOptions.IgnoreNullValues = true;
}); });
builder.Services.AddSession(options => builder.Services.AddSession(options =>
{ {
options.IdleTimeout = TimeSpan.FromHours(1); options.IdleTimeout = TimeSpan.FromDays(30);
options.Cookie.HttpOnly = true; options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true; options.Cookie.IsEssential = true;
}); });
@@ -47,24 +85,43 @@ builder.Services.AddSession(options =>
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
// Configure your DbContext with MySQLs // Registrera rätt databas och identity beroende på om setup är klar
Console.WriteLine("🔗 Connection string: " + builder.Configuration.GetConnectionString("DefaultConnection")); if (setup.IsConfigured)
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(
builder.Configuration.GetConnectionString("DefaultConnection"),
new MySqlServerVersion(new Version(8, 0, 36)),
mySqlOptions => mySqlOptions.EnableRetryOnFailure()
)
);
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{ {
options.SignIn.RequireConfirmedAccount = false;
}) var csBuilder = new MySqlConnector.MySqlConnectionStringBuilder
.AddEntityFrameworkStores<ApplicationDbContext>() {
.AddDefaultTokenProviders(); Server = setup.DbHost,
Port = (uint)setup.DbPort,
Database = setup.DbName,
UserID = setup.DbUser,
Password = setup.DbPassword,
AllowUserVariables = true // valfritt ta bort om du inte använder det
};
var connectionString = csBuilder.ConnectionString;
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
else
{
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase("TempSetup"));
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
// Identity inställningar
builder.Services.Configure<IdentityOptions>(options => builder.Services.Configure<IdentityOptions>(options =>
{ {
options.Password.RequireDigit = false; options.Password.RequireDigit = false;
@@ -74,11 +131,10 @@ builder.Services.Configure<IdentityOptions>(options =>
options.Password.RequireUppercase = false; options.Password.RequireUppercase = false;
}); });
builder.Services.AddControllersWithViews(); // Appens övriga tjänster
// Register your services
builder.Services.AddScoped<MenuService>(); builder.Services.AddScoped<MenuService>();
builder.Services.AddSingleton<PushNotificationService>(sp => builder.Services.AddScoped<PushNotificationService>(sp =>
{ {
var config = sp.GetRequiredService<IConfiguration>(); var config = sp.GetRequiredService<IConfiguration>();
return new PushNotificationService( return new PushNotificationService(
@@ -88,12 +144,20 @@ builder.Services.AddSingleton<PushNotificationService>(sp =>
); );
}); });
builder.Services.AddScoped<PizzaNotificationService>();
builder.Services.Configure<VapidOptions>(builder.Configuration.GetSection("Vapid")); builder.Services.Configure<VapidOptions>(builder.Configuration.GetSection("Vapid"));
builder.Services.ConfigureApplicationCookie(options => builder.Services.ConfigureApplicationCookie(options =>
{ {
options.LoginPath = "/Identity/Account/Login"; // korrekt för ditt nuvarande upplägg options.LoginPath = "/Identity/Account/Login";
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
options.Cookie.IsEssential = true;
}); });
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
builder.Services.Configure<RequestLocalizationOptions>(options => builder.Services.Configure<RequestLocalizationOptions>(options =>
{ {
var supportedCultures = new[] { new CultureInfo("sv-SE") }; var supportedCultures = new[] { new CultureInfo("sv-SE") };
@@ -101,60 +165,67 @@ builder.Services.Configure<RequestLocalizationOptions>(options =>
options.SupportedCultures = supportedCultures; options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures; options.SupportedUICultures = supportedCultures;
}); });
builder.Services.AddSingleton<SetupService>();
//builder.Configuration
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
// .AddEnvironmentVariables();
builder.Services.AddSingleton<PushNotificationService>(sp =>
{
var config = sp.GetRequiredService<IConfiguration>();
return new PushNotificationService(
config["VapidKeys:Subject"],
config["VapidKeys:PublicKey"],
config["VapidKeys:PrivateKey"]
);
});
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles(); app.UseStaticFiles();
// Middleware: om ej konfigurerad → redirect till /setup
app.Use(async (context, next) =>
{
var setupService = context.RequestServices.GetRequiredService<SetupService>();
var currentSetup = setupService.GetSetup();
var path = context.Request.Path;
var method = context.Request.Method;
if (!currentSetup.IsConfigured &&
!path.StartsWithSegments("/setup") &&
!(path == "/setup" && method == "POST") && // 👈 tillåt POST till /setup
!path.StartsWithSegments("/api/setup"))
{
context.Response.Redirect("/setup");
return;
}
await next();
});
app.UseRouting(); app.UseRouting();
app.UseSession(); app.UseSession();
app.UseAuthentication();; app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
// Map controller endpoints (including AJAX JSON actions) // Routing
app.MapControllers(); app.MapControllers();
// Conventional MVC route
app.MapControllerRoute( app.MapControllerRoute(
name: "default", name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); pattern: "{controller=Home}/{action=Index}/{id?}");
// Map Razor Pages
app.MapRazorPages(); app.MapRazorPages();
using (var scope = app.Services.CreateScope())
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseHsts();
// Init: migrera databas och skapa admin
if (setup.IsConfigured)
{ {
using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider; var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>(); var context = services.GetRequiredService<ApplicationDbContext>();
// Vänta tills databasen är redo
int retries = 10; int retries = 10;
while (retries > 0) while (retries > 0)
{ {
try try
{ {
context.Database.OpenConnection(); // bara testa öppna anslutningen context.Database.OpenConnection();
context.Database.CloseConnection(); context.Database.CloseConnection();
break; // lyckades! break;
} }
catch catch
{ {
@@ -164,17 +235,20 @@ using (var scope = app.Services.CreateScope())
} }
} }
// Kör alla EF-migrationer automatiskt
context.Database.Migrate(); context.Database.Migrate();
// Skapa standardroller och admin var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
await IdentityDataInitializer.SeedData(services); var anyUsers = await userManager.Users.AnyAsync();
// (valfritt) Lägg in exempelbudgetdata if (!anyUsers)
// await TestDataSeeder.SeedBudget(context); {
Console.WriteLine("🧩 Ingen användare hittades skapar admin...");
await IdentityDataInitializer.SeedData(services, setup);
}
}
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage(); // Detta ger stacktraces i browsern
} }
app.Run(); app.Run();

View File

@@ -8,7 +8,7 @@
} }
}, },
"profiles": { "profiles": {
"Aberwyn (Dev)": { "Aberwyn": {
"commandName": "Project", "commandName": "Project",
"launchBrowser": true, "launchBrowser": true,
"environmentVariables": { "environmentVariables": {
@@ -16,14 +16,6 @@
}, },
"applicationUrl": "https://localhost:7290;http://localhost:5290" "applicationUrl": "https://localhost:7290;http://localhost:5290"
}, },
"Aberwyn (Prod)": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
},
"applicationUrl": "https://localhost:7290;http://localhost:5290"
},
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
"launchBrowser": true, "launchBrowser": true,

View File

@@ -1,103 +1,236 @@
@model List<Aberwyn.Controllers.AdminUserViewModel> @model List<Aberwyn.Controllers.AdminUserViewModel>
<link rel="stylesheet" href="~/css/admin.css" />
<h2>Användarhantering</h2> <h2 class="mb-3">Adminpanel</h2>
<h3>Skapa ny roll</h3>
<form method="post" asp-action="CreateRole">
<div class="form-group">
<input type="text" name="roleName" class="form-control" placeholder="Namn på ny roll" required />
</div>
<button type="submit" class="btn btn-success mt-2">Skapa roll</button>
</form>
<h3>Skapa ny användare</h3>
@if (TempData["Message"] != null)
{
<div class="alert alert-success">@TempData["Message"]</div>
}
<form method="post" asp-action="CreateUser"> <div class="card mb-4">
<div class="form-group"> <div class="card-header">Roller och användare</div>
<label for="email">E-post:</label> <div class="card-body">
<input type="email" name="email" class="form-control" required /> <div class="row">
</div> <div>
<div class="form-group"> <h4>Skapa ny roll</h4>
<label for="password">Lösenord:</label> <form method="post" asp-action="CreateRole">
<input type="password" name="password" class="form-control" required /> <div class="form-group">
</div> <input type="text" name="roleName" class="form-control" placeholder="Namn på ny roll" required />
<button type="submit" class="btn btn-success mt-2">Skapa användare</button> </div>
</form> <button type="submit" class="btn btn-success mt-2">Skapa roll</button>
<hr />
<h4>Alla roller</h4>
<ul>
@foreach (var role in ViewBag.AllRoles as List<string>)
{
<li>@role</li>
}
</ul>
<table class="table">
<thead>
<tr>
<th>E-post</th>
<th>Roller</th>
<th>Lägg till roll</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.Email</td>
<td>
@foreach (var role in user.Roles)
{
<span>@role</span>
<form method="post" asp-action="RemoveFromRole" style="display:inline;">
<input type="hidden" name="userId" value="@user.UserId" />
<input type="hidden" name="role" value="@role" />
<button type="submit" class="btn btn-sm btn-danger">Ta bort</button>
</form> </form>
</div>
<div>
<h4>Skapa ny användare</h4>
@if (TempData["Message"] != null)
{
<div class="alert alert-success">@TempData["Message"]</div>
}
<form method="post" asp-action="CreateUser">
<div class="form-group">
<label for="email">E-post:</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label for="password">Lösenord:</label>
<input type="password" name="password" class="form-control" required />
</div>
<button type="submit" class="btn btn-success mt-2">Skapa användare</button>
</form>
</div>
</div>
</div>
</div>
<div class="card mb-4">
<div class="card-header">Befintliga roller och användare</div>
<div class="card-body">
<h5>Alla roller</h5>
<ul>
@foreach (var role in ViewBag.AllRoles as List<string>)
{
<li>@role</li>
} }
</td> </ul>
<td>
<form method="post" asp-action="AddToRole" class="form-inline">
<input type="hidden" name="userId" value="@user.UserId" />
<input type="text" name="role" class="form-control" placeholder="Rollnamn" />
<button type="submit" class="btn btn-sm btn-primary">Lägg till</button>
</form>
</td>
</tr>
}
</tbody>
</table>
<h3>Testa Pushnotis</h3> <table class="table">
<form onsubmit="sendPush(event)"> <thead>
<div class="form-group"> <tr>
<label for="title">Titel:</label> <th>E-post</th>
<input type="text" id="title" name="title" class="form-control" required /> <th>Roller</th>
<th>Lägg till roll</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.Email</td>
<td>
@foreach (var role in user.Roles)
{
<span>@role</span>
<form method="post" asp-action="RemoveFromRole" style="display:inline;">
<input type="hidden" name="userId" value="@user.UserId" />
<input type="hidden" name="role" value="@role" />
<button type="submit" class="btn btn-sm btn-danger">Ta bort</button>
</form>
}
</td>
<td>
<form method="post" asp-action="AddToRole" class="form-inline">
<input type="hidden" name="userId" value="@user.UserId" />
<input type="text" name="role" class="form-control" placeholder="Rollnamn" />
<button type="submit" class="btn btn-sm btn-primary">Lägg till</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div> </div>
<div class="form-group"> </div>
<label for="body">Meddelande:</label>
<input type="text" id="body" name="body" class="form-control" required /> <div class="card mb-4">
</div> <div class="card-header">Övriga funktioner</div>
<button type="submit" class="btn btn-warning mt-2">Skicka testnotis</button> <div class="card-body">
</form> <button class="btn btn-secondary mb-3" onclick="generateThumbnails()">🖼 Generera thumbnails</button>
<h4>Testa Pushnotis</h4>
<form onsubmit="sendPush(event)">
<div class="form-group">
<label for="title">Titel:</label>
<input type="text" id="title" name="title" class="form-control" required />
</div>
<div class="form-group">
<label for="body">Meddelande:</label>
<input type="text" id="body" name="body" class="form-control" required />
</div>
<button type="submit" class="btn btn-warning mt-2">Skicka testnotis</button>
</form>
<hr />
<h4>Skicka Pizza-notis</h4>
<button class="btn btn-danger mt-2" onclick="sendPizzaPush()">🍕 Skicka pizzanotis</button>
<div id="pizzaPushResult" class="mt-2"></div>
</div>
</div>
<div class="card mb-5">
<div class="card-header">Importera från annan databas</div>
<div class="card-body">
<form id="customDbForm">
<div class="form-group">
<label>Server:</label>
<input type="text" name="dbHost" class="form-control" required />
</div>
<div class="form-group">
<label>Port:</label>
<input type="number" name="dbPort" class="form-control" value="3306" required />
</div>
<div class="form-group">
<label>Databas:</label>
<input type="text" name="dbName" class="form-control" required />
</div>
<div class="form-group">
<label>Användarnamn:</label>
<input type="text" name="dbUser" class="form-control" required />
</div>
<div class="form-group">
<label>Lösenord:</label>
<input type="password" name="dbPassword" class="form-control" required />
</div>
</form>
<button class="btn btn-info mt-3" onclick="testDbConnection()">🔌 Testa anslutning</button>
<div id="testResult" class="mt-2"></div>
<button class="btn btn-primary mt-3" onclick="submitTo('ImportMealsFromCustom')">🍽 Importera måltider</button>
<button class="btn btn-primary mt-3" onclick="submitTo('ImportMenusFromCustom')">🗓 Importera menyer</button>
<button class="btn btn-primary mt-3" onclick="submitTo('ImportBudgetFromCustom')">💰 Importera budget</button>
</div>
</div>
<hr />
<h3>Importera måltider från produktion</h3>
<form method="post" asp-action="ImportMealsFromProd">
<button type="submit" class="btn btn-danger">Importera alla måltider</button>
</form>
<form method="post" asp-action="ImportMenusFromProd">
<button type="submit" class="btn btn-danger mt-2">Importera veckomenyer</button>
</form>
<form method="post" asp-action="ImportBudgetFromProd">
<button type="submit" class="btn btn-danger mt-2">Importera budgetdata</button>
</form>
<script> <script>
async function sendPizzaPush() {
const resultDiv = document.getElementById("pizzaPushResult");
resultDiv.innerText = "⏳ Skickar notis...";
try {
const response = await fetch("/api/push/notify-pizza", {
method: "POST"
});
const text = await response.text();
if (response.ok) {
resultDiv.className = "text-success mt-2";
resultDiv.innerText = "✅ " + text;
} else {
resultDiv.className = "text-danger mt-2";
resultDiv.innerText = "❌ Fel: " + text;
}
} catch (err) {
resultDiv.className = "text-danger mt-2";
resultDiv.innerText = "❌ Ett tekniskt fel uppstod.";
console.error(err);
}
}
function generateThumbnails() {
if (!confirm("Generera thumbnails för alla måltider som saknar?")) return;
fetch("/admin/GenerateThumbnails", {
method: "POST"
})
.then(res => res.text())
.then(msg => {
alert("✅ " + msg);
})
.catch(err => {
console.error("Fel vid generering av thumbnails:", err);
alert("❌ Ett fel uppstod vid generering av thumbnails.");
});
}
function collectFormData() {
const form = document.getElementById("customDbForm");
return new FormData(form); // 🔁 Byt ut till ren FormData istället för URLSearchParams
}
function submitTo(action) {
const data = collectFormData();
fetch(`/admin/${action}`, {
method: "POST",
body: data
})
.then(async res => {
const text = await res.text();
if (res.ok) {
alert(`✅ ${action} lyckades`);
} else {
alert(`❌ Fel vid ${action}:\n${text}`);
}
});
}
function testDbConnection() {
const data = collectFormData();
fetch(`/admin/TestDbConnection`, {
method: "POST",
body: data
})
.then(res => res.json())
.then(data => {
const div = document.getElementById("testResult");
div.innerText = data.message;
div.className = data.success ? "text-success mt-2" : "text-danger mt-2";
})
.catch(err => {
document.getElementById("testResult").innerText = "❌ Ett tekniskt fel uppstod.";
console.error(err);
});
}
async function sendPush(event) { async function sendPush(event) {
event.preventDefault(); // 🚫 stoppa formuläret från att göra vanlig POST event.preventDefault(); // 🚫 stoppa formuläret från att göra vanlig POST

View File

@@ -10,8 +10,31 @@
<script src="~/js/todo.js" asp-append-version="true"></script> <script src="~/js/todo.js" asp-append-version="true"></script>
<style> <style>
.todo-column input[type="text"],
.todo-column textarea,
.todo-column select {
width: 100%;
margin-top: 6px;
margin-bottom: 6px;
padding: 6px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
font-family: inherit;
font-size: 0.9em;
}
.todo-column textarea {
resize: vertical;
min-height: 60px;
}
.todo-column button {
margin-top: 10px;
width: 100%;
}
.todo-board { .todo-board {
padding: 20px;
font-family: sans-serif; font-family: sans-serif;
} }
.todo-columns { .todo-columns {
@@ -80,8 +103,18 @@
<div class="todo-task {{ PriorityClass(task.Priority) }}" <div class="todo-task {{ PriorityClass(task.Priority) }}"
ng-repeat="task in FilteredTasks(col.Id) track by task.Id" ng-repeat="task in FilteredTasks(col.Id) track by task.Id"
draggable-task draggable-task
task="task"> task="task"
{{ task.Title }} ng-if="!task.IsArchived">
<strong>{{ task.Title }}</strong>
<p ng-if="task.Description">{{ task.Description }}</p>
<div>
<small>🏷️ {{ task.Tags }}</small><br />
<small>📅 {{ task.CreatedAt | date:'yyyy-MM-dd HH:mm' }}</small>
</div>
<div> <div>
<small>Prioritet: <small>Prioritet:
<select ng-model="task.Priority" ng-change="UpdatePriority(task)"> <select ng-model="task.Priority" ng-change="UpdatePriority(task)">
@@ -93,8 +126,11 @@
</div> </div>
</div> </div>
<div ng-if="col.Id === 'ideas'"> <div ng-if="col.Id === 'ideas'">
<input type="text" ng-model="NewTask.Title" placeholder="Ny idé..." /> <input type="text" ng-model="NewTask.Title" placeholder="Ny idé..." />
<textarea ng-model="NewTask.Description" placeholder="Beskrivning"></textarea>
<input type="text" ng-model="NewTask.Tags" placeholder="Taggar (komma-separerat)" />
<select ng-model="NewTask.Priority"> <select ng-model="NewTask.Priority">
<option value="1">Låg</option> <option value="1">Låg</option>
<option value="2">Medel</option> <option value="2">Medel</option>
@@ -102,6 +138,7 @@
</select> </select>
<button type="button" ng-click="AddTask()">Lägg till</button> <button type="button" ng-click="AddTask()">Lägg till</button>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -5,187 +5,275 @@
ViewData["Title"] = "Budget"; ViewData["Title"] = "Budget";
} }
<div ng-app="budgetApp" ng-controller="BudgetController" class="budget-page" ng-init="loadBudget()"> <div ng-app="budgetApp" ng-controller="BudgetController">
<div class="budget-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;"> <div class="budget-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
<div class="month-nav-bar" style="display: flex; align-items: center; gap: 10px; position: relative;"> <div class="month-nav-bar" style="display: flex; align-items: center; gap: 10px; position: relative;">
<button class="nav-button" ng-click="previousMonth()">←</button> <button class="nav-button" ng-click="previousMonth()">←</button>
<span class="month-label" ng-click="showMonthPicker = !showMonthPicker" style="cursor: pointer;"> <span class="month-label" ng-click="showMonthPicker = !showMonthPicker" style="cursor: pointer;">
{{ selectedMonthName }} {{ selectedYear }} {{ selectedMonthName }} {{ selectedYear }}
</span> </span>
<button class="nav-button" ng-click="nextMonth()">→</button> <button class="nav-button" ng-click="nextMonth()">→</button>
<div class="month-picker-dropdown" ng-show="showMonthPicker" style="position: absolute; top: 100%; left: 50%; transform: translateX(-50%); background: white; border: 1px solid #ccc; padding: 10px; border-radius: 8px; z-index: 1000; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"> <div class="month-picker-dropdown" ng-show="showMonthPicker" style="position: absolute; top: 100%; left: 50%; transform: translateX(-50%); background: white; border: 1px solid #ccc; padding: 10px; border-radius: 8px; z-index: 1000; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
<select ng-model="tempMonth" ng-options="month for month in monthNames" style="margin-bottom: 8px;"></select><br> <select ng-model="tempMonth" ng-options="month for month in monthNames" style="margin-bottom: 8px;"></select><br>
<input type="number" ng-model="tempYear" placeholder="År" style="width: 100%; margin-bottom: 8px;" /> <input type="number" ng-model="tempYear" placeholder="År" style="width: 100%; margin-bottom: 8px;" />
<button class="nav-button" ng-click="applyMonthSelection()">Välj</button> <button class="nav-button" ng-click="applyMonthSelection()">Välj</button>
</div>
</div>
<div class="menu-container" ng-class="{ 'open': menuOpen }">
<button class="icon-button" ng-click="toggleMenu($event)">
<i class="fa fa-ellipsis-v"></i>
</button>
<div class="dropdown-menu" ng-show="menuOpen">
<button ng-click="copyPreviousMonthSafe()">Kopiera föregående månad</button>
<button ng-click="deleteMonth(); menuOpen = false;" class="danger">Ta bort hela månaden</button>
<button ng-click="createNewCategory(); menuOpen = false;">Lägg till ny kategori</button>
</div>
</div>
</div>
<div class="summary-cards" ng-if="budget && budget.categories.length > 0" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin: 24px 0;">
<div class="summary-card income">Totalt inkomst<br><strong>{{ getTotalIncome() | number:0 }}</strong></div>
<div class="summary-card expense">Total utgift<br><strong>({{ getTotalExpense() | number:0 }})</strong></div>
<div class="summary-card savings">Sparande<br><strong>{{ getTotalSaving() | number:0 }}</strong></div>
<div class="summary-card leftover">Pengar kvar<br><strong>{{ getLeftover() | number:0 }}</strong></div>
</div>
<div class="budget-grid" ng-if="budget && budget.categories">
<div class="budget-card"
ng-repeat="cat in budget.categories"
style="--cat-color: {{cat.color}};"
draggable-category
category="cat"
on-category-drop="handleCategoryDrop(data, targetCategory)">
<div class="card-header" style="background-color: {{cat.color}};">
<div class="header-left" ng-if="!cat.editing">{{ cat.name }}</div>
<input class="header-edit" type="text" ng-model="cat.name" ng-if="cat.editing" />
<input class="color-edit" type="color" ng-model="cat.color" ng-if="cat.editing" />
<div class="header-actions">
<button class="icon-button" ng-click="cat.editing ? saveCategory(cat) : cat.editing = true">
<i ng-class="{'fa fa-check': cat.editing, 'fa fa-pencil': !cat.editing}"></i>
</button>
<button class="icon-button" ng-if="cat.editing" ng-click="cancelCategoryEdit(cat)">
<i class="fa fa-times"></i>
</button>
<button class="icon-button" ng-if="cat.editing" ng-click="cat.allowDrag = !cat.allowDrag" title="Flytt av kategori">
<i class="fa" ng-class="cat.allowDrag ? 'fa-unlock' : 'fa-lock'"></i>
</button>
<button class="icon-button danger" ng-if="cat.editing" ng-click="deleteCategory(cat)">
<i class="fa fa-trash"></i>
</button>
</div> </div>
</div> </div>
<div class="item-list">
<div ng-repeat="item in cat.items track by item.id"> <div class="menu-container" ng-class="{ 'open': menuOpen }">
<div drop-placeholder <button class="icon-button" ng-click="toggleMenu($event)">
category="cat" <i class="fa fa-ellipsis-v"></i>
index="$index" </button>
on-drop-item="handleItemPreciseDrop(data, cat, $index)"> <div class="dropdown-menu" ng-show="menuOpen">
<button ng-click="copyPreviousMonthSafe()">Kopiera föregående månad</button>
<button ng-click="deleteMonth(); menuOpen = false;" class="danger">Ta bort hela månaden</button>
<button ng-click="createNewCategory(); menuOpen = false;">Lägg till ny kategori</button>
<!--<button ng-click="openImportModule(); menuOpen = false;">📥 Importera rader</button> -->
</div>
</div>
</div>
<div class="budget-overview-row" ng-if="budget && budget.categories.length > 0">
<!-- Vänster: Summering -->
<div class="budget-summary-box compact">
<h3>Sammanställning</h3>
<ul class="summary-list">
<li><span>💰 Inkomst:</span> {{ getTotalIncome() | number:0 }} kr</li>
<li><span>💸 Utgift:</span> {{ getTotalExpense() | number:0 }} kr</li>
<li><span>🏦 Sparande:</span> {{ getTotalSaving() | number:0 }} kr</li>
<p>
📈 Kvar:
<span class="highlight leftover" ng-class="{'plus': getLeftover() >= 0, 'minus': getLeftover() < 0}">
{{ getLeftover() | number:0 }} kr
</span>
</p>
</ul>
<hr>
<ul class="category-summary-list">
<li ng-repeat="cat in budget.categories">
<span style="color: {{ cat.color }}">{{ cat.name }}</span>
<span>{{ getCategorySum(cat) | number:0 }} kr</span>
</li>
</ul>
</div>
<!-- Höger: Diagramväxling -->
<div class="budget-chart-box compact">
<div class="chart-row">
<div class="chart-legend">
<h4>Utgifter</h4>
<p style="font-size: 12px; margin: 4px 0 10px;">
Totalt: <strong>{{ getTotalExpense() | number:0 }} kr</strong>
</p>
<p ng-if="topExpenseCategory" style="font-size: 12px; margin-bottom: 12px;">
Största kategori: <br>
<strong>{{ topExpenseCategory.name }}</strong> ({{ topExpenseCategory.percent | number:1 }}%)
</p>
</div>
<div class="chart-area">
<canvas id="expenseChart"></canvas>
</div>
</div>
</div>
</div>
<div class="budget-grid" ng-if="budget && budget.categories">
<div class="budget-card"
ng-repeat="cat in budget.categories"
style="--cat-color: {{cat.color}};"
draggable-category
category="cat"
on-category-drop="handleCategoryDrop(data, targetCategory)">
<div class="card-header" style="background-color: {{cat.color}};">
<div class="header-left" ng-if="!cat.editing" >{{ cat.name }}</div>
<input class="header-edit" type="text" ng-model="cat.name" ng-if="cat.editing" />
<input class="color-edit" type="color" ng-model="cat.color" ng-if="cat.editing" />
<div class="header-actions">
<button class="icon-button" ng-click="cat.editing ? saveCategory(cat) : cat.editing = true">
<i ng-class="{'fa fa-check': cat.editing, 'fa fa-pencil': !cat.editing}"></i>
</button>
<button class="icon-button" ng-if="cat.editing" ng-click="cancelCategoryEdit(cat)">
<i class="fa fa-times"></i>
</button>
<button class="icon-button" ng-if="cat.editing" ng-click="cat.allowDrag = !cat.allowDrag" title="Flytt av kategori">
<i class="fa" ng-class="cat.allowDrag ? 'fa-unlock' : 'fa-lock'"></i>
</button>
<button class="icon-button danger" ng-if="cat.editing" ng-click="deleteCategory(cat)">
<i class="fa fa-trash"></i>
</button>
</div> </div>
</div>
<div class="item-row" <div class="item-list">
draggable-item <div ng-repeat="item in cat.items track by item.id">
item="item" <div drop-placeholder
category="cat" category="cat"
on-item-drop="handleItemDrop(event, data, cat)" index="$index"
ng-class="{ dragging: dragInProgress && draggedItemId === item.id }"> on-drop-item="handleItemPreciseDrop(data, cat, $index)">
<i class="fa fa-grip-lines drag-handle" </div>
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" /> <div class="item-row"
<span ng-if="!cat.editing" title="{{ item.definitionName }}">{{ item.name }}</span> draggable-item
<!-- <span ng-if="!cat.editing">#{{ item.definitionName }}</span>--> item="item"
<input type="number" ng-model="item.amount" ng-if="cat.editing" /> category="cat"
<span class="amount" ng-if="!cat.editing">{{ item.amount | number:0 }}</span> on-item-drop="handleItemDrop(event, data, cat)"
ng-class="{
dragging: dragInProgress && draggedItemId === item.id,
due: item.paymentStatus === 1,
paid: item.paymentStatus === 2
}"
ng-click="handleItemInteraction($event, item)">
<i class="fa fa-grip-lines drag-handle"
ng-show="cat.editing"
style="opacity: 0.5; padding-right: 6px; cursor: grab;"></i>
<!-- 3-pricksmeny --> <input type="text" class="item-label" ng-model="item.name" ng-if="cat.editing" />
<div class="item-menu-container" ng-if="cat.editing" style="position: relative;"> <span ng-if="!cat.editing" class="item-label" title="{{ item.name }}">{{ item.name }}</span>
<button class="icon-button" ng-click="openItemMenu($event, item)"> <input type="number" ng-model="item.amount" ng-if="cat.editing" />
<i class="fa fa-ellipsis-v"></i> <span class="amount" ng-if="!cat.editing">{{ item.amount | number:0 }}</span>
</button>
<div class="item-floating-menu" ng-show="menuVisible" ng-style="menuStyle"> <!-- 3-pricksmeny -->
<span style="font-size: 11px; color: #94a3b8; display: block; margin: 0px 0px 0px 40px;"> <div class="item-menu-container" ng-if="cat.editing" style="position: relative;">
#{{ menuItem.definitionName }} <button class="icon-button" ng-click="openItemMenu($event, item)">
</span> <i class="fa fa-ellipsis-v"></i>
<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> </button>
<div class="item-floating-menu" ng-show="menuVisible" ng-style="menuStyle">
<span style="font-size: 11px; color: #94a3b8; display: block; margin: 0px 0px 0px 40px;">
#{{ menuItem.definitionName }}
</span>
<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> </div>
</div> </div>
<div drop-fallback
ng-if="cat.editing"
category="cat"
on-drop-item="handleItemPreciseDrop(data, targetCategory, targetIndex)">
</div>
<button class="icon-button add-post-btn"
ng-if="cat.editing && !cat.addingItem"
ng-click="openItemPopup($event, cat)">
Lägg till post
</button>
</div> </div>
<div drop-fallback <div class="item-row total-row">
ng-if="cat.editing" <div>Summa</div>
category="cat" <div class="amount">{{ getCategorySum(cat) | number:0 }}</div>
on-drop-item="handleItemPreciseDrop(data, targetCategory, targetIndex)">
</div> </div>
<button class="icon-button add-post-btn"
ng-if="cat.editing && !cat.addingItem"
ng-click="openItemPopup($event, cat)">
Lägg till post
</button>
</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>
</div> </div>
</div> </div>
</div> <div class="no-data" ng-if="!loading && budget && budget.categories.length === 0">
<p>Det finns ingen budgetdata för
<strong>{{ budget.name || (selectedMonth + '/' + selectedYear) }}</strong>.
</p>
<div style="margin-top: 10px;">
<button ng-click="createEmptyBudget()" style="margin-right: 10px;">
Skapa ny budget
</button>
<button ng-click="copyPreviousMonthSafe()">
Kopiera föregående månad
</button>
</div>
</div>
<div class="add-item-popup" ng-show="addPopupVisible" ng-style="addPopupStyle" ng-class="{ 'above': addPopupAbove }">
<label>Typ:</label>
<select ng-model="addPopupData.newItemType">
<option value="expense">💸 Utgift</option>
<option value="income">💰 Inkomst</option>
<option value="saving">🏦 Sparande</option>
</select>
<div class="add-item-popup" ng-show="addPopupVisible" ng-style="addPopupStyle" ng-class="{ 'above': addPopupAbove }"> <label>Definition:</label>
<label>Typ:</label> <input type="text"
<select ng-model="addPopupData.newItemType"> ng-model="addPopupData.newItemDefinition"
<option value="expense">💸 Utgift</option> ng-change="updateDefinitionSuggestions()"
<option value="income">💰 Inkomst</option> placeholder="Ex: Elhandel"
<option value="saving">🏦 Sparande</option> autocomplete="on"
</select> ng-blur="hideSuggestionsDelayed()"
ng-focus="showDefinitionSuggestions = true" />
<p style="color: red">{{ filteredDefinitions.length }} träffar</p>
<ul class="suggestion-list" ng-show="showDefinitionSuggestions && filteredDefinitions.length > 0">
<li ng-repeat="suggestion in filteredDefinitions"
ng-mousedown="selectDefinitionSuggestion(suggestion.Name)">
{{ suggestion.Name }}
</li>
</ul>
<label>Definition:</label> <label>Etikett (valfritt):</label>
<input type="text" <input type="text" ng-model="addPopupData.newItemLabel" placeholder="Ex: Däck till Volvon" />
ng-model="addPopupData.newItemDefinition"
ng-change="updateDefinitionSuggestions()"
placeholder="Ex: Elhandel"
autocomplete="on"
ng-blur="hideSuggestionsDelayed()"
ng-focus="showDefinitionSuggestions = true" />
<p style="color: red">{{ filteredDefinitions.length }} träffar</p>
<ul class="suggestion-list" ng-show="showDefinitionSuggestions && filteredDefinitions.length > 0">
<li ng-repeat="suggestion in filteredDefinitions"
ng-mousedown="selectDefinitionSuggestion(suggestion.Name)">
{{ suggestion.Name }}
</li>
</ul>
<label>Etikett (valfritt):</label> <label>Belopp:</label>
<input type="text" ng-model="addPopupData.newItemLabel" placeholder="Ex: Däck till Volvon" /> <input type="number" ng-model="addPopupData.newItemAmount" placeholder="0" />
<label>Belopp:</label> <button ng-click="addItemFromPopup()">Lägg till</button>
<input type="number" ng-model="addPopupData.newItemAmount" placeholder="0" /> <button ng-click="addPopupVisible = false">Avbryt</button>
</div>
<button ng-click="addItemFromPopup()">Lägg till</button> <div class="import-module" ng-show="importing" style="position: fixed; top: 10vh; left: 50%; transform: translateX(-50%);
<button ng-click="addPopupVisible = false">Avbryt</button> background: #1F2C3C; color: white; padding: 24px; border-radius: 8px; z-index: 2000; width: 90%; max-width: 600px;
</div> box-shadow: 0 10px 30px rgba(0,0,0,0.4);">
<h3 style="margin-top: 0;">📥 Importera rader till {{ importTargetCategory.name }}</h3>
<label for="importText">Klistra in rader (en per rad, t.ex. <code>Kallhyra 11315</code>):</label>
<textarea id="importText" ng-model="importText" rows="6" style="width: 100%; margin-bottom: 10px;"></textarea>
<button ng-click="parseImportText()">Förhandsgranska</button>
<button ng-click="cancelImport()">Avbryt</button>
<div class="preview-list" ng-if="importPreview.length > 0" style="margin-top: 16px;">
<h4>Förhandsvisning:</h4>
<div class="item-row" ng-repeat="item in importPreview">
<span class="item-label">{{ item.name }}</span>
<span class="amount">{{ item.amount | number:0 }} kr</span>
</div>
<button ng-click="applyImport()">✔️ Skapa {{ importPreview.length }} rader</button>
</div>
</div>
</div>
</div>
<link rel="stylesheet" href="~/css/budget.css" /> <link rel="stylesheet" href="~/css/budget.css" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
<script>
window.initialYear = @(ViewBag.Year ?? "null");
window.initialMonth = @(ViewBag.Month ?? "null");
window.initialName = "@(ViewBag.BudgetName ?? "")";
</script>
<script src="~/js/budget.js"></script> <script src="~/js/budget.js"></script>
<script src="~/js/budget-dragdrop.js"></script> <script src="~/js/budget-dragdrop.js"></script>

View File

@@ -0,0 +1,75 @@
@{
Layout = "_Layout";
var errorCode = ViewData["ErrorCode"] as int?;
var exception = ViewData["Exception"] as Exception;
var isDebug = System.Diagnostics.Debugger.IsAttached;
}
<style>
.error-page {
max-width: 600px;
margin: 4rem auto;
padding: 2rem;
background-color: #1F2C3C;
color: white;
border-radius: 16px;
box-shadow: 0 0 10px rgba(0,0,0,0.4);
font-family: 'Segoe UI', sans-serif;
}
.error-page h1 {
font-size: 2.2rem;
margin-bottom: 1rem;
color: #f87171;
}
.error-page .code {
font-size: 1.5rem;
margin-bottom: 1rem;
color: #facc15;
}
.error-page pre {
background-color: #2E3C4F;
padding: 1rem;
border-radius: 8px;
overflow-x: auto;
margin-top: 1rem;
color: #fefefe;
font-size: 0.95rem;
}
.error-page details summary {
cursor: pointer;
color: #6a0dad;
margin-top: 1rem;
font-weight: bold;
}
.error-page p {
margin-top: 0.5rem;
}
</style>
<div class="error-page">
<h1>🚨 Något gick fel</h1>
<a href="/" class="btn-outline">Till startsidan</a>
@if (errorCode.HasValue)
{
<div class="code">Statuskod: <strong>@errorCode</strong></div>
}
@if (exception != null)
{
<h3>Felmeddelande:</h3>
<pre>@exception.Message</pre>
@if (isDebug)
{
<details>
<summary>Visa stacktrace</summary>
<pre>@exception.StackTrace</pre>
</details>
}
}
else
{
<p>Vi kunde tyvärr inte visa sidan. Det kan bero på ett tillfälligt fel.</p>
}
</div>

View File

@@ -3,7 +3,7 @@
@{ @{
ViewData["Title"] = "Pizza Admin"; ViewData["Title"] = "Pizza Admin";
var availablePizzas = Model.AvailablePizzas as List<Meal> ?? new List<Meal>(); var availablePizzas = Model.AvailablePizzas as List<Meal> ?? new List<Meal>();
var restaurantOpen = ViewBag.RestaurantOpen as bool? ?? true; var restaurantOpen = ViewBag.RestaurantIsOpen as bool? ?? false;
} }
<link rel="stylesheet" href="~/css/pizza-admin.css" /> <link rel="stylesheet" href="~/css/pizza-admin.css" />

View File

@@ -2,7 +2,7 @@
@using Newtonsoft.Json.Serialization @using Newtonsoft.Json.Serialization
@{ @{
ViewData["Title"] = "Beställ pizza"; ViewData["Title"] = "Beställ pizza";
var pizzas = ViewBag.Pizzas as List<Meal>; var pizzas = ViewBag.Pizzas as List<MealListDto> ?? new List<MealListDto>();
var previousOrder = ViewBag.PreviousOrder as PizzaOrder; var previousOrder = ViewBag.PreviousOrder as PizzaOrder;
var lastId = Context.Session.GetInt32("LastPizzaOrderId"); var lastId = Context.Session.GetInt32("LastPizzaOrderId");
var isCurrentOrder = previousOrder?.Id == lastId; var isCurrentOrder = previousOrder?.Id == lastId;

View File

@@ -143,8 +143,9 @@
</aside> </aside>
<datalist id="meals-list"> <datalist id="meals-list">
@foreach (var m in ViewBag.AvailableMeals as List<Aberwyn.Models.Meal>) { @foreach (var meal in (List<Meal>)ViewBag.AvailableMeals)
<option value="@m.Name" /> {
<option value="@meal.Name">@meal.Name</option>
} }
</datalist> </datalist>
</form> </form>

View File

@@ -7,16 +7,21 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" ng-app="budgetApp"> <html lang="en" ng-app="budgetApp">
<head> <head>
<style>
[ng-cloak] {
display: none !important;
}
</style>
<meta charset="utf-8"> <meta charset="utf-8">
<title>Budget Overview</title> <title>Budget Overview</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="~/css/budget.css"> <link rel="stylesheet" type="text/css" href="~/css/budget.css">
</head> </head>
<body ng-controller="BudgetController"> <body ng-controller="BudgetController" ng-cloak>
<div class="budget-page"> <div class="budget-page">
<h1>Budget Overview</h1> <h1 ng-cloak>Budget Overview</h1>
<div class="date-picker" ng-click="toggleDatePicker($event)"> <div class="date-picker" ng-click="toggleDatePicker($event)">
<button type="button" class="date-picker-toggle"> <button type="button" class="date-picker-toggle">
@@ -28,7 +33,11 @@
</div> </div>
</div> </div>
<div class="budget-container"> <div ng-if="isLoadingBudget" class="loading-indicator">
⏳ Laddar budget...
</div>
<div ng-if="!isLoadingBudget" class="budget-container">
<div ng-repeat="category in categories" class="category-block"> <div ng-repeat="category in categories" class="category-block">
<div class="category-header"> <div class="category-header">
{{ category }} {{ category }}
@@ -55,7 +64,7 @@
angular.module('budgetApp', []) angular.module('budgetApp', [])
.controller('BudgetController', function ($scope, $http) { .controller('BudgetController', function ($scope, $http) {
const today = new Date(); const today = new Date();
$scope.isLoadingBudget = true;
// Initialize months and years // Initialize months and years
$scope.months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; $scope.months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
$scope.years = [...Array(11).keys()].map(i => today.getFullYear() - 10 + i); $scope.years = [...Array(11).keys()].map(i => today.getFullYear() - 10 + i);
@@ -72,11 +81,16 @@
// Automatically filter when month or year changes // Automatically filter when month or year changes
$scope.filterBudget = function () { $scope.filterBudget = function () {
$scope.isLoadingBudget = true;
$http.get('/api/budgetapi/items', { $http.get('/api/budgetapi/items', {
params: { month: $scope.selectedMonth, year: $scope.selectedYear } params: { month: $scope.selectedMonth, year: $scope.selectedYear }
}).then(response => { }).then(response => {
$scope.budgetItems = response.data; $scope.budgetItems = response.data;
}).catch(error => console.error("Error fetching budget items:", error)); $scope.isLoadingBudget = false;
}).catch(error => {
console.error("Error fetching budget items:", error);
$scope.isLoadingBudget = false;
});
}; };
$scope.getItemsByCategory = function (category) { $scope.getItemsByCategory = function (category) {

View File

@@ -1,18 +1,111 @@
@{ @model Aberwyn.Models.WeeklyMenu
ViewData["Title"] = "Welcome to Lewel!"; @{
var showDate = (DateTime)ViewBag.ShowDate;
var day = showDate.ToString("dddd", new System.Globalization.CultureInfo("sv-SE"));
}
<link rel="stylesheet" href="~/css/Welcome.css" />
<section class="welcome-section light-mode">
<div class="welcome-content">
<h1 class="welcome-title">Välkommen till
<span class="initial L">L</span>
<span class="initial E">E</span>
<span class="initial W">W</span>
<span class="initial E2">E</span>
<span class="initial L2">L</span></h1>
<p class="welcome-subtitle">Meny för <strong>@day</strong> är:</p>
@if (Model != null)
{
<div class="meal-lines">
@if (!string.IsNullOrWhiteSpace(Model.BreakfastMealName)) {
<div class="meal-line">
<p><strong>Frukost:</strong>
<a href="/meal/view/@Model.BreakfastMealId">@Model.BreakfastMealName</a>
</p>
@if (Model.BreakfastThumbnail != null)
{
var b64 = Convert.ToBase64String(Model.BreakfastThumbnail);
<div class="meal-large-thumb-container">
<img class="meal-large-thumb" src="data:image/jpeg;base64,@b64" alt="@Model.BreakfastMealName" />
</div>
}
</div>
} }
<!DOCTYPE html> @if (!string.IsNullOrWhiteSpace(Model.LunchMealName)) {
<html lang="en"> <div class="meal-line">
<head> <p><strong>Lunch:</strong>
<meta charset="utf-8"> <a href="/meal/view/@Model.LunchMealId">@Model.LunchMealName</a>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> </p>
<title>@ViewData["Title"]</title> @if (Model.LunchThumbnail != null)
{
</head> var b64 = Convert.ToBase64String(Model.LunchThumbnail);
<body> <div class="meal-large-thumb-container">
<div class="container"> <img class="meal-large-thumb" src="data:image/jpeg;base64,@b64" alt="@Model.LunchMealName" />
<h1>Välkommen</h1> Kika på <a href="/Home/Menu" class="button">Menyn</a> om du vill. </div>
}
</div> </div>
</body> }
</html>
@if (!string.IsNullOrWhiteSpace(Model.DinnerMealName)) {
<div class="meal-line">
<p><strong>Middag:</strong>
<a href="/meal/view/@Model.DinnerMealId">@Model.DinnerMealName</a>
</p>
@if (Model.DinnerThumbnail != null)
{
var b64 = Convert.ToBase64String(Model.DinnerThumbnail);
<div class="meal-large-thumb-container">
<img class="meal-large-thumb" src="data:image/jpeg;base64,@b64" alt="@Model.DinnerMealName" />
</div>
}
</div>
}
@if (ViewBag.RestaurantIsOpen as bool? == true)
{
<p><strong>Pizzerian är öppen!</strong></p>
<a asp-controller="FoodMenu" asp-action="PizzaOrder">Klicka här för att Beställa pizza</a>
}
</div>
}
else
{
<p class="no-menu">Ingen meny är inlagd för denna dag.</p>
}
<a class="nav-button" href="/Home/Menu">Visa hela veckomenyn</a>
</div>
</section>
<div id="lightboxOverlay" class="lightbox-overlay" onclick="hideLargeImage()" style="display:none;">
<div class="lightbox-content" onclick="event.stopPropagation()">
<button class="close-lightbox" onclick="hideLargeImage()">×</button>
<img id="lightboxImage" class="lightbox-image" src="" alt="Meal image" />
<p id="lightboxCaption" class="lightbox-caption"></p>
</div>
</div>
<script>
function showLargeImage(base64Data, caption) {
const overlay = document.getElementById("lightboxOverlay");
const image = document.getElementById("lightboxImage");
const text = document.getElementById("lightboxCaption");
image.src = `data:image/jpeg;base64,${base64Data}`;
text.textContent = caption || '';
overlay.style.display = "flex";
document.body.classList.add("no-scroll");
}
function hideLargeImage() {
document.getElementById("lightboxOverlay").style.display = "none";
document.body.classList.remove("no-scroll");
}
document.addEventListener('keydown', function (e) {
if (e.key === "Escape") hideLargeImage();
});
</script>

View File

@@ -32,13 +32,13 @@
<div class="day-header">{{day}}</div> <div class="day-header">{{day}}</div>
<div class="meal-info" ng-if="menu[day]"> <div class="meal-info" ng-if="menu[day]">
<div ng-if="menu[day].breakfastMealId" class="meal-selection"> <div ng-if="menu[day].breakfastMealId" class="meal-selection">
<a href="/Meal/View/{{menu[day].breakfastMealId}}" target="_blank"><strong>Frukost:</strong> {{menu[day].breakfastMealName}}</a> <a href="/Meal/View/{{menu[day].breakfastMealId}}"><strong>Frukost:</strong> {{menu[day].breakfastMealName}}</a>
</div> </div>
<div ng-if="menu[day].lunchMealId" class="meal-selection"> <div ng-if="menu[day].lunchMealId" class="meal-selection">
<a href="/Meal/View/{{menu[day].lunchMealId}}" target="_blank"><strong>Lunch:</strong> {{menu[day].lunchMealName}}</a> <a href="/Meal/View/{{menu[day].lunchMealId}}"><strong>Lunch:</strong> {{menu[day].lunchMealName}}</a>
</div> </div>
<div ng-if="menu[day].dinnerMealId" class="meal-selection"> <div ng-if="menu[day].dinnerMealId" class="meal-selection">
<a href="/Meal/View/{{menu[day].dinnerMealId}}" target="_blank"><strong>Middag:</strong> {{menu[day].dinnerMealName}}</a> <a href="/Meal/View/{{menu[day].dinnerMealId}}"><strong>Middag:</strong> {{menu[day].dinnerMealName}}</a>
</div> </div>
</div> </div>
<div ng-if="!menu[day]"> <div ng-if="!menu[day]">
@@ -56,16 +56,38 @@
ng-click="openMeal(getMealIdByDay(day))"> ng-click="openMeal(getMealIdByDay(day))">
<div class="card-content"> <div class="card-content">
<div class="day">{{day}}</div> <div class="day">{{day}}</div>
<div class="meal" ng-if="menu[day].breakfastMealName">Frukost: {{menu[day].breakfastMealName}}</div>
<div class="meal" ng-if="menu[day].lunchMealName">Lunch: {{menu[day].lunchMealName}}</div>
<div class="meal" ng-if="menu[day].dinnerMealName">Middag: {{menu[day].dinnerMealName}}</div> <div class="meal" ng-if="menu[day].dinnerMealName">Middag: {{menu[day].dinnerMealName}}</div>
<div class="meal" ng-if="!menu[day]">Inte bestämd</div> <div class="meal" ng-if="menu[day].lunchMealName">Lunch: {{menu[day].lunchMealName}}</div>
<div class="meal" ng-if="menu[day].breakfastMealName">Frukost: {{menu[day].breakfastMealName}}</div>
<div class="meal" ng-if="menu[day] && !menu[day].breakfastMealName && !menu[day].lunchMealName && !menu[day].dinnerMealName">Inte bestämd</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> <!--
<div class="school-meals card-view">
<h2>Skolmat</h2>
<div ng-repeat="school in schoolMealsBySchool">
<div class="school-meal-title" ng-click="toggleSchoolExpanded(school)">
<span class="chevron" ng-class="{ rotated: school.expanded }">&#x25BC;</span>
{{ school.name }}
</div>
<div class="card-container" ng-show="school.expanded">
<div class="meal-card" ng-repeat="day in school.days">
<div class="card-content school-meal-card-content">
<div class="day">{{ day.weekday }}</div>
<div class="meal" ng-repeat="meal in day.courses">{{ meal }}</div>
</div>
</div>
</div>
</div>
</div>
-->
</div> </div>
</body> </body>
</html> </html>

View File

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>Offline</title>
<style>
body { font-family: sans-serif; text-align: center; padding: 2rem; background: #1F2C3C; color: white; }
</style>
</head>
<body>
<h1>🌐 Du är offline</h1>
<p>LEWEL är inte tillgänglig just nu. Kontrollera din internetanslutning och försök igen.</p>
</body>
</html>

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Aberwyn.Views.Home
{
public class OfflineModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@@ -0,0 +1,89 @@
<!DOCTYPE html>
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
bool isChef = HttpContextAccessor.HttpContext.User.IsInRole("Chef");
}
<html lang="sv" ng-app="mealGalleryApp">
<head>
<meta charset="utf-8">
<title>Måltider</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<link rel="stylesheet" href="/css/meal-gallery.css">
<script src="https://kit.fontawesome.com/yourkit.js" crossorigin="anonymous"></script>
<style>
*, *::before, *::after { box-sizing: border-box; }
body { overflow-x: hidden; }
</style>
</head>
<body ng-controller="MealGalleryController">
<div class="meal-gallery-container">
<div class="meal-gallery-header">
<h1>Recept</h1>
<div class="search-container">
<input type="text" ng-model="search" placeholder="Sök recept..." />
<i class="fa-solid fa-magnifying-glass"></i>
@if (isChef)
{
<label class="toggle-published">
<input type="checkbox" ng-model="includeUnpublished" ng-change="reloadMeals()" />
<span>Visa alla</span>
</label>
<a href="/meal/view?edit=true" class="btn-create-meal">+ Ny rätt</a>
}
</div>
</div>
<div class="meal-gallery-grid">
<div class="meal-card"
ng-repeat="meal in (meals | filter:search) | limitTo:visibleCount track by meal.Id">
<img ng-src="{{ meal.ThumbnailData ? 'data:image/webp;base64,' + meal.ThumbnailData : '/images/fallback.jpg' }}"
alt="{{ meal.Name }}">
<div class="meal-card-content">
<h3>{{ meal.Name }}</h3>
<p ng-if="meal.Description">{{ meal.Description }}</p>
<a class="btn-readmore" ng-href="/meal/view/{{ meal.Id }}">Läs mer</a>
</div>
</div>
</div>
</div>
<script>
angular.module("mealGalleryApp", []).controller("MealGalleryController", function ($scope, $http) {
$scope.meals = [];
$scope.search = "";
$scope.visibleCount = 12;
$scope.includeUnpublished = false;
$scope.reloadMeals = function () {
const url = `/api/mealMenuApi/getPublishedMeals?includeUnpublished=${$scope.includeUnpublished}`;
$http.get(url).then(res => {
$scope.meals = res.data;
});
};
$scope.reloadMeals();
window.addEventListener('scroll', function () {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 150) {
$scope.$applyAsync(() => {
$scope.visibleCount += 8;
});
}
});
$scope.$watch('search', function (newVal) {
$scope.visibleCount = newVal ? 9999 : 12;
});
});
</script>
</body>
</html>

View File

@@ -0,0 +1,173 @@
@model Aberwyn.Models.RecipeLabEntry
@{
ViewData["Title"] = "Matlabb";
}
<link rel="stylesheet" href="/css/lab.css" />
<div class="lab-container">
<!-- Vänster: formulär för labb-entry -->
<div class="lab-main">
<h2>Matlabb @(string.IsNullOrEmpty(Model.Title) ? "Ny" : Model.Title)</h2>
<form asp-action="SaveLabEntry" method="post">
<input type="hidden" name="Id" value="@Model.Id" />
<div class="lab-form-group">
<label>Titel</label>
<input type="text" name="Title" value="@Model.Title" class="lab-input" required />
</div>
<div class="lab-form-group">
<label>Inspiration</label>
<input type="text" name="Inspiration" value="@Model.Inspiration" class="lab-input" />
</div>
<div class="lab-form-group">
<label>Anteckningar</label>
<textarea name="Notes" class="lab-textarea">@Model.Notes</textarea>
</div>
<div class="lab-form-group">
<label>Taggar</label>
<input type="text" name="Tags" value="@Model.Tags" class="lab-input" />
</div>
<button type="submit" class="lab-save-button">Spara labb</button>
</form>
@if (Model.Id > 0)
{
<hr />
<!-- Ingredienser sektion -->
<h3>Ingredienser</h3>
<div id="ingredients-section">
<form asp-action="SaveLabIngredients" method="post">
<input type="hidden" name="RecipeLabEntryId" value="@Model.Id" />
<div id="ingredients-list">
@if (Model.Ingredients?.Any() == true)
{
@for (int i = 0; i < Model.Ingredients.Count; i++)
{
<div class="ingredient-row">
<input type="text" name="Ingredients[@i].Quantity" value="@Model.Ingredients[i].Quantity" placeholder="Mängd" class="lab-input" />
<input type="text" name="Ingredients[@i].Item" value="@Model.Ingredients[i].Item" placeholder="Ingrediens" class="lab-input" />
<button type="button" class="remove-ingredient" onclick="removeIngredient(this)">Ta bort</button>
</div>
}
}
else
{
<div class="ingredient-row">
<input type="text" name="Ingredients[0].Quantity" placeholder="Mängd" class="lab-input" />
<input type="text" name="Ingredients[0].Item" placeholder="Ingrediens" class="lab-input" />
<button type="button" class="remove-ingredient" onclick="removeIngredient(this)">Ta bort</button>
</div>
}
</div>
<button type="button" onclick="addIngredient()" class="lab-add-button">Lägg till ingrediens</button>
<button type="submit" class="lab-save-button">Spara ingredienser</button>
</form>
</div>
<hr />
<!-- Ny version sektion -->
<h3>Ny version</h3>
<form asp-action="AddLabVersion" method="post">
<input type="hidden" name="RecipeLabEntryId" value="@Model.Id" />
<div class="lab-form-group">
<label>Version-label</label>
<input type="text" name="VersionLabel" value="v@((Model.Versions?.Count + 1 ?? 1))" class="lab-input" />
</div>
<div class="lab-form-group">
<label>Instruktioner</label>
<textarea name="Instructions" class="lab-textarea"></textarea>
</div>
<div class="lab-form-group">
<label>Resultat</label>
<textarea name="ResultNotes" class="lab-textarea"></textarea>
</div>
<button type="submit" class="lab-add-button">Lägg till version</button>
</form>
}
else
{
<p><em>Spara labbet först för att kunna lägga till ingredienser och versioner.</em></p>
}
</div>
<!-- Höger: versioner -->
<div class="lab-versions">
<h3>Versioner</h3>
@if (Model.Versions?.Any() == true)
{
<div class="version-scroll">
@foreach (var version in Model.Versions.OrderByDescending(v => v.CreatedAt))
{
<div class="version-card">
<h4>@version.VersionLabel</h4>
<p><strong>Skapat:</strong> @version.CreatedAt.ToString("yyyy-MM-dd")</p>
@if (!string.IsNullOrEmpty(version.Instructions))
{
<p><strong>Instruktioner:</strong><br />@version.Instructions</p>
}
@if (!string.IsNullOrEmpty(version.ResultNotes))
{
<p><strong>Resultat:</strong><br />@version.ResultNotes</p>
}
@if (version.Ingredients?.Any() == true)
{
<p><strong>Ingredienser:</strong></p>
<ul>
@foreach (var ing in version.Ingredients)
{
<li>@ing.Quantity @ing.Item</li>
}
</ul>
}
</div>
}
</div>
}
else
{
<p>Inga tidigare versioner ännu.</p>
}
</div>
</div>
<script>
let ingredientIndex = @(Model.Ingredients?.Count ?? 1);
function addIngredient() {
const list = document.getElementById('ingredients-list');
const div = document.createElement('div');
div.className = 'ingredient-row';
div.innerHTML = `
<input type="text" name="Ingredients[${ingredientIndex}].Quantity" placeholder="Mängd" class="lab-input" />
<input type="text" name="Ingredients[${ingredientIndex}].Item" placeholder="Ingrediens" class="lab-input" />
<button type="button" class="remove-ingredient" onclick="removeIngredient(this)">Ta bort</button>
`;
list.appendChild(div);
ingredientIndex++;
}
function removeIngredient(button) {
const row = button.closest('.ingredient-row');
row.remove();
reindexIngredients();
}
function reindexIngredients() {
const rows = document.querySelectorAll('.ingredient-row');
rows.forEach((row, index) => {
const quantityInput = row.querySelector('input[name*="Quantity"]');
const itemInput = row.querySelector('input[name*="Item"]');
if (quantityInput) quantityInput.name = `Ingredients[${index}].Quantity`;
if (itemInput) itemInput.name = `Ingredients[${index}].Item`;
});
ingredientIndex = rows.length;
}
</script>

View File

@@ -0,0 +1,74 @@
@model List<Aberwyn.Models.MealCategory>
@{
ViewData["Title"] = "Måltidskategorier";
}
<h1 class="page-title">Måltidskategorier</h1>
<div class="category-list">
@foreach (var cat in Model)
{
<form method="post" action="/meal/categories/save" class="category-row">
<input type="hidden" name="Id" value="@cat.Id" />
<div class="name-with-preview">
<div class="icon-preview" style="background-color: @cat.Color">
@if (!string.IsNullOrWhiteSpace(cat.Icon))
{
<span>@cat.Icon</span>
}
else
{
<span>🍽️</span>
}
</div>
<input name="Name" value="@cat.Name" placeholder="Namn" />
</div>
<input name="Icon" value="@cat.Icon" placeholder="Ikon (emoji eller klass)" />
<input name="Slug" value="@cat.Slug" placeholder="Slug" />
<input name="Color" value="@cat.Color" type="color" title="Färg" />
<label class="checkbox-label">
<input type="checkbox" name="IsActive" @(cat.IsActive ? "checked" : "") />
Aktiv
</label>
<span class="meal-count">@cat.MealCount st</span>
<div class="row-actions">
<button type="submit" title="Spara"><i class="fas fa-save"></i></button>
<form method="post" action="/meal/categories/delete" style="display:inline;">
<input type="hidden" name="id" value="@cat.Id" />
<button type="submit" class="delete" title="Ta bort"><i class="fas fa-trash"></i></button>
</form>
</div>
</form>
}
<!-- Ny kategori -->
<form method="post" action="/meal/categories/save" class="category-row new">
<div class="name-with-preview">
<div class="icon-preview" style="background-color: #6a0dad"></div>
<input name="Name" placeholder="Ny kategori" autofocus />
</div>
<input name="Icon" placeholder="Ikon" />
<input name="Slug" placeholder="Slug" />
<input name="Color" type="color" value="#6a0dad" />
<label class="checkbox-label">
<input type="checkbox" name="IsActive" checked />
Aktiv
</label>
<span></span>
<div class="row-actions">
<button type="submit" title="Lägg till"><i class="fas fa-plus"></i></button>
</div>
</form>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
<link rel="stylesheet" href="/css/meal-categories.css">

View File

@@ -14,12 +14,13 @@
} }
else else
{ {
imageSrc = "/images/placeholder-meal.jpg"; imageSrc = "/images/fallback.jpg";
} }
bool isChef = HttpContextAccessor.HttpContext.User.IsInRole("Chef"); bool isChef = HttpContextAccessor.HttpContext.User.IsInRole("Chef");
isEditing = isEditing && isChef; isEditing = isEditing && isChef;
} }
<link rel="stylesheet" href="/css/meal.css">
<div class="meal-container"> <div class="meal-container">
<div class="meal-header"> <div class="meal-header">
@@ -29,7 +30,7 @@
@if (isEditing) @if (isEditing)
{ {
<div style="margin-top: 0.5rem;"> <div style="margin-top: 0.5rem;">
<button type="button" class="btn-outline" onclick="openImageModal()">Byt bild</button> <button type="button" class="btn-lewel-outline" onclick="openImageModal()">Byt bild</button>
</div> </div>
} }
@@ -37,6 +38,7 @@
<h1 class="meal-title">@Model.Name</h1> <h1 class="meal-title">@Model.Name</h1>
<p class="description">@Model.Description</p> <p class="description">@Model.Description</p>
</div> </div>
</div> </div>
@if (isEditing) @if (isEditing)
@@ -64,6 +66,15 @@
<label for="CarbType">Kolhydrat</label> <label for="CarbType">Kolhydrat</label>
<input type="text" name="CarbType" value="@Model.CarbType" class="form-control" /> <input type="text" name="CarbType" value="@Model.CarbType" class="form-control" />
</div> </div>
<div class="form-group">
<label for="MealCategoryId">Kategori</label>
<select asp-for="MealCategoryId" asp-items="@(new SelectList((List<MealCategory>)ViewBag.Categories, "Id", "Name", Model.MealCategoryId))" class="form-control">
<option value="">-- Välj kategori --</option>
</select>
</div>
<div class="form-group"> <div class="form-group">
<label for="RecipeUrl">Receptlänk</label> <label for="RecipeUrl">Receptlänk</label>
@@ -79,7 +90,7 @@
<div class="form-group"> <div class="form-group">
<label>Ingredienser</label> <label>Ingredienser</label>
<div id="ingredients-list"> <div id="ingredients-list">
@for (int i = 0; i < Model.Ingredients.Count; i++) @for (int i = 0; i < (Model.Ingredients?.Count ?? 0); i++)
{ {
<div class="ingredient-row"> <div class="ingredient-row">
<input type="text" name="Ingredients[@i].Quantity" placeholder="Mängd" value="@Model.Ingredients[i].Quantity" class="form-control ingredient-qty" /> <input type="text" name="Ingredients[@i].Quantity" placeholder="Mängd" value="@Model.Ingredients[i].Quantity" class="form-control ingredient-qty" />
@@ -87,14 +98,26 @@
</div> </div>
} }
</div> </div>
<button type="button" class="btn-outline" onclick="addIngredientRow()">+ Lägg till ingrediens</button> <div style="margin-top: 0.5rem;">
</div> <label for="bulkIngredients">Klistra in flera ingredienser</label>
</div> <textarea id="bulkIngredients" placeholder="1 dl mjölk&#10;2 tsk socker" class="form-control" rows="3"></textarea>
<button type="button" class="btn-lewel-outline" onclick="parseBulkIngredients()">Lägg till från lista</button>
<button type="button" class="btn-lewel-outline" onclick="addIngredientRow()">+ Lägg till rad</button>
</div>
</div>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="IsPublished" value="true" @(Model.IsPublished ? "checked" : "") />
Publicera recept på receptsidan
</label>
</div>
<div class="buttons"> <div class="buttons">
<button type="submit" class="btn">Spara</button> <button type="submit" class="btn-lewel">Spara</button>
<button type="submit" formaction="@Url.Action("DeleteMeal", new { id = Model.Id })" formmethod="post" onclick="return confirm('Vill du verkligen ta bort denna måltid?');" class="btn-outline">Ta bort</button> <button type="submit" formaction="@Url.Action("DeleteMeal", new { id = Model.Id })" formmethod="post" onclick="return confirm('Vill du verkligen ta bort denna måltid?');" class="btn-lewel-outline">Ta bort</button>
<a href="@Url.Action("View", new { id = Model.Id, edit = false })" class="btn-outline">Avbryt</a> <a href="@Url.Action("View", new { id = Model.Id, edit = false })" class="btn-lewel-outline">Avbryt</a>
</div> </div>
</form> </form>
} }
@@ -115,15 +138,29 @@
{ {
<p><a href="@Model.RecipeUrl" class="recipe-link" target="_blank">Visa Recept</a></p> <p><a href="@Model.RecipeUrl" class="recipe-link" target="_blank">Visa Recept</a></p>
} }
@if (User.Identity.IsAuthenticated)
{
<div class="rating-box" data-meal-id="@Model.Id">
<p>Ditt betyg:</p>
<div class="star-container">
@for (int i = 1; i <= 5; i++)
{
<i class="fa fa-star" data-value="@i"></i>
}
</div>
</div>
}
<div class="buttons"> <div style="display: flex; gap: 0.5rem;">
@if (isChef) @if (isChef)
{ {
<a class="btn-outline" href="@Url.Action("View", new { id = Model.Id, edit = true })">Redigera</a> <a class="btn-lewel-outline slim" href="@Url.Action("View", new { id = Model.Id, edit = true })">Redigera</a>
} }
<button type="button" class="btn-outline" onclick="toggleRecipe()">Recept</button> <button type="button" class="btn-lewel-outline slim" onclick="toggleRecipe()">Recept</button>
</div> </div>
<div id="recipe-section" style="display:none; margin-top:1.5rem;"> <div id="recipe-section" style="display:none; margin-top:1.5rem;">
<h2>Så här gör du</h2> <h2>Så här gör du</h2>
@if (!string.IsNullOrWhiteSpace(Model.Instructions)) @if (!string.IsNullOrWhiteSpace(Model.Instructions))
@@ -165,8 +202,95 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script>
<script src="https://kit.fontawesome.com/yourkit.js" crossorigin="anonymous"></script>
<script> <script>
document.addEventListener("DOMContentLoaded", () => {
const ratingBox = document.querySelector(".rating-box");
if (!ratingBox) return;
const mealId = ratingBox.dataset.mealId;
const stars = ratingBox.querySelectorAll(".fa-star");
fetch(`/api/MealRatingApi/${mealId}`)
.then(res => res.json())
.then(rating => {
stars.forEach(star => {
if (parseInt(star.dataset.value) <= rating) {
star.classList.add("rated");
}
});
});
stars.forEach(star => {
star.addEventListener("click", () => {
const rating = star.dataset.value;
fetch("/api/MealRatingApi", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mealId: mealId, rating: parseInt(rating) })
}).then(() => {
stars.forEach(s => s.classList.remove("rated"));
stars.forEach(s => {
if (parseInt(s.dataset.value) <= rating) {
s.classList.add("rated");
}
});
});
});
});
});
function addIngredientRow(quantity = '', item = '') {
const list = document.getElementById('ingredients-list');
const index = list.children.length;
const div = document.createElement('div');
div.className = 'ingredient-row';
const qtyInput = document.createElement('input');
qtyInput.type = 'text';
qtyInput.name = `Ingredients[${index}].Quantity`;
qtyInput.placeholder = 'Mängd';
qtyInput.className = 'form-control ingredient-qty';
qtyInput.value = quantity;
const itemInput = document.createElement('input');
itemInput.type = 'text';
itemInput.name = `Ingredients[${index}].Item`;
itemInput.placeholder = 'Ingrediens';
itemInput.className = 'form-control ingredient-item';
itemInput.value = item;
div.appendChild(qtyInput);
div.appendChild(itemInput);
list.appendChild(div);
}
function parseBulkIngredients() {
const bulk = document.getElementById('bulkIngredients').value;
if (!bulk.trim()) return;
const lines = bulk.trim().split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
// Försök dela på första mellanslag → mängd + ingrediens
const parts = trimmed.split(' ');
const quantity = parts.slice(0, 2).join(' '); // typ "2 dl" eller "1 tsk"
const item = parts.slice(2).join(' '); // resten
// fallback om bara ett ord: "ägg"
const safeQuantity = item ? quantity : '';
const safeItem = item || quantity;
addIngredientRow(safeQuantity, safeItem);
}
document.getElementById('bulkIngredients').value = '';
}
function toggleRecipe() { function toggleRecipe() {
const section = document.getElementById('recipe-section'); const section = document.getElementById('recipe-section');
if (!section) return; if (!section) return;
@@ -215,7 +339,7 @@
closeImageModal(); closeImageModal();
} }
}); });
$(document).ready(function () { $(document).ready(function () {
if ($('#Instructions').length > 0) { if ($('#Instructions').length > 0) {
$('#Instructions').trumbowyg({ $('#Instructions').trumbowyg({
autogrow: true, autogrow: true,
@@ -223,199 +347,10 @@
}); });
} }
}); });
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register('/service-worker.js')
.then(function (registration) {
console.log('Service Worker registered', registration);
return registration.pushManager.getSubscription()
.then(async function (subscription) {
if (subscription) {
console.log('Already subscribed to push notifications.');
return subscription;
}
const response = await fetch('/api/push/vapid-public-key');
const vapidPublicKey = await response.text();
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
});
});
}).then(function (subscription) {
return fetch('/api/push/subscribe', {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'Content-Type': 'application/json'
}
});
});
}
</script> </script>
<style> <style>
.dragging {
outline: 2px dashed #6a0dad;
}
.meal-image-wrapper {
position: relative;
}
.meal-container {
max-width: 900px;
margin: 2rem auto;
background: #fff;
padding: 2rem;
border-radius: 16px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
font-family: 'Segoe UI', sans-serif;
}
.meal-header {
display: flex;
flex-direction: row;
gap: 1.5rem;
align-items: center;
}
.meal-meta {
flex: 1;
}
.meal-title {
font-size: 2.5rem;
font-weight: bold;
margin-bottom: 1rem;
color: #333;
}
.meal-image {
width: 250px;
height: 250px;
object-fit: cover;
border-radius: 12px;
border: 1px solid #ccc;
}
.description {
font-size: 1.1rem;
color: #555;
margin-top: 0.5rem;
margin-bottom: 1.5rem;
}
.meal-details p {
font-size: 1rem;
color: #333;
margin: 0.3rem 0;
}
.label {
font-weight: bold;
color: #6a0dad;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
font-weight: 600;
margin-bottom: 0.3rem;
display: block;
}
.form-control {
width: 100%;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
}
.buttons {
margin-top: 1.5rem;
}
.btn,
.btn-outline {
background-color: #6a0dad;
color: white;
border: none;
padding: 0.6rem 1.4rem;
border-radius: 6px;
margin: 0.4rem;
cursor: pointer;
font-size: 1rem;
text-decoration: none;
}
.btn-outline {
background-color: transparent;
border: 2px solid #6a0dad;
color: #6a0dad;
}
.recipe-link {
color: #6a0dad;
text-decoration: underline;
font-weight: 500;
}
.placeholder {
color: #999;
font-style: italic;
}
.ingredient-row {
display: flex;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.ingredient-qty {
flex: 1 0 30%;
}
.ingredient-item {
flex: 2 0 60%;
}
@@media (max-width: 768px) {
.meal-container {
padding: 1rem;
}
.meal-header {
flex-direction: column;
align-items: center;
text-align: center;
}
.meal-meta {
width: 100%;
}
.meal-title {
font-size: 2rem;
}
.meal-image {
width: 100%;
max-width: 300px;
height: auto;
}
.form-control {
font-size: 1rem;
}
.ingredient-row {
flex-direction: column;
}
.ingredient-qty,
.ingredient-item {
flex: 1 0 auto;
width: 100%;
}
.btn,
.btn-outline {
width: 100%;
margin: 0.25rem 0;
}
.buttons {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
}
</style> </style>

View File

@@ -0,0 +1,43 @@
@{
ViewData["Title"] = "Filmsök";
}
<div class="container mt-4">
<h2>🎬 Filmsök</h2>
<input type="text" class="form-control mb-3" id="searchInput" placeholder="Sök efter en film..." oninput="searchMovie()" />
<div class="results row" id="results"></div>
</div>
@section Scripts {
<script>
const API_KEY = 'aef2f49296b77b9b9c269678d04bdbc6';
const BASE_URL = 'https://api.themoviedb.org/3';
const IMG_BASE = 'https://image.tmdb.org/t/p/w300';
async function searchMovie() {
const query = document.getElementById('searchInput').value.trim();
const resultContainer = document.getElementById('results');
resultContainer.innerHTML = '';
if (query.length < 2) return;
const res = await fetch(`${BASE_URL}/search/movie?api_key=${API_KEY}&language=sv-SE&query=${encodeURIComponent(query)}`);
const data = await res.json();
data.results.forEach(movie => {
const col = document.createElement('div');
col.className = 'col-md-3 mb-4';
col.innerHTML = `
<div class="card h-100 bg-dark text-white border-0 shadow">
<img src="${movie.poster_path ? IMG_BASE + movie.poster_path : 'https://via.placeholder.com/300x450?text=Ingen+bild'}" class="card-img-top" alt="${movie.title}" />
<div class="card-body">
<h5 class="card-title">${movie.title}</h5>
<p class="card-text"><small>${movie.release_date || 'Okänt datum'}</small></p>
</div>
</div>
`;
resultContainer.appendChild(col);
});
}
</script>
}

View File

@@ -0,0 +1,395 @@
@model Aberwyn.Models.SetupSettings
@{
ViewData["Title"] = "Installera Aberwyn";
}
<h1>Installera Aberwyn</h1>
@if (ViewBag.Error != null)
{
<div class="alert alert-danger">@ViewBag.Error</div>
}
<style>
.setup-step {
margin-bottom: 2rem;
padding: 1.5rem;
background-color: #f8f9fa;
border-radius: 8px;
box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}
.form-group {
margin-bottom: 1rem;
display: flex;
flex-direction: column;
}
label {
font-weight: bold;
margin-bottom: 0.2rem;
}
input.form-control {
padding: 0.5rem;
font-size: 1rem;
border-radius: 6px;
}
.is-invalid {
border-color: #dc3545;
}
.invalid-feedback {
color: #dc3545;
font-size: 0.875rem;
display: none;
}
.is-invalid + .invalid-feedback {
display: block;
}
button {
padding: 10px 20px;
font-size: 1rem;
border-radius: 6px;
border: none;
cursor: pointer;
transition: background 0.2s ease;
margin-top: 0.5rem;
margin-right: 0.5rem;
}
.btn-primary { background-color: #6a0dad; color: white; }
.btn-primary:hover { background-color: #5a0cab; }
.btn-secondary { background-color: #adb5bd; color: black; }
.btn-secondary:hover { background-color: #9ca3af; }
.btn-success { background-color: #198754; color: white; }
.btn-success:hover { background-color: #157347; }
.btn-danger { background-color: #dc3545; color: white; }
.btn-danger:hover { background-color: #bb2d3b; }
.btn-outline-info {
border: 1px solid #0dcaf0;
color: #0dcaf0;
background: none;
}
.btn-outline-info:hover {
background-color: #0dcaf0;
color: white;
}
#setup-summary ul {
list-style: none;
padding-left: 0;
}
#setup-summary li {
margin-bottom: 0.4rem;
}
.spinner {
display: inline-block;
width: 1.2rem;
height: 1.2rem;
border: 3px solid rgba(0,0,0,0.2);
border-top-color: #6a0dad;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-left: 0.5rem;
}
@@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
<form method="post" id="setup-form">
<div id="step-1" class="setup-step">
<h2>Steg 1: Databasinställningar</h2>
<div class="form-group">
<label for="DbHost">Server</label>
<input asp-for="DbHost" name="DbHost" class="form-control" id="DbHost" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="DbPort">Port</label>
<input asp-for="DbPort" name="DbPort" class="form-control" id="DbPort" value="3306" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="DbName">Databasnamn</label>
<input asp-for="DbName" name="DbName" class="form-control" id="DbName" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="DbUser">Användarnamn</label>
<input asp-for="DbUser" name="DbUser" class="form-control" id="DbUser" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="DbPassword">Lösenord</label>
<input asp-for="DbPassword" name="DbPassword" type="password" class="form-control" id="DbPassword" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<button type="button" class="btn btn-outline-info" onclick="testDbConnection()">Testa anslutning</button>
<div id="db-test-result" class="mt-2"></div>
<button type="button" class="btn btn-primary" onclick="validateStep(1) && goToStep(2)">Nästa</button>
</div>
<div id="step-2" class="setup-step" style="display: none;">
<h2>Steg 2: Administratör</h2>
<div class="form-group">
<label for="AdminUsername">Admin Användarnamn</label>
<input asp-for="AdminUsername" name="AdminUsername" class="form-control" id="AdminUsername" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="AdminEmail">E-postadress</label>
<input asp-for="AdminEmail" name="AdminEmail" type="email" class="form-control" id="AdminEmail" required />
<div class="invalid-feedback">Fältet är obligatoriskt</div>
</div>
<div class="form-group">
<label for="AdminPassword">Lösenord</label>
<input asp-for="AdminPassword" name="AdminPassword" type="password" class="form-control"
id="AdminPassword"
pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{6,}"
title="Minst 6 tecken, inklusive versal, gemen, siffra och specialtecken"
required />
<div class="invalid-feedback">Ange ett giltigt lösenord enligt kraven</div>
</div>
<div class="form-group">
<label for="ConfirmPassword">Bekräfta lösenord</label>
<input type="password" id="ConfirmPassword" class="form-control" required />
<span id="password-match-status" style="margin-top: 4px; font-size: 1.2rem;"></span>
<div class="invalid-feedback" id="confirmPasswordError">Lösenorden matchar inte</div>
</div>
<ul id="password-criteria" style="list-style: none; padding-left: 0; font-size: 0.9rem; margin-top: 0.5rem;">
<li id="length-criteria">❌ Minst 6 tecken</li>
<li id="uppercase-criteria">❌ Minst en stor bokstav (AZ)</li>
<li id="lowercase-criteria">❌ Minst en liten bokstav (az)</li>
<li id="digit-criteria">❌ Minst en siffra (09)</li>
<li id="special-criteria">❌ Minst ett specialtecken (!#&...)</li>
</ul>
<button type="button" class="btn btn-secondary" onclick="goToStep(1)">Tillbaka</button>
<button type="button" class="btn btn-primary" onclick="validateAdminStep() && goToStep(3)">Nästa</button>
</div>
<div id="step-3" class="setup-step" style="display: none;">
<h2>Steg 3: Konfiguration pågår...</h2>
<div id="setup-summary">
<ul>
<li><strong>Server:</strong> <span id="summary-DbHost"></span></li>
<li><strong>Port:</strong> <span id="summary-DbPort"></span></li>
<li><strong>Databas:</strong> <span id="summary-DbName"></span></li>
<li><strong>Användare:</strong> <span id="summary-DbUser"></span></li>
<li><strong>Adminnamn:</strong> <span id="summary-AdminUsername"></span></li>
<li><strong>Admin-e-post:</strong> <span id="summary-AdminEmail"></span></li>
</ul>
</div>
<div id="setup-progress" class="mt-3">
<p>
Skapar databastabeller och konfigurerar administratörskonto...
<span class="spinner"></span>
</p>
</div>
<button type="button" class="btn btn-secondary" onclick="goToStep(2)">Tillbaka</button>
<button type="button" class="btn btn-success" onclick="submitSetup()">Slutför installation</button>
</div>
</form>
@if (User.IsInRole("Admin"))
{
<form method="post" asp-action="Reset" class="mt-3" onsubmit="return confirm('Är du säker på att du vill återställa konfigurationen?')">
<button type="submit" class="btn btn-danger">Återställ inställningar</button>
</form>
}
@section Scripts {
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate-unobtrusive/3.2.12/jquery.validate.unobtrusive.min.js"></script>
<script>
function goToStep(step) {
document.querySelectorAll('.setup-step').forEach(s => s.style.display = 'none');
document.getElementById('step-' + step).style.display = 'block';
if (step === 3) {
document.getElementById('summary-DbHost').textContent = document.getElementById('DbHost').value;
document.getElementById('summary-DbPort').textContent = document.getElementById('DbPort').value;
document.getElementById('summary-DbName').textContent = document.getElementById('DbName').value;
document.getElementById('summary-DbUser').textContent = document.getElementById('DbUser').value;
document.getElementById('summary-AdminUsername').textContent = document.getElementById('AdminUsername').value;
document.getElementById('summary-AdminEmail').textContent = document.getElementById('AdminEmail').value;
document.getElementById('setup-progress').innerHTML = `<p>Redo att påbörja installationen.</p>`;
}
}
document.getElementById('AdminPassword').addEventListener('input', function () {
const val = this.value;
const hasLength = val.length >= 6;
const hasUpper = /[A-Z]/.test(val);
const hasLower = /[a-z]/.test(val);
const hasDigit = /\d/.test(val);
const hasSpecial = /[!@@#$%^&*(),.?":{}|<>_\-\\[\]\/+=~`]/.test(val); // lägg till specialtecken
updateCriteria('length-criteria', hasLength);
updateCriteria('uppercase-criteria', hasUpper);
updateCriteria('lowercase-criteria', hasLower);
updateCriteria('digit-criteria', hasDigit);
updateCriteria('special-criteria', hasSpecial);
});
function updateCriteria(id, isValid) {
const el = document.getElementById(id);
if (isValid) {
el.textContent = '✔ ' + el.textContent.slice(2);
el.style.color = 'green';
} else {
el.textContent = '❌ ' + el.textContent.slice(2);
el.style.color = 'red';
}
}
function validateStep(step) {
let isValid = true;
document.querySelectorAll('#step-' + step + ' [required]').forEach(field => {
if (!field.value.trim()) {
field.classList.add('is-invalid');
isValid = false;
} else {
field.classList.remove('is-invalid');
}
});
return isValid;
}
function testDbConnection() {
const host = document.getElementById('DbHost').value;
const port = document.getElementById('DbPort').value;
const db = document.getElementById('DbName').value;
const user = document.getElementById('DbUser').value;
const pass = document.getElementById('DbPassword').value;
const output = document.getElementById('db-test-result');
output.innerHTML = '<span class="spinner"></span> Testar...';
fetch('/api/setup/testdb', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ host, port, db, user, pass })
})
.then(async res => {
const text = await res.text();
console.log("Raw:", text);
try {
const result = JSON.parse(text);
if (result.success) {
output.innerHTML = '✅ <span class="text-success">Anslutning lyckades!</span>';
} else {
output.innerHTML = '❌ <span class="text-danger">' + result.message + '</span>';
}
} catch (e) {
output.innerHTML = '❌ <span class="text-danger">Felaktigt svar från servern: ' + text + '</span>';
}
})
.catch(err => {
output.innerHTML = '❌ <span class="text-danger">Nätverksfel: ' + err.message + '</span>';
});
}
function validateAdminStep() {
let valid = validateStep(2);
const pass = document.getElementById('AdminPassword');
const confirm = document.getElementById('ConfirmPassword');
const confirmError = document.getElementById('confirmPasswordError');
if (pass.value !== confirm.value) {
confirm.classList.add('is-invalid');
confirmError.style.display = 'block';
valid = false;
} else {
confirm.classList.remove('is-invalid');
confirmError.style.display = 'none';
}
return valid;
}
document.getElementById('ConfirmPassword').addEventListener('input', function () {
const pass = document.getElementById('AdminPassword').value;
const confirm = this.value;
const confirmField = document.getElementById('ConfirmPassword');
const matchStatus = document.getElementById('password-match-status');
if (confirm.length === 0) {
matchStatus.innerHTML = '';
confirmField.classList.remove('is-invalid');
return;
}
if (pass === confirm) {
matchStatus.innerHTML = '✔';
matchStatus.style.color = 'green';
confirmField.classList.remove('is-invalid');
} else {
matchStatus.innerHTML = '❌';
matchStatus.style.color = 'red';
confirmField.classList.add('is-invalid');
}
});
async function submitSetup() {
goToStep(3);
const form = document.getElementById('setup-form');
const formData = new FormData(form);
const data = {};
formData.forEach((value, key) => { data[key] = value; });
const resultEl = document.getElementById('setup-progress');
resultEl.innerHTML = `<p>
Skapar databastabeller och konfigurerar administratörskonto...
<span class="spinner"></span>
</p>`;
try {
const response = await fetch('/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const text = await response.text();
let result;
try {
result = JSON.parse(text);
} catch (err) {
throw new Error("Kunde inte tolka JSON-svar: " + text);
}
if (!response.ok) {
resultEl.innerHTML = `
<div class="alert alert-danger mt-3">
❌ Fel vid installation: ${result.error || 'Okänt fel'}
</div>`;
return;
}
resultEl.innerHTML = `
<div class="alert alert-success mt-3">
✅ ${result.message || 'Installation slutförd!'}
<br />
<button class="btn btn-success mt-3" onclick="window.location.href='/'">Gå vidare</button>
</div>`;
} catch (err) {
console.error("Något gick fel:", err);
resultEl.innerHTML = `<div class="alert alert-danger mt-3">
❌ Fel vid installation: ${err.message}
</div>`;
}
}
</script>
}

View File

@@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Klart!";
}
<h1>✅ Aberwyn är nu installerad</h1>
<p>Du kan nu starta om applikationen för att börja använda den.</p>
<a href="/" class="btn btn-primary">Till startsidan</a>
<hr />
<h3>🔄 Återställ installation</h3>
<p>Om du vill nollställa installationen och börja om från början, klicka här:</p>
<form method="post" asp-action="Reset">
<button type="submit" class="btn btn-danger">Återställ konfiguration</button>
</form>

View File

@@ -1,9 +1,15 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<link rel="manifest" href="/manifest.json"> <link rel="manifest" href="/manifest-v2.json">
<link rel="icon" type="image/png" sizes="512x512" href="/images/lewel-icon.png"> <link rel="icon" type="image/png" sizes="512x512" href="/images/lewel-icon.png">
<meta name="theme-color" content="#6a0dad"> <meta name="theme-color" content="#6a0dad">
<style>
[ng-cloak] {
display: none !important;
}
</style>
<meta name="theme-color" content="#1F2C3C" />
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LEWEL - Dashboard</title> <title>LEWEL - Dashboard</title>
@@ -21,43 +27,66 @@
<span class="initial L2">L</span><span class="name">udwig</span> <span class="initial L2">L</span><span class="name">udwig</span>
</h1> </h1>
</div> </div>
<partial name="_LoginPartial" /> @if (ViewBag.IsSetupMode as bool? != true)
{
<partial name="_LoginPartial" />
}
</header> </header>
<div class="page-content"> <div class="page-content">
<aside class="sidebar"> <nav class="main-nav">
<ul class="nav-list"> <ul class="nav-list-horizontal">
<li><a asp-controller="Home" asp-action="Index"><i class="fas fa-home"></i> Home</a></li> <li><a asp-controller="Home" asp-action="Index"><i class="fas fa-home"></i> Hem</a></li>
@if (User.IsInRole("Admin") || User.IsInRole("Budget")) <li><a asp-controller="Home" asp-action="Menu"><i class="fas fa-utensils"></i> Veckomeny</a></li>
{ <li><a asp-controller="Meal" asp-action="Index">Recept</a></li>
<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 (ViewBag.RestaurantIsOpen as bool? == true)
{
@if (User.IsInRole("Admin")) <li><a asp-controller="FoodMenu" asp-action="PizzaOrder"><i class="fas fa-pizza-slice"></i> Beställ pizza</a></li>
{ }
<li><a asp-controller="Admin" asp-action="Index"><i class="fas fa-cog"></i> Adminpanel</a></li> @if (User.IsInRole("Budget"))
} {
<li><a asp-controller="Budget" asp-action="Index"> Budget</a></li>
}
@if (User.IsInRole("Chef"))
{
<li class="dropdown">
<a href="#" class="dropdown-toggle" role="button" tabindex="0">
<i class="fas fa-list"></i> Mat<i class="fas fa-caret-down"></i>
</a>
<ul class="dropdown-menu">
<li><a asp-controller="FoodMenu" asp-action="Veckomeny">Planera Veckomeny</a></li>
<li><a asp-controller="FoodMenu" asp-action="PizzaAdmin">Pizza Admin</a></li>
<li><a asp-controller="Meal" asp-action="Categories">Hantera Kategorier</a></li>
</ul> </ul>
</aside> </li>
}
@if (User.IsInRole("Admin"))
{
<li class="dropdown">
<a href="#" class="dropdown-toggle" role="button" tabindex="0">
<i class="fas fa-cog"></i> Admin <i class="fas fa-caret-down"></i>
</a>
<ul class="dropdown-menu">
<li><a asp-controller="Admin" asp-action="Index">Adminpanel</a></li>
<li><a asp-controller="Admin" asp-action="Todo">Todo</a></li>
</ul>
</li>
}
</ul>
</nav>
<main class="main-panel"> <main class="main-panel">
@RenderBody() @RenderBody()
@RenderSection("Scripts", required: false) @RenderSection("Scripts", required: false)
</main> </main>
</div> </div>
<div id="global-dropdown-container" style="position: relative; z-index: 10000;"></div>
<script src="~/js/site.js" asp-append-version="true"></script> <script src="~/js/site.js" asp-append-version="true"></script>
</body> </body>

View File

@@ -13,7 +13,10 @@
<i class="fas fa-user-circle"></i> <i class="fas fa-user-circle"></i>
</button> </button>
<div class="auth-dropdown"> <div class="auth-dropdown">
<span style="padding: 8px 12px; display: block;">@User.Identity.Name</span> <a href="/User/Profile">
<i class="fas fa-user-cog"></i> Min profil
</a>
<form method="post" asp-area="Identity" asp-page="/Account/Logout" style="margin: 0;"> <form method="post" asp-area="Identity" asp-page="/Account/Logout" style="margin: 0;">
<button type="submit" class="dropdown-logout-button" style="padding: 8px 12px; width: 100%; text-align: left; background: none; border: none; cursor: pointer;">Logga ut</button> <button type="submit" class="dropdown-logout-button" style="padding: 8px 12px; width: 100%; text-align: left; background: none; border: none; cursor: pointer;">Logga ut</button>
</form> </form>
@@ -31,7 +34,7 @@ else
<div class="auth-dropdown"> <div class="auth-dropdown">
<form method="post" asp-area="Identity" asp-page="/Account/Login" style="padding: 12px; display: flex; flex-direction: column; gap: 8px;"> <form method="post" asp-area="Identity" asp-page="/Account/Login" style="padding: 12px; display: flex; flex-direction: column; gap: 8px;">
<input type="hidden" name="ReturnUrl" value="/" /> <input type="hidden" name="ReturnUrl" value="/" />
<input name="Input.Email" type="email" placeholder="E-post" required style="padding: 6px; font-size: 14px;" /> <input name="Input.Username" type="text" placeholder="Användarnamn" required style="padding: 6px; font-size: 14px;" />
<input name="Input.Password" type="password" placeholder="Lösenord" required style="padding: 6px; font-size: 14px;" /> <input name="Input.Password" type="password" placeholder="Lösenord" required style="padding: 6px; font-size: 14px;" />
<button type="submit" style="background-color: #3A4E62; color: white; border: none; padding: 6px 10px; border-radius: 4px; font-size: 14px;"> <button type="submit" style="background-color: #3A4E62; color: white; border: none; padding: 6px 10px; border-radius: 4px; font-size: 14px;">
Logga in Logga in

View File

@@ -0,0 +1,225 @@
@model TorrentUploadViewModel
@{
ViewData["Title"] = "Torrent Analyzer";
}
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3 class="mb-0">
<i class="fas fa-download"></i> Torrent Analyzer
</h3>
<p class="text-muted mb-0">Ladda upp en torrent-fil för att se seeders/leechers</p>
</div>
<div class="card-body">
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
@foreach (var error in ViewData.ModelState.Values.SelectMany(v => v.Errors))
{
<div>@error.ErrorMessage</div>
}
</div>
}
<form asp-action="Upload" method="post" enctype="multipart/form-data" class="mb-4">
@Html.AntiForgeryToken()
<div class="mb-3">
<label for="torrentFile" class="form-label">Välj torrent-fil</label>
<input type="file"
class="form-control"
asp-for="TorrentFile"
accept=".torrent"
required>
<div class="form-text">Endast .torrent filer, max 10MB</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-upload"></i> Analysera Torrent
</button>
</form>
@if (Model.ShowResults && Model.TorrentInfo != null)
{
<hr>
<div class="torrent-results">
<h4 class="mb-3">
<i class="fas fa-info-circle"></i> Torrent Information
</h4>
<div class="row mb-3">
<div class="col-sm-3"><strong>Filnamn:</strong></div>
<div class="col-sm-9">@Model.TorrentInfo.FileName</div>
</div>
<div class="row mb-3">
<div class="col-sm-3"><strong>Storlek:</strong></div>
<div class="col-sm-9">@FormatFileSize(Model.TorrentInfo.Size)</div>
</div>
<div class="row mb-3">
<div class="col-sm-3"><strong>Announce URL:</strong></div>
<div class="col-sm-9">
<small class="text-muted font-monospace">@Model.TorrentInfo.AnnounceUrl</small>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-3"><strong>Info Hash:</strong></div>
<div class="col-sm-9">
<small class="text-muted font-monospace">@Model.TorrentInfo.InfoHash</small>
</div>
</div>
@if (!string.IsNullOrEmpty(Model.TorrentInfo.ErrorMessage))
{
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle"></i>
<strong>Tracker-info:</strong> @Model.TorrentInfo.ErrorMessage
</div>
}
else if (Model.TorrentInfo.HasTrackerData)
{
<div class="card bg-light">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">
<i class="fas fa-chart-bar"></i> Tracker Statistik
</h5>
<button type="button"
class="btn btn-sm btn-outline-primary"
onclick="refreshStats()"
id="refreshBtn">
<i class="fas fa-sync-alt"></i> Uppdatera
</button>
</div>
<div class="card-body">
<div class="row text-center">
<div class="col-md-4">
<div class="stat-box p-3">
<h3 class="text-success mb-1" id="seeders">@Model.TorrentInfo.Seeders</h3>
<small class="text-muted">Seeders</small>
</div>
</div>
<div class="col-md-4">
<div class="stat-box p-3">
<h3 class="text-warning mb-1" id="leechers">@Model.TorrentInfo.Leechers</h3>
<small class="text-muted">Leechers</small>
</div>
</div>
<div class="col-md-4">
<div class="stat-box p-3">
<h3 class="text-info mb-1" id="completed">@Model.TorrentInfo.Completed</h3>
<small class="text-muted">Completed</small>
</div>
</div>
</div>
</div>
</div>
}
else
{
<div class="alert alert-info">
<i class="fas fa-info-circle"></i>
Tracker-statistik kunde inte hämtas. Detta kan bero på att trackern inte stöder scraping eller kräver autentisering.
</div>
}
</div>
}
</div>
</div>
</div>
</div>
</div>
@functions {
string FormatFileSize(long bytes)
{
if (bytes == 0) return "Okänd storlek";
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
int order = 0;
double size = bytes;
while (size >= 1024 && order < sizes.Length - 1)
{
order++;
size = size / 1024;
}
return $"{size:0.##} {sizes[order]}";
}
}
<style>
.stat-box {
border: 1px solid #dee2e6;
border-radius: 8px;
background: white;
margin: 5px;
}
.torrent-results {
animation: fadeIn 0.5s ease-in;
}
@@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.font-monospace {
font-family: 'Courier New', monospace;
word-break: break-all;
}
</style>
<script>
async function refreshStats() {
const refreshBtn = document.getElementById('refreshBtn');
const seedersEl = document.getElementById('seeders');
const leechersEl = document.getElementById('leechers');
const completedEl = document.getElementById('completed');
if (!seedersEl) return; // Ingen tracker data att uppdatera
refreshBtn.disabled = true;
refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uppdaterar...';
try {
const response = await fetch('@Url.Action("RefreshStats", "Torrent")', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
},
body: JSON.stringify({
infoHash: '@Model.TorrentInfo?.InfoHash',
scrapeUrl: '@Model.TorrentInfo?.ScrapeUrl'
})
});
const data = await response.json();
if (data.success) {
seedersEl.textContent = data.seeders;
leechersEl.textContent = data.leechers;
completedEl.textContent = data.completed;
// Visa success animation
[seedersEl, leechersEl, completedEl].forEach(el => {
el.style.transform = 'scale(1.1)';
setTimeout(() => el.style.transform = 'scale(1)', 200);
});
} else {
alert('Fel vid uppdatering: ' + (data.error || 'Okänt fel'));
}
} catch (error) {
console.error('Fel:', error);
alert('Nätverksfel vid uppdatering');
} finally {
refreshBtn.disabled = false;
refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Uppdatera';
}
}
</script>

View File

@@ -0,0 +1,137 @@
@model Aberwyn.Models.UserProfileViewModel
@{
ViewData["Title"] = "Min profil";
}
<h2>Min profil</h2>
<form method="post" asp-action="SaveProfile">
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" readonly />
</div>
<h3>Pushnotiser</h3>
<div>
<input asp-for="NotifyPizza" type="checkbox" />
<label asp-for="NotifyPizza">Ny pizzabeställning</label>
</div>
<div>
<input asp-for="NotifyMenu" type="checkbox" />
<label asp-for="NotifyMenu">Meny ändrad</label>
</div>
<div>
<input asp-for="NotifyBudget" type="checkbox" />
<label asp-for="NotifyBudget">Budget uppdaterad</label>
</div>
<button type="submit">Spara</button>
<div style="margin-top: 1em;">
<div id="notificationStatus" style="font-weight: bold;"></div>
<button type="button" id="enableNotificationsBtn">Aktivera notiser</button>
<button type="button" id="disableNotificationsBtn">Stäng av notiser</button>
</div>
</form>
@section Scripts {
<script>
async function updateNotificationStatus() {
const el = document.getElementById("notificationStatus");
if (!("Notification" in window)) {
el.textContent = "⛔️ Pushnotiser stöds inte i denna webbläsare.";
el.style.color = "gray";
return;
}
const status = Notification.permission;
const reg = await navigator.serviceWorker.ready;
const existing = await reg.pushManager.getSubscription();
switch (status) {
case "granted":
el.textContent = existing ? "✅ Pushnotiser är aktiverade." : "🟡 Tillåtet men ingen prenumeration aktiv.";
el.style.color = existing ? "green" : "orange";
break;
case "denied":
el.textContent = "❌ Pushnotiser är blockerade.";
el.style.color = "red";
break;
case "default":
el.textContent = "❔ Pushnotiser har inte begärts ännu.";
el.style.color = "orange";
break;
}
}
document.addEventListener("DOMContentLoaded", updateNotificationStatus);
document.getElementById("enableNotificationsBtn").addEventListener("click", async () => {
if (!("Notification" in window)) {
alert("Notiser stöds inte i denna webbläsare.");
return;
}
const permission = await Notification.requestPermission();
if (permission !== "granted") {
alert("Du måste tillåta notiser.");
updateNotificationStatus();
return;
}
const reg = await navigator.serviceWorker.ready;
const existing = await reg.pushManager.getSubscription();
if (existing) {
alert("🔔 Du är redan prenumererad på notiser.");
updateNotificationStatus();
return;
}
const vapidPublicKey = await fetch('/api/push/vapid-public-key').then(r => r.text());
const sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey.trim())
});
await fetch("/api/push/subscribe-user", {
method: "POST",
body: JSON.stringify(sub),
headers: { "Content-Type": "application/json" }
});
alert("✅ Du är nu prenumererad!");
updateNotificationStatus();
});
document.getElementById("disableNotificationsBtn").addEventListener("click", async () => {
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
if (!sub) {
alert(" Ingen prenumeration att ta bort.");
return;
}
await sub.unsubscribe();
await fetch("/api/push/unsubscribe", {
method: "POST",
body: JSON.stringify({ endpoint: sub.endpoint }),
headers: { "Content-Type": "application/json" }
});
alert("🚫 Prenumeration avslutad.");
updateNotificationStatus();
});
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const raw = atob(base64);
return new Uint8Array([...raw].map(char => char.charCodeAt(0)));
}
</script>
}

View File

@@ -6,7 +6,7 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=mysql;Database=aberwyn_dev;User=aberwyn;Password=3edc4RFV;", "DefaultConnection": "Server=192.168.1.108;Database=Nevyn;Uid=root;Pwd=3edc4RFV;",
"ProdConnection": "Server=192.168.1.108;Database=Nevyn;Uid=root;Pwd=3edc4RFV;" "ProdConnection": "Server=192.168.1.108;Database=Nevyn;Uid=root;Pwd=3edc4RFV;"
} }

View File

@@ -1,5 +1,5 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=mysql;Database=aberwyn_prod;User=aberwyn;Password=3edc4RFV;" "DefaultConnection": "Server=192.168.1.108;Database=Nevyn;Uid=root;Pwd=3edc4RFV;"
} }
} }

View File

@@ -7,11 +7,12 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=mysql;Database=aberwyn_dev;User=aberwyn;Password=3edc4RFV;" "DefaultConnection": "Server=192.168.1.108;Database=Nevyn;Uid=root;Pwd=3edc4RFV;"
}, },
"VapidKeys": { "VapidKeys": {
"Subject": "mailto:e@zcz.se", "Subject": "mailto:e@zcz.se",
"PublicKey": "BBLmMdU3X3e79SqzAy4vIAJI0jmzRME17F9UKbO8XT1dfnO-mWIPKIrFDbIZD4_3ic7uoijK61vaGdfFUk3HUfU", "PublicKey": "BBLmMdU3X3e79SqzAy4vIAJI0jmzRME17F9UKbO8XT1dfnO-mWIPKIrFDbIZD4_3ic7uoijK61vaGdfFUk3HUfU",
"PrivateKey": "oranoCmCo8HXdc03juNgbeSlKE39N3DYus_eMunLsnc" "PrivateKey": "oranoCmCo8HXdc03juNgbeSlKE39N3DYus_eMunLsnc"
} },
} }

View File

@@ -0,0 +1,194 @@
.welcome-section.light-mode {
display: flex;
justify-content: center;
align-items: center;
min-height: 90vh;
text-align: center;
padding: 0 20px;
background: linear-gradient(to bottom right, #f9fafb, #e2e8f0);
animation: fadeIn 0.6s ease-in;
}
*, *::before, *::after {
box-sizing: border-box;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.welcome-content {
max-width: 700px;
color: #1e293b;
font-family: 'Segoe UI', sans-serif;
}
.welcome-title {
font-size: 3rem;
font-weight: 700;
margin-bottom: 10px;
color: #1e293b;
}
.highlight {
color: #eab308;
}
.welcome-subtitle {
font-size: 1.35rem;
color: #334155;
margin-bottom: 28px;
}
.meal-line {
margin-bottom: 0rem;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
.meal-line p {
font-size: 1rem;
margin-bottom: 0.5rem;
}
.meal-line a {
color: #007d36;
text-decoration: none;
font-weight: 500;
}
.meal-line a:hover {
text-decoration: underline;
}
.meal-large-thumb-container {
margin-top: 0rem;
width: 100%;
max-width: 300px;
height: 100px;
overflow: hidden;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.meal-large-thumb {
width: 100%;
max-width: 300px;
height: 160px;
object-fit: cover;
object-position: center%;
display: block;
border-radius: 8px;
margin-top: 0rem;
}
.no-menu {
font-size: 1.1rem;
color: #64748b;
margin-bottom: 24px;
}
.nav-button {
background: #3b82f6;
color: white;
text-decoration: none;
padding: 12px 26px;
border-radius: 10px;
font-size: 1rem;
font-weight: 600;
display: inline-block;
margin-top: 24px;
transition: background 0.2s ease, transform 0.2s ease;
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
.nav-button:hover {
background: #2563eb;
transform: translateY(-2px);
}
.thumb-button {
border: none;
background: none;
padding: 0;
cursor: pointer;
}
.meal-line {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 10px;
}
.meal-thumb {
width: 48px;
height: 48px;
object-fit: cover;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.lightbox-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
padding: 20px;
}
.lightbox-content {
position: relative;
max-width: 90%;
max-height: 90%;
display: flex;
flex-direction: column;
align-items: center;
}
.lightbox-image {
max-width: 100%;
max-height: 80vh;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0,0,0,0.5);
}
.lightbox-caption {
color: white;
margin-top: 10px;
font-size: 16px;
text-align: center;
}
.close-lightbox {
position: absolute;
top: -10px;
right: -10px;
background: #fff;
color: #333;
border: none;
border-radius: 50%;
font-size: 20px;
width: 32px;
height: 32px;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
}
.no-scroll {
overflow: hidden;
}

View File

@@ -0,0 +1,116 @@
/* ================================
ADMIN JUSTERAD LEWEL STIL
================================ */
h2, h3, h4,h5 {
margin-top: 2px;
margin-bottom: 12px;
color: #394B5A;
font-weight: 600;
}
form {
background-color: #ffffff;
padding: 2px 8px;
border-radius: 6px;
margin-bottom: 2px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}
.form-group {
margin-bottom: 2px;
}
.form-control {
width: 100%;
max-width: 360px;
padding: 6px 10px;
border-radius: 4px;
border: 1px solid #ccc;
font-size: 14px;
}
button, .btn {
font-size: 14px;
font-weight: 500;
border-radius: 4px;
padding: 6px 12px;
margin-top: 6px;
}
.btn-sm {
padding: 4px 8px;
font-size: 13px;
}
.alert-success {
background-color: #e6ffed;
color: #256029;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid #b4e2c5;
margin-bottom: 16px;
max-width: 360px;
}
table.table {
width: 100%;
border-collapse: collapse;
background-color: #ffffff;
margin-top: 8px;
border-radius: 6px;
overflow: hidden;
font-size: 14px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}
table.table th,
table.table td {
padding: 8px 10px;
text-align: left;
border-bottom: 1px solid #eee;
}
table.table th {
background-color: #f0f4f8;
font-weight: 600;
}
.card {
background-color: #ffffff;
border-radius: 6px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
overflow: hidden;
margin-bottom: 16px;
}
.card-header {
background-color: #394B5A;
color: #ffffff;
font-weight: 600;
padding: 10px 14px;
font-size: 15px;
}
.card-body {
padding: 5px;
}
#testResult {
font-weight: bold;
font-size: 14px;
margin-top: 6px;
}
ul {
margin-top: 0;
margin-bottom: 16px;
padding-left: 20px;
color: #394B5A;
}
@media (max-width: 768px) {
.form-control, .btn {
width: 100%;
}
}

View File

@@ -1,18 +1,23 @@
:root { :root {
--text-main: #1E293B; --text-main: #1F2937; /* Mörkblågrå tydlig men mjuk */
--text-sub: #64748B; --text-sub: #64748B; /* Sekundär gråblå */
--bg-main: #f9fafb; --bg-main: #1F2C3C; /* SID-bakgrund */
--bg-card: #f1f5f9; --bg-card: #dbe3ec;
--border-color: #e5e7eb; --bg-card-summary: #d6dde6;
--card-income: #f97316; --border-color: #cbd5e1; /* Ljus kant men inte skarp */
--item-divider: rgba(0, 0, 0, 0.05); /* ljus standard */
--card-income: #fb923c;
--card-expense: #ef4444; --card-expense: #ef4444;
--card-savings: #facc15; --card-savings: #facc15;
--card-leftover: #86efac; --card-leftover: #4ade80;
--btn-edit: #3b82f6; --btn-edit: #3b82f6;
--btn-check: #10b981; --btn-check: #10b981;
--btn-delete: #ef4444; --btn-delete: #ef4444;
} }
body { body {
background-color: var(--bg-main); background-color: var(--bg-main);
color: var(--text-main); color: var(--text-main);
@@ -88,40 +93,7 @@ body {
background-color: #cbd5e1; background-color: #cbd5e1;
} }
.summary-cards {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
margin: 16px 0 12px;
}
.summary-card {
background-color: var(--bg-card);
padding: 8px 10px;
border-radius: 10px;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
font-weight: 600;
font-size: 13px;
min-width: 130px;
}
.summary-card.income {
border-top: 3px solid var(--card-income);
}
.summary-card.expense {
border-top: 3px solid var(--card-expense);
color: var(--card-expense);
}
.summary-card.savings {
border-top: 3px solid var(--card-savings);
}
.summary-card.leftover {
border-top: 3px solid var(--card-leftover);
}
.budget-grid { .budget-grid {
display: grid; display: grid;
@@ -138,6 +110,7 @@ body {
height: 350px; height: 350px;
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: 12px; border-radius: 12px;
color: var(--text-main);
background-color: var(--bg-card); background-color: var(--bg-card);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
overflow: hidden; overflow: hidden;
@@ -167,6 +140,7 @@ body {
border-top: 1px solid var(--border-color); border-top: 1px solid var(--border-color);
border-radius: 0 0 12px 12px; border-radius: 0 0 12px 12px;
flex-shrink: 0; flex-shrink: 0;
background: var(--bg-card-summary);
} }
.card-header { .card-header {
@@ -268,7 +242,35 @@ body {
text-align: right; text-align: right;
font-weight: 600; font-weight: 600;
} }
@keyframes fadeRed {
0% {
color: rgb(200, 50, 50);
}
100% {
color: rgb(160, 0, 0);
}
}
@keyframes fadeGreen {
0% {
color: rgb(50, 200, 50);
}
100% {
color: rgb(0, 160, 0);
}
}
.item-row.due {
animation: fadeRed 0.2s ease-in-out;
animation-fill-mode: forwards;
}
.item-row.paid {
animation: fadeGreen 0.2s ease-in-out;
animation-fill-mode: forwards;
}
.icon-button { .icon-button {
@@ -294,11 +296,17 @@ color: var(--btn-edit);
.icon-button.confirm { .icon-button.confirm {
color: var(--btn-check); color: var(--btn-check);
} }
.menu-container {
position: relative;
display: inline-block;
}
.dropdown-menu { .dropdown-menu {
position: absolute; position: absolute;
right: 0;
top: calc(100% + 6px); top: calc(100% + 6px);
left: auto;
right: 0;
transform: translateX(-100%) translateX(100%); /* Effektivt: ingen förskjutning */
background-color: #ffffff; background-color: #ffffff;
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: 6px; border-radius: 6px;
@@ -306,27 +314,29 @@ color: var(--btn-check);
z-index: 1000; z-index: 1000;
padding: 6px; padding: 6px;
display: none; display: none;
gap: 4px; flex-direction: column;
flex-wrap: wrap; min-width: 160px;
min-width: 200px; max-width: 240px;
box-sizing: border-box;
} }
.menu-container.open .dropdown-menu { .menu-container.open .dropdown-menu {
display: flex; display: flex;
} }
.dropdown-menu button { .dropdown-menu button {
padding: 5px 8px; padding: 6px 10px;
border-radius: 6px; border-radius: 6px;
border: 1px solid #ddd; border: none;
background: #f3f4f6; background: #f3f4f6;
cursor: pointer; cursor: pointer;
font-size: 12px; font-size: 13px;
flex: 1; text-align: left;
font-weight: 500; width: 100%;
} }
.dropdown-menu button:hover { .dropdown-menu button:hover {
background-color: #e5e7eb; background-color: #e5e7eb;
} }
@@ -535,3 +545,237 @@ color: var(--btn-check);
.suggestion-list li:hover { .suggestion-list li:hover {
background: #334155; background: #334155;
} }
/* Summary */
.budget-overview-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 8px 0 16px;
}
.budget-summary-box,
.budget-chart-box {
flex: 1 1 250px;
background-color: var(--bg-card);
padding: 8px 12px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
min-width: 220px;
background-color: var(--bg-card);
color: var(--text-main);
}
.budget-summary-box h3,
.budget-chart-box h3 {
margin: 0 0 6px;
font-size: 13px;
font-weight: 600;
color: var(--text-main);
}
.summary-list,
.category-summary-list {
list-style: none;
padding: 0;
margin: 0;
}
.summary-list li,
.category-summary-list li {
display: flex;
justify-content: space-between;
padding: 1px 0;
font-size: 12px;
font-weight: 500;
line-height: 1.4;
color: var(--text-main);
}
.summary-list li span:first-child {
font-weight: 600;
color: var(--text-sub);
}
.category-summary-list li {
border-top: 1px dashed var(--border-color);
padding: 3px 0;
font-size: 11.5px;
}
.highlight {
font-weight: 700;
}
.highlight.leftover.plus {
color: #15803d;
}
.highlight.leftover.minus {
color: #dc2626;
}
/* chart */
.chart-area {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.chart-legend h4 {
margin: 0 0 6px;
font-size: 13px;
font-weight: 600;
}
.chart-area {
flex: 1;
min-width: 200px;
max-width: 340px;
}
canvas {
max-width: 100%;
height: auto;
}
body.dark-mode {
--item-divider: rgba(255, 255, 255, 0.05); /* för mörk bakgrund */
}
.item-row:not(.total-row) {
border-bottom: 1px solid var(--item-divider);
padding-bottom: 4px;
margin-bottom: 4px;
}
@media (min-width: 769px) {
.budget-overview-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
align-items: start;
}
.budget-chart-box {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 300px;
text-align: center;
}
.budget-chart-box .chart-row {
display: flex;
justify-content: center;
align-items: center;
}
.budget-chart-box .chart-area {
flex: 1;
max-width: 420px;
width: 100%;
}
.budget-chart-box canvas {
max-width: 100%;
height: auto;
}
.item-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 4px 8px;
border-bottom: 1px solid var(--border-color);
}
.item-label {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
display: inline-block;
}
.amount {
flex-shrink: 0;
white-space: nowrap;
font-weight: bold;
}
}
@media (max-width: 768px) {
.item-label {
white-space: normal;
overflow-wrap: break-word;
word-break: break-word;
flex: 1 1 auto;
max-width: 100%;
}
.amount {
white-space: nowrap;
text-align: right;
flex-shrink: 0;
}
.budget-grid {
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
}
.budget-overview-row {
display: flex;
flex-direction: column;
gap: 12px;
}
.budget-summary-box,
.budget-chart-box {
width: 100%;
}
.chart-row {
flex-direction: column;
align-items: center;
}
.chart-area {
max-width: 100%;
}
.chart-legend {
width: 100%;
text-align: center;
padding-bottom: 10px;
color: #1E293B; /* djupare textfärg */
font-weight: 600;
}
.chart-area canvas {
max-width: 240px;
height: auto;
}
}
.loading-indicator {
text-align: center;
margin-top: 40px;
font-size: 18px;
color: #64748B;
font-style: italic;
}
[ng-cloak] {
display: none !important;
}

116
Aberwyn/wwwroot/css/lab.css Normal file
View File

@@ -0,0 +1,116 @@
.lab-flex-layout {
display: flex;
gap: 24px;
padding: 24px;
box-sizing: border-box;
}
.lab-section {
background: #fff;
padding: 16px;
border-radius: 8px;
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
flex-grow: 1;
min-width: 0;
color: #1F2C3C;
}
.lab-section.info {
flex: 1;
}
.lab-section.ingredients {
flex: 2;
}
.lab-section.versions {
flex: 1;
max-width: 300px;
overflow-y: auto;
position: sticky;
top: 70px;
}
.lab-section h2 {
margin-top: 0;
font-size: 1.2rem;
}
.lab-field {
margin-bottom: 12px;
display: flex;
flex-direction: column;
}
.lab-field input,
.lab-field textarea {
padding: 6px;
border-radius: 4px;
border: 1px solid #ccc;
font-size: 14px;
}
.ingredient-row {
display: flex;
gap: 10px;
margin-bottom: 8px;
}
.ingredient-row input {
flex: 1;
}
.add-version-form {
margin-top: 24px;
}
.lab-version {
border-top: 1px solid #ddd;
padding-top: 12px;
margin-top: 12px;
}
.version-notes {
font-style: italic;
margin-bottom: 4px;
}
.version-result {
margin-bottom: 6px;
}
input[type="text"],
input[type="number"],
textarea {
width: 100%;
padding: 10px;
font-size: 14px;
border-radius: 6px;
border: 1px solid #ccc;
box-sizing: border-box;
margin-bottom: 12px;
background: #f9f9f9;
}
input:focus,
textarea:focus {
outline: none;
border-color: #6a0dad;
background-color: #fff;
}
button {
background-color: #6a0dad;
color: #fff;
padding: 10px 16px;
border: none;
border-radius: 6px;
font-weight: bold;
font-size: 14px;
cursor: pointer;
margin-top: 12px;
transition: background 0.2s ease;
}
button:hover {
background-color: #5a0ca0;
}

View File

@@ -0,0 +1,110 @@
.page-title {
font-size: 2rem;
color: white;
margin-bottom: 1rem;
text-align: center;
}
.category-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
max-width: 1200px;
margin: auto;
}
.category-row {
display: grid;
grid-template-columns: 2.5fr 1.2fr 1.2fr 1fr auto auto auto;
gap: 0.5rem;
background-color: #1F2C3C;
padding: 0.75rem 1rem;
border-radius: 8px;
align-items: center;
color: white;
}
.category-row.new {
background-color: #2E3C4F;
border: 2px dashed #6a0dad;
}
.category-row input[type="text"],
.category-row input[type="color"],
.category-row input:not([type="checkbox"]) {
padding: 0.4rem;
border: none;
border-radius: 6px;
background-color: #334155;
color: #fefefe;
width: 100%;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.9rem;
color: #ddd;
justify-content: center;
}
.row-actions {
display: flex;
gap: 0.5rem;
}
.row-actions button {
background-color: #6a0dad;
border: none;
color: white;
padding: 0.4rem 0.6rem;
border-radius: 6px;
cursor: pointer;
}
.row-actions button.delete {
background-color: #ef4444;
}
.row-actions i {
pointer-events: none;
}
.name-with-preview {
display: flex;
align-items: center;
gap: 0.5rem;
}
.icon-preview {
width: 32px;
height: 32px;
border-radius: 50%;
background-color: #6a0dad;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.1rem;
color: white;
flex-shrink: 0;
border: 2px solid #ffffff22;
}
.meal-count {
font-size: 0.85rem;
color: #94a3b8;
text-align: right;
white-space: nowrap;
}
@media (max-width: 768px) {
.category-row {
grid-template-columns: 1fr;
}
.meal-count {
text-align: left;
margin-top: 0.25rem;
}
}

View File

@@ -0,0 +1,213 @@
body {
background-color: #f7f7f7;
font-family: 'Segoe UI', sans-serif;
color: #222;
margin: 0;
}
.meal-gallery-container {
margin: 0 auto;
padding: 2rem 1rem;
width: 100%;
max-width: 1200px;
}
/* === Header och sökfält === */
.meal-gallery-header {
text-align: center;
margin-bottom: 1.5rem;
}
.meal-gallery-header h1 {
font-size: 2.2rem;
font-weight: 600;
margin: 0;
}
/* Sökfält + checkbox */
.search-container {
margin-top: 1rem;
position: relative;
width: 100%;
max-width: 600px;
margin-inline: auto;
display: flex;
align-items: center;
gap: 1rem;
background: #e9eef3;
padding: 0.5rem 1rem;
border-radius: 12px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.search-container input[type="text"] {
flex-grow: 1;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid #ccc;
font-size: 1rem;
box-sizing: border-box;
}
.search-container i {
color: #888;
font-size: 1rem;
}
/* Checkboxdel */
.toggle-published {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.9rem;
color: #222;
user-select: none;
white-space: nowrap;
}
.toggle-published input[type="checkbox"] {
accent-color: #3399ff;
transform: scale(1.1);
cursor: pointer;
}
/* === Grid layout === */
.meal-gallery-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
padding-top: 16px;
}
/* === Kortstruktur === */
.meal-card {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
transition: transform 0.2s ease, box-shadow 0.2s ease;
display: flex;
flex-direction: column;
}
.meal-card:hover {
transform: scale(1.015);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.meal-card img {
width: 100%;
height: 180px;
object-fit: cover;
}
.meal-card-content {
padding: 14px;
display: flex;
flex-direction: column;
flex-grow: 1;
}
.meal-card-content h3 {
margin: 0 0 6px;
font-size: 1.15rem;
color: #111;
}
.meal-card-content p {
flex-grow: 1;
font-size: 0.95rem;
color: #555;
margin: 0;
}
/* === Läs mer-knapp === */
.btn-readmore {
align-self: flex-start;
background: #007d36;
color: white;
padding: 7px 12px;
border-radius: 6px;
text-decoration: none;
font-size: 0.9rem;
margin-top: auto;
transition: background-color 0.2s ease;
}
.btn-readmore:hover {
background: #005c27;
}
/* === Mobilanpassning === */
@media (max-width: 600px) {
.meal-gallery-grid {
grid-template-columns: repeat(2, 1fr);
}
.meal-gallery-header h1 {
font-size: 1.6rem;
}
.search-container {
flex-direction: column;
align-items: stretch;
padding: 1rem;
gap: 0.75rem;
max-width: 90%;
}
.search-container input[type="text"] {
font-size: 0.95rem;
}
.toggle-published {
justify-content: center;
}
.meal-card img {
height: 130px;
}
.meal-card-content {
padding: 10px;
}
.meal-card-content h3 {
font-size: 1rem;
}
.meal-card-content p {
font-size: 0.85rem;
}
.btn-readmore {
padding: 6px 10px;
font-size: 0.85rem;
}
}
.btn-create-meal {
background-color: #3399ff;
color: white;
padding: 8px 14px;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 500;
text-decoration: none;
border: none;
cursor: pointer;
transition: background-color 0.2s ease;
white-space: nowrap;
}
.btn-create-meal:hover {
background-color: #2389e0;
}
@media (max-width: 600px) {
.btn-create-meal {
width: 100%;
text-align: center;
}
}

Some files were not shown because too many files have changed in this diff Show More