771 lines
39 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using gehGassi.Common.Data;
using gehGassi.Core.Interfaces;
using gehGassi.Core.Services;
using gehGassi.Domain.Common;
using gehGassi.Permissions;
using gehGassi.Web.Auth;
using gehGassi.Web.Auth.Attributes;
using gehGassi.Web.Helper;
using gehGassi.Web.Models;
using gehGassi.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Localization;
namespace gehGassi.Web.Controllers
{
/// <summary>
/// Controller für die Verwaltung von Listingen
/// </summary>
[Authorize]
public class OrderController : BaseController
{
private readonly IMapper _mapper;
private readonly IStringLocalizer<OrderController> _localizer;
private readonly IOrderService _orderService;
private readonly IAuditService _auditService;
private readonly IListingService _listingService;
private readonly ICountryService _countryService;
private readonly ICustomerService _customerService;
private readonly IKlarnaService _klarnaService;
private readonly IShopSettingsService _shopSettingsService;
private readonly IAdvertisementService _advertisementService;
private readonly IBannerService _bannerService;
private readonly IPinService _pinService;
private readonly IInvoiceService _invoiceService;
private readonly IWebHostEnvironment _environment;
private readonly IUrlHelperFactory _urlHelperFactory;
private readonly IEmailSender _emailSender;
private readonly ICreditNoteService _creditNoteService;
/// <summary>
/// Erstellt eine Instanz
/// </summary>
/// <param name="mapper">Instanz eines IMapper</param>
/// <param name="localizer">Instanz eines IStringLocalizer</param>
/// <param name="orderService">Instanz eines IOrderService</param>
/// <param name="auditService">Instzanz eines IAuditService</param>
/// <param name="listingService">Instanz eines IListingService</param>
/// <param name="countryService">Instanz eines ICountryService</param>
/// <param name="customerService">Instanz eines ICustomerService</param>
/// <param name="klarnaService">Instanz eines IKlarnaService</param>
/// <param name="shopSettingsService">Instanz eines IShopSettingsService</param>
/// <param name="advertisementService">Instanz eines IAdvertisementService</param>
/// <param name="bannerService">Instanz eines IBannerService</param>
/// <param name="pinService">Instanz eines IPinService</param>
/// <param name="invoiceService">Instanz eines IInvoiceService</param>
/// <param name="environment">Instanz eines IWebHostEnvironment</param>
/// <param name="urlHelperFactory">Instanz einer IUrlHelperFactory</param>
/// <param name="emailSender">Instanz eines IEmailSender</param>
/// <param name="creditNoteService">Instanz eines ICreditNoteService</param>
public OrderController(IMapper mapper, IStringLocalizer<OrderController> localizer, IOrderService orderService, IAuditService auditService, IListingService listingService,
ICountryService countryService, ICustomerService customerService, IKlarnaService klarnaService, IShopSettingsService shopSettingsService, IAdvertisementService advertisementService,
IBannerService bannerService, IPinService pinService, IInvoiceService invoiceService, IWebHostEnvironment environment, IUrlHelperFactory urlHelperFactory,
IEmailSender emailSender, ICreditNoteService creditNoteService)
{
_mapper = mapper;
_localizer = localizer;
_orderService = orderService;
_auditService = auditService;
_listingService = listingService;
_countryService = countryService;
_customerService = customerService;
_klarnaService = klarnaService;
_shopSettingsService = shopSettingsService;
_advertisementService = advertisementService;
_bannerService = bannerService;
_pinService = pinService;
_invoiceService = invoiceService;
_environment = environment;
_urlHelperFactory = urlHelperFactory;
_emailSender = emailSender;
_creditNoteService = creditNoteService;
}
#region Admin / Poweruser
/// <summary>
/// Gibt einen View für die Verwaltung von Listungen zurück
/// </summary>
/// <returns>View</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
public IActionResult Index()
{
return View();
}
/// <summary>
/// Gibt eine Liste von Entitäten basierend auf Abfragekriterien zurück
/// </summary>
/// <param name="dm">Abfragekriterien</param>
/// <returns>Liste von gefundenen Entitäten</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
[HttpPost]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult GetOrders([FromBody] DataManager dm)
{
if (dm != null)
{
var propList = new List<ComplexProperty>();
dm.SetComplexProperties(propList);
if (dm.Where != null)
{
foreach (var whereFilter in dm.Where)
{
if (whereFilter.predicates == null)
continue;
foreach (var whereFilterPredicate in whereFilter.predicates)
{
if (whereFilterPredicate.Field == "orderSource")
whereFilterPredicate.value = (OrderSource)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "orderStatus")
whereFilterPredicate.value = (OrderStatus)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "paymentType")
whereFilterPredicate.value = (PaymentType)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "paymentStatus")
whereFilterPredicate.value = (PaymentStatus)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "shipmentType")
whereFilterPredicate.value = (ShipmentType)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "shipmentStatus")
whereFilterPredicate.value = (ShipmentStatus)((int)((long)whereFilterPredicate.value));
}
}
}
}
var resultList = _orderService.Filter(dm?.SearchValue ?? "", includeDeleted: false);
//Sortierung
resultList = dm.ApplySorting(resultList);
//Filter
resultList = dm.ApplyFiltering(resultList, out var countFiltered);
//Paging
resultList = dm.ApplyPaging(resultList);
var resultListVm = resultList.ToList().Select(item => _mapper.Map<OrderListVm>(item)).ToList();
foreach (var itemVm in resultListVm)
{
itemVm.OrderSourceText = itemVm.OrderSource.GetDisplayName(AnnotationsLocalizer);
itemVm.OrderStatusText = itemVm.OrderStatus.GetDisplayName(AnnotationsLocalizer);
itemVm.PaymentTypeText = itemVm.PaymentType.GetDisplayName(AnnotationsLocalizer);
itemVm.PaymentStatusText = itemVm.PaymentStatus.GetDisplayName(AnnotationsLocalizer);
itemVm.ShipmentTypeText = itemVm.ShipmentType.GetDisplayName(AnnotationsLocalizer);
itemVm.ShipmentStatusText = itemVm.ShipmentStatus.GetDisplayName(AnnotationsLocalizer);
}
//FilterPreview?
if (!dm.RequiresCounts)
return Json(resultListVm);
return Json(new { result = resultListVm, count = countFiltered });
}
/// <summary>
/// Details einer Bestellung
/// </summary>
/// <param name="id">Id der Listung</param>
/// <returns>PartialView</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> Details(long id)
{
var order = await _orderService.GetAsync(id);
if (order != null)
{
var model = _mapper.Map<OrderVm>(order);
var orderItems = await _orderService.GetItemsAsync(order.Id);
foreach (var orderItem in orderItems)
{
var orderItemVm = _mapper.Map<OrderItemVm>(orderItem);
if (orderItem.ProductType == ProductType.Listing)
{
var listing = await _listingService.GetByOrderItemAsync(orderItem.Id);
if (listing != null)
{
var country = _countryService.GetCountry(listing.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {listing.StartDate.Value.Date.ToShortDateString()} - {listing.EndDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Advertisement)
{
var advertisement = await _advertisementService.GetByOrderItemAsync(orderItem.Id);
if (advertisement != null)
{
var country = _countryService.GetCountry(advertisement.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {advertisement.StartDate.Value.Date.ToShortDateString()} - {advertisement.EndDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Banner)
{
var banner = await _bannerService.GetByOrderItemAsync(orderItem.Id);
if (banner != null)
{
var country = _countryService.GetCountry(banner.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {banner.StartDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Pin)
{
var pin = await _pinService.GetByOrderItemAsync(orderItem.Id);
if (pin != null)
{
orderItemVm.ProductSpecialInfo = $"Lat: {pin.Location.Y.ToString("N6")} Lng: {pin.Location.X.ToString("N6")} Rad: {pin.Radius.ToString("N2")}km | {pin.StartDate.Value.Date.ToShortDateString()} - {pin.EndDate.Value.Date.ToShortDateString()}";
}
}
model.Items.Add(orderItemVm);
}
await _auditService.LogAccessAsync(order.Id.ToString(), order.AuditTable(), User.Identity.Name);
return PartialView("_Details", model);
}
return PartialView("_Error");
}
/// <summary>
/// Aktualisieren eines der Stati einer Bestellung.
/// Kann z.B. OrderStatus, PaymentStatus usw. sein
/// </summary>
/// <param name="model">Model</param>
/// <returns>JSON</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
[HttpPost]
public async Task<IActionResult> UpdateOrderStatus([FromBody] UpdateOrderStatusVm model)
{
if (ModelState.IsValid)
{
try
{
var uniqueId = Guid.Parse(model.PrimaryKey);
var order = await _orderService.GetByUniqueIdAsync(uniqueId);
if (order != null)
{
if (model.Name.ToLower() == "orderstatus")
{
var statusValue = int.Parse(model.Value);
var oldValue = order.OrderStatus;
order.OrderStatus = (OrderStatus)statusValue;
//Stornierung behandeln
if (order.OrderStatus == OrderStatus.Cancelled && oldValue != OrderStatus.Cancelled)
{
//Listungen setzen....
await _listingService.SetStatusByOrderAsync(order.Id, ListingStatus.Cancelled, null);
await _listingService.CommitAsync(User.Identity.Name);
//Werbungen setzen....
await _advertisementService.SetStatusByOrderAsync(order.Id, AdvertisementStatus.Cancelled);
await _advertisementService.CommitAsync(User.Identity.Name);
//Banner setzen....
await _bannerService.SetStatusByOrderAsync(order.Id, BannerStatus.Cancelled);
await _bannerService.CommitAsync(User.Identity.Name);
//Pin setzen....
await _pinService.SetStatusByOrderAsync(order.Id, PinStatus.Cancelled);
await _pinService.CommitAsync(User.Identity.Name);
}
order.LastUpdate = DateTimeOffset.UtcNow;
await _orderService.CommitAsync(User.Identity.Name);
}
if (model.Name.ToLower() == "paymentstatus")
{
var statusValue = int.Parse(model.Value);
var oldStatusValue = order.PaymentStatus;
order.PaymentStatus = (PaymentStatus)statusValue;
if (order.PaymentStatus == PaymentStatus.Paid)
{
if (order.PaymentDate == null)
{
order.PaymentDate = DateTimeOffset.UtcNow;
var invoice = await _invoiceService.CreateAsync(order.Id);
_invoiceService.Add(invoice);
await _invoiceService.CommitAsync(User.Identity.Name);
//Listungen setzen....
await _listingService.SetStatusByOrderAsync(order.Id, ListingStatus.Booked, null);
await _listingService.SetPaymentStatusByOrderAsync(order.Id, PaymentStatus.Paid);
await _listingService.CommitAsync(User.Identity.Name);
//Werbungen setzen....
await _advertisementService.SetStatusByOrderAsync(order.Id, AdvertisementStatus.Booked);
await _advertisementService.SetPaymentStatusByOrderAsync(order.Id, PaymentStatus.Paid);
await _advertisementService.CommitAsync(User.Identity.Name);
//Banner setzen....
await _bannerService.SetStatusByOrderAsync(order.Id, BannerStatus.Booked);
await _bannerService.SetPaymentStatusByOrderAsync(order.Id, PaymentStatus.Paid);
await _bannerService.CommitAsync(User.Identity.Name);
//Pin setzen....
await _pinService.SetStatusByOrderAsync(order.Id, PinStatus.Booked);
await _pinService.SetPaymentStatusByOrderAsync(order.Id, PaymentStatus.Paid);
await _pinService.CommitAsync(User.Identity.Name);
//Rechnung senden
var fileName = $"{invoice.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "Invoice", new { orderId = order.Id, language = SelectedLanguage });
await SendInvoiceAsync(order.Id, fileName, file);
await SendInvoiceCustomerAsync(order.Id, fileName, file);
}
}
if (order.PaymentStatus == PaymentStatus.Refunded && oldStatusValue != PaymentStatus.Refunded)
{
//Gutschrift erstellen...
var invoice = await _invoiceService.GetByOrderAsync(order.Id);
if (invoice != null)
{
var creditNote = await _creditNoteService.GetByOrderAsync(order.Id);
if (creditNote == null)
{
creditNote = await _creditNoteService.CreateAsync(order.Id, invoice.Number);
_creditNoteService.Add(creditNote);
await _creditNoteService.CommitAsync(User.Identity.Name);
}
}
}
order.LastUpdate = DateTimeOffset.UtcNow;
await _orderService.CommitAsync(User.Identity.Name);
}
if (model.Name.ToLower() == "shipmentstatus")
{
var statusValue = int.Parse(model.Value);
order.ShipmentStatus = (ShipmentStatus)statusValue;
if (order.ShipmentStatus == ShipmentStatus.Shipped)
{
if (order.PaymentType == PaymentType.Klarna)
{
if (order.ShipmentDate == null && order.PaymentStatus == PaymentStatus.Paid)
{
var shopSettings = await _shopSettingsService.GetAsync();
order.KlarnaShipmentSentDate = DateTimeOffset.UtcNow;
await _klarnaService.CaptureOrderAsync(order.Id, shopSettings.KlarnaClientId, shopSettings.KlarnaSecret);
}
}
order.ShipmentDate = DateTimeOffset.UtcNow;
}
order.LastUpdate = DateTimeOffset.UtcNow;
await _orderService.CommitAsync(User.Identity.Name);
}
}
}
catch { }
}
return Json(model);
}
/// <summary>
/// Anzeigen einer Rechnung oder Proforma Rechnung zu einer Bestellung
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <returns>PDF</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
public async Task<IActionResult> ShowInvoice(long orderId)
{
var order = await _orderService.GetAsync(orderId);
if (order != null)
{
if (order.PaymentType == PaymentType.Invoice && order.PaymentDate == null)
{
var fileName = $"{order.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "InvoiceProforma", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
else
{
var invoice = await _invoiceService.GetByOrderAsync(order.Id);
if (invoice != null)
{
var fileName = $"{invoice.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "Invoice", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
}
}
return View("Error");
}
/// <summary>
/// Anzeigen einer Gutschrift zu einer Bestellung
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <returns>PDF</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
public async Task<IActionResult> ShowCreditNote(long orderId)
{
var order = await _orderService.GetAsync(orderId);
if (order != null)
{
var creditNote = await _creditNoteService.GetByOrderAsync(order.Id);
if (creditNote != null)
{
var fileName = $"{creditNote.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "CreditNote", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
}
return View("Error");
}
#endregion
#region Customer
/// <summary>
/// Gibt einen View für die Verwaltung von Listungen für Kunden zurück
/// </summary>
/// <returns>View</returns>
[Authorize(Policy = Policies.CustomerOnly)]
[HasPermission(Permission.OrdersAccess)]
public async Task<IActionResult> IndexCustomer()
{
var customer = await _customerService.GetAsync(User.CustomerId().Value);
if (customer != null)
{
return View(customer.UniqueId.Value);
}
return RedirectToAction("Error", "Home");
}
/// <summary>
/// Gibt eine Liste von Entitäten basierend auf Abfragekriterien zurück
/// </summary>
/// <param name="dm">Abfragekriterien</param>
/// <param name="customerUniqueId">UniqueId des Kunden</param>
/// <returns>Liste von gefundenen Entitäten</returns>
[Authorize(Policy = Policies.CustomerOnly)]
[HasPermission(Permission.OrdersAccess)]
[CustomerAuthorize("customerUniqueId")]
[HttpPost]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> GetOrdersCustomer([FromBody] DataManager dm, [FromQuery]Guid customerUniqueId)
{
if (dm != null)
{
var propList = new List<ComplexProperty>();
dm.SetComplexProperties(propList);
if (dm.Where != null)
{
foreach (var whereFilter in dm.Where)
{
if (whereFilter.predicates == null)
continue;
foreach (var whereFilterPredicate in whereFilter.predicates)
{
if (whereFilterPredicate.Field == "orderSource")
whereFilterPredicate.value = (OrderSource)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "orderStatus")
whereFilterPredicate.value = (OrderStatus)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "paymentType")
whereFilterPredicate.value = (PaymentType)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "paymentStatus")
whereFilterPredicate.value = (PaymentStatus)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "shipmentType")
whereFilterPredicate.value = (ShipmentType)((int)((long)whereFilterPredicate.value));
if (whereFilterPredicate.Field == "shipmentStatus")
whereFilterPredicate.value = (ShipmentStatus)((int)((long)whereFilterPredicate.value));
}
}
}
}
long customerId = -1;
var customer = await _customerService.GetByUniqueIdAsync(customerUniqueId);
if (customer != null)
customerId = customer.Id;
var resultList = _orderService.FilterByCustomer(dm?.SearchValue ?? "", customerId, false);
//Sortierung
resultList = dm.ApplySorting(resultList);
//Filter
resultList = dm.ApplyFiltering(resultList, out var countFiltered);
//Paging
resultList = dm.ApplyPaging(resultList);
var resultListVm = resultList.ToList().Select(item => _mapper.Map<OrderListVm>(item)).ToList();
foreach (var itemVm in resultListVm)
{
itemVm.OrderSourceText = itemVm.OrderSource.GetDisplayName(AnnotationsLocalizer);
itemVm.OrderStatusText = itemVm.OrderStatus.GetDisplayName(AnnotationsLocalizer);
itemVm.PaymentTypeText = itemVm.PaymentType.GetDisplayName(AnnotationsLocalizer);
itemVm.PaymentStatusText = itemVm.PaymentStatus.GetDisplayName(AnnotationsLocalizer);
itemVm.ShipmentTypeText = itemVm.ShipmentType.GetDisplayName(AnnotationsLocalizer);
itemVm.ShipmentStatusText = itemVm.ShipmentStatus.GetDisplayName(AnnotationsLocalizer);
}
//FilterPreview?
if (!dm.RequiresCounts)
return Json(resultListVm);
return Json(new { result = resultListVm, count = countFiltered });
}
/// <summary>
/// Details einer Bestellung für Kunden
/// </summary>
/// <param name="id">Id der Listung</param>
/// <param name="customerUniqueId">UniqueId des Kunden</param>
/// <returns>PartialView</returns>
[Authorize(Policy = Policies.CustomerOnly)]
[HasPermission(Permission.OrdersAccess)]
[CustomerAuthorize("customerUniqueId")]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> DetailsCustomer(long id, Guid customerUniqueId)
{
var customer = await _customerService.GetByUniqueIdAsync(customerUniqueId);
if (customer != null && customer.Id == User.CustomerId())
{
var order = await _orderService.GetAsync(id);
if (order != null)
{
var model = _mapper.Map<OrderVm>(order);
var orderItems = await _orderService.GetItemsAsync(order.Id);
foreach (var orderItem in orderItems)
{
var orderItemVm = _mapper.Map<OrderItemVm>(orderItem);
if (orderItem.ProductType == ProductType.Listing)
{
var listing = await _listingService.GetByOrderItemAsync(orderItem.Id);
if (listing != null)
{
var country = _countryService.GetCountry(listing.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {listing.StartDate.Value.Date.ToShortDateString()} - {listing.EndDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Advertisement)
{
var advertisement = await _advertisementService.GetByOrderItemAsync(orderItem.Id);
if (advertisement != null)
{
var country = _countryService.GetCountry(advertisement.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {advertisement.StartDate.Value.Date.ToShortDateString()} - {advertisement.EndDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Banner)
{
var banner = await _bannerService.GetByOrderItemAsync(orderItem.Id);
if (banner != null)
{
var country = _countryService.GetCountry(banner.Address.CountryCode);
orderItemVm.ProductSpecialInfo = $"{country.Name} | {banner.StartDate.Value.Date.ToShortDateString()}";
}
}
else if (orderItem.ProductType == ProductType.Pin)
{
var pin = await _pinService.GetByOrderItemAsync(orderItem.Id);
if (pin != null)
{
orderItemVm.ProductSpecialInfo = $"Lat: {pin.Location.Y.ToString("N6")} Lng: {pin.Location.X.ToString("N6")} Rad: {pin.Radius.ToString("N2")}km | {pin.StartDate.Value.Date.ToShortDateString()} - {pin.EndDate.Value.Date.ToShortDateString()}";
}
}
model.Items.Add(orderItemVm);
}
await _auditService.LogAccessAsync(order.Id.ToString(), order.AuditTable(), User.Identity.Name);
return PartialView("_DetailsCustomer", model);
}
}
return PartialView("_Error");
}
/// <summary>
/// Anzeigen einer Rechnung oder Proforma Rechnung zu einer Bestellung für kunden
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <param name="customerUniqueId">UniqueId des Kunden</param>
/// <returns>PDF</returns>
[Authorize(Policy = Policies.CustomerOnly)]
[HasPermission(Permission.OrdersAccess)]
[CustomerAuthorize("customerUniqueId")]
public async Task<IActionResult> ShowInvoiceCustomer(long orderId, Guid customerUniqueId)
{
var customer = await _customerService.GetByUniqueIdAsync(customerUniqueId);
if (customer != null && customer.Id == User.CustomerId())
{
var order = await _orderService.GetAsync(orderId);
if (order != null)
{
if (order.PaymentType == PaymentType.Invoice && order.PaymentDate == null)
{
var fileName = $"{order.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "InvoiceProforma", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
else
{
var invoice = await _invoiceService.GetByOrderAsync(order.Id);
if (invoice != null)
{
var fileName = $"{invoice.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "Invoice", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
}
}
}
return View("Error");
}
/// <summary>
/// Anzeigen einer Gutschrift zu einer Bestellung für kunden
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <param name="customerUniqueId">UniqueId des Kunden</param>
/// <returns>PDF</returns>
[Authorize(Policy = Policies.PowerUserOnly)]
[HasPermission(Permission.OrdersAccess)]
public async Task<IActionResult> ShowCreditNoteCustomer(long orderId, Guid customerUniqueId)
{
var customer = await _customerService.GetByUniqueIdAsync(customerUniqueId);
if (customer != null && customer.Id == User.CustomerId())
{
var order = await _orderService.GetAsync(orderId);
if (order != null)
{
var creditNote = await _creditNoteService.GetByOrderAsync(order.Id);
if (creditNote != null)
{
var fileName = $"{creditNote.Number}.pdf";
var file = ControllerContext.GetPdfWithHeaderAndFooter(_urlHelperFactory, _environment, "Print", "CreditNote", new { orderId = order.Id, language = SelectedLanguage });
var outputStream = new MemoryStream();
outputStream.Write(file, 0, file.Length);
outputStream.Position = 0;
return File(file, "application/pdf", fileName);
}
}
}
return View("Error");
}
#endregion
#region Emails - Rechnung senden
/// <summary>
/// Senden der Rechnung für den Shop-Besitzer
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <param name="fileName">Dateiname einer Datei die mitgesendet werden soll</param>
/// <param name="file">Datei die mitgesendet werden soll</param>
/// <returns>Task</returns>
private async Task SendInvoiceAsync(long orderId, string fileName, byte[] file)
{
var shopSettings = await _shopSettingsService.GetAsync();
var order = await _orderService.GetAsync(orderId);
var invoice = await _invoiceService.GetByOrderAsync(orderId);
var orderVm = _mapper.Map<OrderVm>(order);
var orderItems = await _orderService.GetItemsAsync(order.Id);
foreach (var orderItem in orderItems)
{
var orderItemVm = _mapper.Map<OrderItemVm>(orderItem);
orderVm.Items.Add(orderItemVm);
}
var currentCulture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo(SelectedLanguage);
ViewBag.Invoice = invoice;
var body = await PartialView("mails/_Invoice", orderVm).ToStringAsync(ControllerContext);
var targetEmail = shopSettings.OrderEmail;
if (string.IsNullOrWhiteSpace(fileName))
await _emailSender.SendEmailAsync(targetEmail, $"gehGassi {_localizer["Mail_Invoice"].Value}: {invoice.Number}", body);
else
await _emailSender.SendEmailAsync(targetEmail, $"gehGassi {_localizer["Mail_Invoice"].Value}: {invoice.Number}", body, file, fileName);
CultureInfo.CurrentCulture = currentCulture;
}
/// <summary>
/// Senden der Rechnung für den Kunden
/// </summary>
/// <param name="orderId">Id der Bestellung</param>
/// <param name="fileName">Dateiname einer Datei die mitgesendet werden soll</param>
/// <param name="file">Datei die mitgesendet werden soll</param>
/// <returns>Task</returns>
private async Task SendInvoiceCustomerAsync(long orderId, string fileName, byte[] file)
{
var shopSettings = await _shopSettingsService.GetAsync();
var order = await _orderService.GetAsync(orderId);
var invoice = await _invoiceService.GetByOrderAsync(orderId);
var customer = await _customerService.GetAsync(order.CustomerId.Value);
var orderVm = _mapper.Map<OrderVm>(order);
var orderItems = await _orderService.GetItemsAsync(order.Id);
foreach (var orderItem in orderItems)
{
var orderItemVm = _mapper.Map<OrderItemVm>(orderItem);
orderVm.Items.Add(orderItemVm);
}
var currentCulture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo(SelectedLanguage);
ViewBag.Invoice = invoice;
var body = await PartialView("mails/_InvoiceCustomer", orderVm).ToStringAsync(ControllerContext);
var targetEmail = customer.Contact.Email;
if (string.IsNullOrWhiteSpace(fileName))
await _emailSender.SendEmailAsync(targetEmail, $"gehGassi {_localizer["Mail_Invoice"].Value}: {invoice.Number}", body);
else
await _emailSender.SendEmailAsync(targetEmail, $"gehGassi {_localizer["Mail_Invoice"].Value}: {invoice.Number}", body, file, fileName);
CultureInfo.CurrentCulture = currentCulture;
}
#endregion
}
}