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

@@ -34,6 +34,7 @@
<PackageReference Include="Htmx" Version="0.0.15" />
<PackageReference Include="Htmx.TagHelpers" Version="0.0.15" />
<PackageReference Include="LettuceEncrypt" Version="1.1.2" />
<PackageReference Include="MailKit" Version="3.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.1" />

View File

@@ -112,7 +112,7 @@ namespace EveryThing.Pages.CodeTableItems
sellingPrice = projectPartItem.SellingPrice;
differenceInPricePercentage = projectPartItem.DifferenceInPricePercentage;
materialDimensions = projectPartItem.MaterialDimensions;
material = projectPartItem.Material.Title;
material = projectPartItem?.Material?.Title;
}
}

View File

@@ -61,6 +61,29 @@
</span>
</h4>
<div class="card pt-2" style="width: 595pt; margin-bottom:10px;">
<div class="card-body">
<div class="row">
<div class="col-6">
<div class="d-flex align-items-center">
<select id="selTranslationLangue" asp-items="Html.GetEnumSelectList<PrintModel.PrintTranslationLanguage>()" class="form-control form-control-sm" style="width: 200px;">
</select>
<button id="btnTranslate" type="button" class="btn btn-sm btn-success ml-2" data-style="zoom-out" onclick="setLanguage();return false;">Prevedi</button>
</div>
</div>
<div class="col-6 text-right">
@if (Model.Invoice.State == Models.Invoice.Invoice.InvoiceState.New)
{
<button id="btnPrintAndConfirm" type="button" class="btn btn-sm btn-success btn-print ladda-button pull-right" data-style="zoom-out" data-confirm="true"><i class="ion ion-md-print"></i>&nbsp; Natisni in potrdi</button>
}
<button id="btnPrint" type="button" class="btn btn-sm btn-primary btn-print ladda-button pull-right" data-style="zoom-out"><i class="ion ion-md-print"></i>&nbsp; Natisni</button>
<button id="btnSend" type="button" class="btn btn-sm btn-secondary ladda-button pull-right" data-style="zoom-out"><i class="far fa-envelope"></i>&nbsp; Pošlji</button>
</div>
</div>
</div>
</div>
<div class="card pt-2" style="width: 595pt">
<div id="print-content" class="card-body pb-4 pl-4 pt-0" style="padding-right: 2rem !important">
@@ -253,23 +276,6 @@
<div style="display: none" id="footer2">Tel.: @Html.DisplayFor(modelItem => Model.Invoice.Company.Phone), @Html.DisplayFor(modelItem => Model.Invoice.Company.Bank); IBAN: @Html.DisplayFor(modelItem => Model.Invoice.Company.Iban); SWIFT/BIC: @Html.DisplayFor(modelItem => Model.Invoice.Company.SwiftBic)</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-6">
<select id="selTranslationLangue" asp-items="Html.GetEnumSelectList<PrintModel.PrintTranslationLanguage>()" class="form-control" style="width: 200px;">
</select>
<button id="btnTranslate" type="button" class="btn btn-success pull-right" data-style="zoom-out" onclick="setLanguage();return false;">Prevedi</button>
</div>
<div class="col-6 text-right">
@if (Model.Invoice.State == Models.Invoice.Invoice.InvoiceState.New)
{
<button id="btnPrintAndConfirm" type="button" class="btn btn-success btn-print ladda-button pull-right" data-style="zoom-out" data-confirm="true"><i class="ion ion-md-print"></i>&nbsp; Natisni in potrdi</button>
}
<button id="btnPrint" type="button" class="btn btn-primary btn-print ladda-button pull-right" data-style="zoom-out"><i class="ion ion-md-print"></i>&nbsp; Natisni</button>
</div>
</div>
</div>
</div>
@Html.AntiForgeryToken()
@@ -281,6 +287,7 @@
<script>
var laddaPrint = Ladda.create(document.querySelector('#btnPrint'));
var laddaSend = Ladda.create(document.querySelector('#btnSend'));
var laddaPrintAndConfirm = document.querySelector('#btnPrintAndConfirm') == null ? null : Ladda.create(document.querySelector('#btnPrintAndConfirm'));
var element = document.getElementById('print-content');
@@ -300,43 +307,40 @@
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
function buildPdf(callback) {
html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdf) {
var totalPages = pdf.internal.getNumberOfPages();
for (var i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(8);
pdf.setTextColor(0);
var fontSize = pdf.internal.getFontSize();
var pageWidth = pdf.internal.pageSize.width;
var txt = $('#footer1').text();
var txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
var x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 8, txt);
txt = $('#footer2').text();
txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 5, txt);
}
callback(pdf);
});
}
function print(confirm) {
laddaPrint.start();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.start();
}
html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdf) {
var totalPages = pdf.internal.getNumberOfPages();
for (i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(8);
pdf.setTextColor(0);
var fontSize = pdf.internal.getFontSize();
var pageWidth = pdf.internal.pageSize.width;
var txt = $('#footer1').text();
var txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
var x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 8, txt);
txt = $('#footer2').text();
txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 5, txt);
//pdf.addImage("YOUR_IMAGE", 'JPEG', pdf.internal.pageSize.getWidth() - 1.1, pdf.internal.pageSize.getHeight() - 0.25, 1, 0.2);
}
buildPdf(function (pdf) {
laddaPrint.stop();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.stop();
}
//window.open(pdf.output('bloburl'), '_blank');
let link = document.createElement('a');
link.target = '_blank';
link.href = pdf.output('bloburl');
@@ -346,7 +350,6 @@
if (confirm) {
confirmInvoice();
}
});
}
@@ -358,6 +361,85 @@
print($(this).attr("data-confirm") === 'true');
});
$('#btnSend').click(function () {
send();
});
function send() {
var partnerEmail = '@Html.Raw(Model.Invoice.Partner?.Email ?? "")';
var partnerTitle = '@Html.Raw(Model.Invoice.Partner?.Title ?? "")';
var emailInput = document.createElement('input');
emailInput.type = 'email';
emailInput.value = partnerEmail;
if (!partnerEmail || !emailInput.checkValidity()) {
Swal.fire('Napaka', `Partner nima veljavnega e-poštnega naslova (${partnerEmail}).`, 'error');
return;
}
Swal.fire({
title: 'Pošlji dokument',
html: 'Dokument bo poslan na:<br>' + partnerTitle + ' (' + partnerEmail + ')',
icon: 'question',
showCancelButton: true,
showDenyButton: true,
confirmButtonText: 'Pošlji s prilogo',
denyButtonText: 'Pošlji',
cancelButtonText: 'Prekliči',
denyButtonColor: '#007bff'
}).then(function (result) {
if (result.isConfirmed) {
laddaSend.start();
buildPdf(function (pdf) {
var formData = new FormData();
formData.append('pdfFile', pdf.output('blob'), '@(Model.Invoice.InvoiceNumberFull.Replace("-", "_"))' + '.pdf');
formData.append('idInvoice', @Model.Invoice.IdInvoice);
formData.append('withAttachment', 'true');
sendDocument(formData);
});
} else if (result.isDenied) {
laddaSend.start();
buildPdf(function (pdf) {
var formData = new FormData();
formData.append('pdfFile', pdf.output('blob'), '@(Model.Invoice.InvoiceNumberFull.Replace("-", "_"))' + '.pdf');
formData.append('idInvoice', @Model.Invoice.IdInvoice);
formData.append('withAttachment', 'false');
sendDocument(formData);
});
}
});
}
function sendDocument(formData) {
$.blockUI();
$.ajax({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: 'Print/?handler=SendDocument',
data: formData,
processData: false,
contentType: false,
success: function (data) {
laddaSend.stop();
if (data.successful) {
Swal.fire('Dokument poslan', '', 'success');
} else {
Swal.fire('Napaka pri pošiljanju dokumenta', data.error, 'error');
}
$.unblockUI();
},
error: function (xhr, ajaxOptions, thrownError) {
laddaSend.stop();
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
}
function confirmInvoice() {
$.blockUI();
$.ajax({

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;

View File

@@ -739,14 +739,15 @@
</div>
<div class="card-footer py-3">
<div class="row">
<div class="col-6">
<div class="col-9">
<button class="btn btn-success" onclick="createOrderSelectPartner(false); return false;">Kreiraj naročilo</button>
<button class="btn btn-success" onclick="createOrderSelectPartner(true); return false;">Kreiraj povpraševanje</button>
<button class="btn btn-success" onclick="createOrderSelectPartner(true); return false;">Kreiraj povpraševanje materiala</button>
<button class="btn btn-secondary" onclick="createOrderSelectPartner(true, 2); return false;">Kreiraj povpraševanje izdelka</button>
<button class="btn btn-info" onclick="createCooperationSelectPartner(); return false;">Kreiraj kooperacijo</button>
<button class="btn btn-primary" onclick="createInvoice(); return false;">Kreiraj dobavnico</button>
</div>
<div class="col-6 text-right">
<div class="col-3 text-right">
<a asp-page="CreatePart" asp-route-idProject="@Model.Project.IdProject" class="btn btn-primary pull-right">Nov del projekta</a>
</div>
</div>
@@ -867,7 +868,7 @@
function tooltips() {
$('[data-toggle="tooltip"]').tooltip();
}
function createOrderSelectPartner(inquiry) {
function createOrderSelectPartner(inquiry, positionsType) {
$.blockUI();
$.ajax({
type: "GET",
@@ -895,7 +896,7 @@
}
}).then((result) => {
if (result.isConfirmed) {
createOrder(inquiry, result.value);
createOrder(inquiry, result.value, positionsType);
}
});
} else {
@@ -914,10 +915,14 @@
});
}
function createOrder(inquiry, idPartner) {
function createOrder(inquiry, idPartner, positionsType) {
if (idPartner == null || idPartner == undefined || isNaN(idPartner))
idPartner = 0;
if (isNaN(positionsType) || positionsType == null || positionsType == undefined){
positionsType = 1;
}
let object = getSelectedPartItems();
if (object.length <= 0) {
@@ -932,7 +937,7 @@
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "Edit/?handler=CreateOrder",
data: { itemsJson: JSON.stringify(object), inquiry: inquiry, idPartner: idPartner },
data: { itemsJson: JSON.stringify(object), inquiry: inquiry, idPartner: idPartner, positionsType: positionsType },
success: function(data) {
if (data.successful) {
if (inquiry) {

View File

@@ -272,7 +272,7 @@ namespace EveryThing.Pages.Projects
return new JsonResult(new { error = "", successful = true, idInvoice });
}
public IActionResult OnPostCreateOrder(string itemsJson, bool inquiry, int idPartner)
public IActionResult OnPostCreateOrder(string itemsJson, bool inquiry, int idPartner, int positionsType)
{
var user = _userManager.GetUserAsync(User).Result;
@@ -330,16 +330,24 @@ namespace EveryThing.Pages.Projects
{
var newInvoiceItem = new Models.Invoice.InvoiceItem
{
Discount = 0,
IdInvoiceFk = idInvoice,
IdProjectPartItem = projectPartItem.IdProjectPartItem,
IdItemFk = projectPartItem.IdMaterialFk,
ItemDescription = projectPartItem.MaterialDimensions,
Note = "",
Price = projectPartItem.MaterialPrice,
//Quantity = projectPartItem.NumberOfItems * projectPartItem.NumberOfSets
Quantity = projectPartItem.NumberOfItems
Discount = 0,
IdInvoiceFk = idInvoice,
IdProjectPartItem = projectPartItem.IdProjectPartItem,
Note = "",
Price = projectPartItem.MaterialPrice,
Quantity = projectPartItem.NumberOfItems
};
if (positionsType == 2)
{
newInvoiceItem.IdItemFk = projectPartItem.IdItemFk;
}
else
{
newInvoiceItem.IdItemFk = projectPartItem.IdMaterialFk;
newInvoiceItem.ItemDescription = projectPartItem.MaterialDimensions;
}
_context.InvoiceItems.Add(newInvoiceItem);
}
_context.SaveChanges();

View File

@@ -2,6 +2,15 @@
"ConnectionStrings": {
"DataConnection": "server=192.168.1.12;user=everything;password=EveryThing2022!;database=EveryThingDev"
},
"EmailSettings": {
"Host": "mail.no-reply.si",
"Port": 465,
"SecureSocketOptions": "SslOnConnect",
"Username": "cnc-paradiz@no-reply.si",
"Password": "52svchwokzce#ss",
"FromEmail": "cnc-paradiz@no-reply.si",
"FromName": "CNC - Paradiž"
},
"Logging": {
"LogLevel": {
"Default": "Information",