using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using EveryThing.Data; using EveryThing.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Authorization; namespace EveryThing.Pages.Invoices { [Authorize(Roles = "Administrator,InvoicingUser,ProjecThingUser")] public class CreateModel : PageModel { private readonly ApplicationDbContext _context; private readonly UserManager _userManager; private readonly SignInManager _loginManager; private readonly RoleManager _roleManager; public CreateModel(ApplicationDbContext context, UserManager userManager, SignInManager loginManager, RoleManager roleManager) { _context = context; _userManager = userManager; _loginManager = loginManager; _roleManager = roleManager; } public IActionResult OnGet(int type) { var user = _userManager.GetUserAsync(User).Result; ViewData["Type"] = type; ViewData["IdPartnerFk"] = new SelectList(_context.CodeTablePartners.Where(x => x.IdCompanyFk == user.IdCompanyFk && x.Active), "IdPartner", "Title"); Invoice = new Models.Invoice.Invoice { PreText = "", PostText = "" }; return Page(); } [BindProperty] public Models.Invoice.Invoice Invoice { get; set; } // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. public async Task OnPostAsync(int type) { if (!ModelState.IsValid) { return Page(); } var user = _userManager.GetUserAsync(User).Result; var invoice = Invoice; SetNewInvoice(user.IdCompanyFk, (Models.Invoice.Invoice.InvoiceType)type, ref invoice, _context); invoice.PostText = invoice.PostText.Replace("

", ""); invoice.PreText = invoice.PreText.Replace("

", ""); _context.Invoices.Add(invoice); await _context.SaveChangesAsync(); return RedirectToPage("./Edit", new { id = invoice.IdInvoice }); } public static void SetNewInvoice(int idCompany, Models.Invoice.Invoice.InvoiceType type, ref Models.Invoice.Invoice invoice, ApplicationDbContext context) { var year = DateTime.Now.Year; invoice.InvoiceYear = year; invoice.State = Models.Invoice.Invoice.InvoiceState.New; invoice.Type = type; var items = context.Invoices .Where(x => x.IdCompanyFk == idCompany && x.InvoiceYear == year && x.Type == type).ToList(); invoice.InvoiceNumber = items == null || items.Count <= 0 ? 1 : items.Max(x => x.InvoiceNumber) + 1; invoice.IdCompanyFk = idCompany; } } }