tiskanje in posiljanje po mailo

This commit is contained in:
2026-03-03 09:16:17 +01:00
parent 1da4b1e751
commit 4cdfbace03
7 changed files with 258 additions and 55 deletions

View File

@@ -3,10 +3,16 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using EveryThing.Data;
using EveryThing.Models;
using EveryThing.Models.Invoice;
@@ -55,16 +61,20 @@ namespace EveryThing.Pages.Invoices
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityApplicationUser> _userManager;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _environment;
public Models.Invoice.Invoice Invoice { get; set; }
public PrintTranslation Translation { get; set; }
public IList<Models.Invoice.InvoiceItem> InvoiceItems { get; set; }
public string ProjectNumber { get; set; }
public PrintModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager)
public PrintModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager, IConfiguration configuration, IWebHostEnvironment environment)
{
_context = context;
_userManager = userManager;
_configuration = configuration;
_environment = environment;
}
public async Task<IActionResult> OnGetAsync(int id, int? printTranslationLanguage)
@@ -112,6 +122,94 @@ namespace EveryThing.Pages.Invoices
return NotFound();
}
public async Task<IActionResult> OnPostSendDocumentAsync(IFormFile pdfFile, int idInvoice, bool withAttachment)
{
if (pdfFile == null || pdfFile.Length == 0)
return new JsonResult(new { successful = false, error = "PDF datoteka je obvezna." });
var user = await _userManager.GetUserAsync(User);
try
{
var invoice = await _context.Invoices
.Include(x => x.Partner)
.Include(x => x.Company)
.FirstOrDefaultAsync(x => x.IdInvoice == idInvoice && x.IdCompanyFk == user.IdCompanyFk);
if (invoice == null)
return new JsonResult(new { successful = false, error = "Invoice not found." });
using var stream = pdfFile.OpenReadStream();
var pdfBytes = new byte[pdfFile.Length];
await stream.ReadAsync(pdfBytes, 0, (int)pdfFile.Length);
var attachments = new List<Models.File>();
if (withAttachment)
{
var itemIds = await _context.InvoiceItems
.Where(x => x.IdInvoiceFk == idInvoice && x.IdItemFk != null)
.Select(x => x.IdItemFk.Value)
.Distinct()
.ToListAsync();
if (itemIds.Any())
{
attachments = await _context.Files
.Where(x => x.IdCompanyFk == user.IdCompanyFk
&& itemIds.Contains(x.IdReferenceFk)
&& x.FileType == FileType.CodeTableItem)
.ToListAsync();
}
}
var emailSettings = _configuration.GetSection("EmailSettings");
var host = emailSettings["Host"];
var port = int.Parse(emailSettings["Port"] ?? "587");
var secureSocketOptions = Enum.Parse<SecureSocketOptions>(emailSettings["SecureSocketOptions"] ?? "StartTls");
var username = emailSettings["Username"];
var password = emailSettings["Password"];
var fromEmail = emailSettings["FromEmail"];
var fromName = emailSettings["FromName"];
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(fromName, fromEmail));
mimeMessage.To.Add(new MailboxAddress(invoice.Partner.Title, invoice.Partner.Email));
mimeMessage.Subject = invoice.InvoiceNumberFull;
var bodyBuilder = new BodyBuilder
{
TextBody = $"Spoštovani,\n\nv prilogi vam pošiljamo dokument {invoice.InvoiceNumberFull}.\n\nLep pozdrav,\n{invoice.Company.Title}"
};
bodyBuilder.Attachments.Add(invoice.InvoiceNumberFull + ".pdf", pdfBytes, new ContentType("application", "pdf"));
var filesFolder = System.IO.Path.Combine(_environment.WebRootPath, "Uploads", "Files", ((int)FileType.CodeTableItem).ToString());
foreach (var file in attachments)
{
var filePath = System.IO.Path.Combine(filesFolder, file.Guid + file.Extension);
if (System.IO.File.Exists(filePath))
{
var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
bodyBuilder.Attachments.Add(file.Title + file.Extension, fileBytes);
}
}
mimeMessage.Body = bodyBuilder.ToMessageBody();
using var smtpClient = new SmtpClient();
await smtpClient.ConnectAsync(host, port, secureSocketOptions);
await smtpClient.AuthenticateAsync(username, password);
await smtpClient.SendAsync(mimeMessage);
await smtpClient.DisconnectAsync(true);
}
catch (Exception ex)
{
return new JsonResult(new { successful = false, error = ex.Message });
}
return new JsonResult(new { successful = true });
}
public IActionResult OnPostConfirmInvoice(int idInvoice)
{
var user = _userManager.GetUserAsync(User).Result;