using System.Security.Claims; using JobsMedical.Web.Data; using JobsMedical.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace JobsMedical.Web.Pages.Me; /// Job alerts (هشدار شغلی) — saved searches that notify the user on a new matching listing. [Authorize] public class AlertsModel : PageModel { private readonly AppDbContext _db; public AlertsModel(AppDbContext db) => _db = db; public List Roles { get; private set; } = new(); public List Cities { get; private set; } = new(); public List Alerts { get; private set; } = new(); [TempData] public string? Msg { get; set; } [BindProperty] public string? Label { get; set; } [BindProperty] public AlertScope Scope { get; set; } = AlertScope.Any; [BindProperty] public int? RoleId { get; set; } [BindProperty] public int? CityId { get; set; } [BindProperty] public ShiftType? ShiftType { get; set; } [BindProperty] public EmploymentType? EmploymentType { get; set; } [BindProperty] public long? MinPay { get; set; } private int Uid => int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); public async Task OnGetAsync() => await LoadAsync(); public async Task OnPostCreateAsync() { if (await _db.JobAlerts.CountAsync(a => a.UserId == Uid) >= 20) { Msg = "حداکثر تعداد هشدار شغلی ساخته شده است."; return RedirectToPage(); } _db.JobAlerts.Add(new JobAlert { UserId = Uid, Label = string.IsNullOrWhiteSpace(Label) ? null : Label.Trim(), Scope = Scope, RoleId = RoleId, CityId = CityId, ShiftType = Scope == AlertScope.Jobs ? null : ShiftType, EmploymentType = Scope == AlertScope.Shifts ? null : EmploymentType, MinPay = MinPay is > 0 ? MinPay : null, }); await _db.SaveChangesAsync(); Msg = "هشدار شغلی ساخته شد. به‌محض ثبت آگهی متناسب، باخبر می‌شوی."; return RedirectToPage(); } public async Task OnPostToggleAsync(int id) { var a = await _db.JobAlerts.FirstOrDefaultAsync(x => x.Id == id && x.UserId == Uid); if (a is not null) { a.IsActive = !a.IsActive; await _db.SaveChangesAsync(); } return RedirectToPage(); } public async Task OnPostDeleteAsync(int id) { var a = await _db.JobAlerts.FirstOrDefaultAsync(x => x.Id == id && x.UserId == Uid); if (a is not null) { _db.JobAlerts.Remove(a); await _db.SaveChangesAsync(); } return RedirectToPage(); } private async Task LoadAsync() { Roles = await _db.Roles.Where(r => r.IsActive).OrderBy(r => r.SortOrder).ToListAsync(); Cities = await _db.Cities.Where(c => c.IsActive).OrderBy(c => c.Name).ToListAsync(); Alerts = await _db.JobAlerts.Include(a => a.Role).Include(a => a.City) .Where(a => a.UserId == Uid).OrderByDescending(a => a.CreatedAt).ToListAsync(); } }