Documenntype? OrderId?

This commit is contained in:
Adam 2025-10-19 13:57:55 +02:00
parent 192904558d
commit 0bee8979b7
4 changed files with 651 additions and 25 deletions

View File

@ -5,6 +5,8 @@ using FruitBank.Common.Interfaces;
using FruitBank.Common.Server.Interfaces;
using FruitBank.Common.SignalRs;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
@ -12,16 +14,21 @@ using Nop.Core.Domain.Tax;
using Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;
using Nop.Plugin.Misc.FruitBankPlugin.Factories;
using Nop.Plugin.Misc.FruitBankPlugin.Models.Orders;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Messages;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Security;
using Nop.Web.Areas.Admin.Controllers;
using Nop.Web.Areas.Admin.Factories;
using Nop.Web.Areas.Admin.Models.Orders;
using Nop.Web.Framework;
using Nop.Web.Framework.Mvc.Filters;
using System.Text.Json.Serialization;
using System.Xml;
using System.Xml.Serialization;
namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
{
@ -36,9 +43,10 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
private readonly IGenericAttributeService _genericAttributeService;
private readonly INotificationService _notificationService;
private readonly ICustomerService _customerService;
private readonly IProductService _productService;
// ... other dependencies
public CustomOrderController(IOrderService orderService, IOrderModelFactory orderModelFactory, ICustomOrderSignalREndpointServer customOrderSignalREndpoint, IPermissionService permissionService, IGenericAttributeService genericAttributeService, INotificationService notificationService, ICustomerService customerService)
public CustomOrderController(IOrderService orderService, IOrderModelFactory orderModelFactory, ICustomOrderSignalREndpointServer customOrderSignalREndpoint, IPermissionService permissionService, IGenericAttributeService genericAttributeService, INotificationService notificationService, ICustomerService customerService, IProductService productService)
{
_orderService = orderService;
_orderModelFactory = orderModelFactory as CustomOrderModelFactory;
@ -47,6 +55,7 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
_genericAttributeService = genericAttributeService;
_notificationService = notificationService;
_customerService = customerService;
_productService = productService;
// ... initialize other deps
}
@ -141,23 +150,30 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
}
[HttpPost]
public virtual async Task<IActionResult> Create(int customerId)
//[CheckPermission(StandardPermission.Orders.ORDERS_CREATE)]
public virtual async Task<IActionResult> Create(int customerId, string orderProductsJson)
{
if (!await _permissionService.AuthorizeAsync(StandardPermission.Orders.ORDERS_CREATE_EDIT_DELETE))
return AccessDeniedView();
// Validate customer exists
// Validate customer
var customer = await _customerService.GetCustomerByIdAsync(customerId);
if (customer == null)
return RedirectToAction("List");
// Create new empty order
// Parse products
var orderProducts = string.IsNullOrEmpty(orderProductsJson)
? new List<OrderProductItem>()
: JsonConvert.DeserializeObject<List<OrderProductItem>>(orderProductsJson);
// Create order
var order = new Order
{
OrderGuid = Guid.NewGuid(),
CustomOrderNumber = "",
CustomerId = customerId,
CustomerLanguageId = customer.LanguageId ?? 1,
CustomerTaxDisplayType = (TaxDisplayType)customer.TaxDisplayType,
CustomerTaxDisplayType = TaxDisplayType.IncludingTax,
CustomerIp = string.Empty,
OrderStatusId = (int)OrderStatus.Pending,
PaymentStatusId = (int)PaymentStatus.Pending,
@ -169,10 +185,117 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
await _orderService.InsertOrderAsync(order);
// Redirect to edit page
// Add order items
foreach (var item in orderProducts)
{
var product = await _productService.GetProductByIdAsync(item.Id);
if (product != null)
{
var orderItem = new OrderItem
{
OrderId = order.Id,
ProductId = item.Id,
Quantity = item.Quantity,
UnitPriceInclTax = item.Price,
UnitPriceExclTax = item.Price,
PriceInclTax = item.Price * item.Quantity,
PriceExclTax = item.Price * item.Quantity,
OriginalProductCost = product.ProductCost,
AttributeDescription = string.Empty,
AttributesXml = string.Empty,
DiscountAmountInclTax = 0,
DiscountAmountExclTax = 0
};
await _orderService.InsertOrderItemAsync(orderItem);
}
}
return RedirectToAction("Edit", new { id = order.Id });
}
public class OrderProductItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Sku { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
//private static OrderItem CreateOrderItem(ProductToAuctionMapping productToAuction, Order order, decimal orderTotal)
//{
// return new OrderItem
// {
// ProductId = productToAuction.ProductId,
// OrderId = order.Id,
// OrderItemGuid = Guid.NewGuid(),
// PriceExclTax = orderTotal,
// PriceInclTax = orderTotal,
// UnitPriceExclTax = orderTotal,
// UnitPriceInclTax = orderTotal,
// Quantity = productToAuction.ProductAmount,
// };
//}
//private static Order CreateOrder(ProductToAuctionMapping productToAuction, decimal orderTotal, Customer customer, Address billingAddress, int storeId, Dictionary<string, object> customValues)
//{
// return new Order
// {
// BillingAddressId = billingAddress.Id,
// CreatedOnUtc = DateTime.UtcNow,
// CurrencyRate = 1,
// CustomOrderNumber = productToAuction.AuctionId + "/" + productToAuction.SortIndex,
// CustomValuesXml = SerializeCustomValuesToXml(customValues),
// CustomerCurrencyCode = "HUF",
// CustomerId = productToAuction.WinnerCustomerId,
// CustomerLanguageId = 2,
// CustomerTaxDisplayType = TaxDisplayType.IncludingTax,
// OrderGuid = Guid.NewGuid(),
// OrderStatus = OrderStatus.Pending,
// OrderTotal = orderTotal,
// PaymentStatus = PaymentStatus.Pending,
// PaymentMethodSystemName = "Payments.CheckMoneyOrder",
// ShippingStatus = ShippingStatus.ShippingNotRequired,
// StoreId = storeId,
// VatNumber = customer.VatNumber,
// CustomerIp = customer.LastIpAddress,
// OrderSubtotalExclTax = orderTotal,
// OrderSubtotalInclTax = orderTotal
// };
//}
private static OrderNote CreateOrderNote(Order order, string note)
{
return new OrderNote
{
CreatedOnUtc = order.CreatedOnUtc,
DisplayToCustomer = true,
OrderId = order.Id,
Note = note
};
}
private static string SerializeCustomValuesToXml(Dictionary<string, object> sourceDictionary)
{
ArgumentNullException.ThrowIfNull(sourceDictionary);
if (!sourceDictionary.Any())
return null;
var ds = new DictionarySerializer(sourceDictionary);
var xs = new XmlSerializer(typeof(DictionarySerializer));
using var textWriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(textWriter))
{
xs.Serialize(xmlWriter, ds);
}
var result = textWriter.ToString();
return result;
}
[HttpGet] // Change from [HttpPost] to [HttpGet]
[CheckPermission(StandardPermission.Customers.CUSTOMERS_VIEW)]
@ -227,6 +350,176 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
return Json(result);
}
[HttpGet]
[CheckPermission(StandardPermission.Catalog.PRODUCTS_VIEW)]
public virtual async Task<IActionResult> ProductSearchAutoComplete(string term)
{
if (string.IsNullOrWhiteSpace(term) || term.Length < 2)
return Json(new List<object>());
const int maxResults = 15;
// Search products by name or SKU
var products = await _productService.SearchProductsAsync(
keywords: term,
pageIndex: 0,
pageSize: maxResults);
var result = new List<object>();
foreach (var product in products)
{
result.Add(new
{
label = product.Name,
value = product.Id,
sku = product.Sku,
price = product.Price
});
}
return Json(result);
}
//[HttpPost]
//public async Task<IActionResult> CreateInvoice(int orderId)
//{
// try
// {
// var order = await _orderService.GetOrderByIdAsync(orderId);
// if (order == null)
// return Json(new { success = false, message = "Order not found" });
// var billingAddress = await _customerService.GetCustomerBillingAddressAsync(order.Customer);
// if (billingAddress == null)
// return Json(new { success = false, message = "Billing address not found" });
// var country = await _countryService.GetCountryByAddressAsync(billingAddress);
// var countryCode = country?.TwoLetterIsoCode ?? "HU";
// // Create invoice request
// var invoiceRequest = new InvoiceCreateRequest
// {
// VevoNev = $"{billingAddress.FirstName} {billingAddress.LastName}",
// VevoIrsz = billingAddress.ZipPostalCode ?? "",
// VevoTelep = billingAddress.City ?? "",
// VevoOrszag = countryCode,
// VevoUtcaHsz = $"{billingAddress.Address1} {billingAddress.Address2}".Trim(),
// SzamlatombID = 1, // Configure this based on your setup
// SzamlaKelte = DateTime.Now,
// TeljesitesKelte = DateTime.Now,
// Hatarido = DateTime.Now.AddDays(15), // 15 days payment term
// Devizanem = order.CustomerCurrencyCode,
// FizetesiMod = order.PaymentMethodSystemName,
// Felretett = false,
// Proforma = false,
// Email = billingAddress.Email,
// Telefon = billingAddress.PhoneNumber
// };
// // Add order items
// var orderItems = await _orderService.GetOrderItemsAsync(order.Id);
// foreach (var item in orderItems)
// {
// var product = await _productService.GetProductByIdAsync(item.ProductId);
// invoiceRequest.AddItem(new InvoiceItem
// {
// TetelNev = product?.Name ?? "Product",
// AfaSzoveg = "27%", // Configure VAT rate as needed
// Brutto = true,
// EgysegAr = item.UnitPriceInclTax,
// Mennyiseg = item.Quantity,
// MennyisegEgyseg = "db",
// CikkSzam = product?.Sku
// });
// }
// // Create invoice via API
// var response = await _innVoiceApiService.CreateInvoiceAsync(invoiceRequest);
// if (response.IsSuccess)
// {
// // TODO: Save invoice details to your database for future reference
// // You might want to create a custom table to store:
// // - OrderId
// // - InnVoice TableId
// // - Invoice Number
// // - PDF URL
// // - Created Date
// return Json(new
// {
// success = true,
// message = "Invoice created successfully",
// data = new
// {
// tableId = response.TableId,
// invoiceNumber = response.Sorszam,
// sorszam = response.Sorszam,
// printUrl = response.PrintUrl
// }
// });
// }
// else
// {
// return Json(new
// {
// success = false,
// message = $"InnVoice API Error: {response.Message}"
// });
// }
// }
// catch (Exception ex)
// {
// return Json(new
// {
// success = false,
// message = $"Error: {ex.Message}"
// });
// }
//}
//[HttpGet]
//public async Task<IActionResult> GetInvoiceStatus(int orderId)
//{
// try
// {
// // TODO: Retrieve invoice details from your database
// // This is a placeholder - you need to implement actual storage/retrieval
// // Example: var invoiceData = await _yourInvoiceService.GetByOrderIdAsync(orderId);
// // if (invoiceData != null)
// // {
// // return Json(new
// // {
// // success = true,
// // data = new
// // {
// // tableId = invoiceData.TableId,
// // invoiceNumber = invoiceData.InvoiceNumber,
// // sorszam = invoiceData.InvoiceNumber,
// // printUrl = invoiceData.PrintUrl
// // }
// // });
// // }
// return Json(new
// {
// success = false,
// message = "No invoice found for this order"
// });
// }
// catch (Exception ex)
// {
// return Json(new
// {
// success = false,
// message = $"Error: {ex.Message}"
// });
// }
//}
}
}

View File

@ -254,7 +254,7 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
//if (file.Length > 0 && file.ContentType == "application/pdf")
if (file.Length > 0)
{
if (!file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase)){
if (file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase)){
try
{
// Open the PDF from the IFormFile's stream directly in memory
@ -296,7 +296,7 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
return StatusCode(500, $"Error processing PDF file: {ex.Message}");
}
}
else
else //read from image
{
try
{
@ -359,6 +359,8 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
DocumentType = extractedMetaData.DocumentType != null ? (DocumentType)Enum.Parse(typeof(DocumentType), extractedMetaData.DocumentType) : DocumentType.Unknown
};
Console.WriteLine(shippingDocumentToFiles.DocumentType);
await _dbContext.ShippingDocumentToFiles.InsertAsync(shippingDocumentToFiles);
// - IF WE DON'T HAVE PARTNERID ALREADY: read partner information
// (check if all 3 refers to the same partner)
@ -438,7 +440,7 @@ namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
// Analyze PDF with AI to extract structured data
var aiAnalysis = await _aiCalculationService.GetOpenAIPDFAnalysisFromText(
pdfText.ToString(),
"Extract the following information from this shipping document and return as JSON: documentDate, recipientName, senderName, invoiceNumber, totalAmount, itemCount, notes. If a field is not found, return null for that field."
"You work for FruitBank. Extract the following information from this shipping document and return as JSON: documentDate, recipientName, senderName, invoiceNumber, totalAmount, itemCount, notes. If a field is not found, return null for that field."
);
// Parse AI response (assuming it returns JSON)

View File

@ -701,15 +701,16 @@
@*create new order form*@
<div id="create-order-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="create-order-window-title">
<div class="modal-dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="create-order-window-title">@T("Admin.Orders.AddNew")</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<form asp-controller="Order" asp-action="Create" method="post" id="create-order-form">
<form asp-controller="CustomOrder" asp-action="Create" method="post" id="create-order-form">
<div class="form-horizontal">
<div class="modal-body">
<!-- Customer Selection -->
<div class="form-group row">
<div class="col-md-3">
<div class="label-wrapper">
@ -725,6 +726,46 @@
<span class="field-validation-error" id="create-order-customer-error" style="display:none;">Please select a customer</span>
</div>
</div>
<!-- Product Selection -->
<div class="form-group row" id="product-search-section" style="display:none;">
<div class="col-md-3">
<div class="label-wrapper">
<label class="col-form-label">
@T("Admin.Orders.Fields.Product")
</label>
</div>
</div>
<div class="col-md-9">
<input type="text" id="create-order-product-search" autocomplete="off" class="form-control" placeholder="Type product name or SKU..." />
</div>
</div>
<!-- Selected Products List -->
<div id="selected-products-section" style="display:none;">
<div class="form-group row">
<div class="col-md-12">
<label class="col-form-label"><strong>Selected Products:</strong></label>
<div class="table-responsive">
<table class="table table-sm table-bordered" id="selected-products-table">
<thead>
<tr>
<th>Product</th>
<th style="width: 100px;">Quantity</th>
<th style="width: 120px;">Price</th>
<th style="width: 50px;"></th>
</tr>
</thead>
<tbody id="selected-products-body">
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Hidden input for products JSON -->
<input type="hidden" id="order-products-json" name="orderProductsJson" value="" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">
@ -743,24 +784,178 @@
<style>
/* Fix z-index for autocomplete dropdown in modal */
.ui-autocomplete {
z-index: 1060 !important; /* Bootstrap modal z-index is 1050 */
z-index: 1060 !important;
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}
#selected-products-table input[type="number"] {
width: 80px;
}
#selected-products-table input[type="text"] {
width: 100px;
}
</style>
<script>
$(function() {
var selectedProducts = [];
// Customer autocomplete
$('#create-order-customer-search').autocomplete({
delay: 500,
minLength: 2,
source: '@Url.Action("CustomerSearchAutoComplete", "CustomOrder")',
select: function(event, ui) {
$('#create-order-customer-id').val(ui.item.value);
$('#create-order-customer-name').html('<strong>' + ui.item.label + '</strong>');
$('#create-order-customer-search').val('');
$('#create-order-customer-error').hide();
return false;
delay: 500,
minLength: 2,
source: '@Url.Action("CustomerSearchAutoComplete", "CustomOrder")',
select: function(event, ui) {
$('#create-order-customer-id').val(ui.item.value);
$('#create-order-customer-name').html('<strong>' + ui.item.label + '</strong>');
$('#create-order-customer-search').val('');
$('#create-order-customer-error').hide();
// Show product search section after customer is selected
$('#product-search-section').slideDown();
$('#create-order-product-search').focus();
return false;
}
});
// Product autocomplete
$('#create-order-product-search').autocomplete({
delay: 500,
minLength: 2,
source: '@Url.Action("ProductSearchAutoComplete", "CustomOrder")',
select: function(event, ui) {
addProduct(ui.item);
$('#create-order-product-search').val('');
return false;
}
});
// Add product to selected list
function addProduct(product) {
var existingProduct = selectedProducts.find(p => p.id === product.value);
if (existingProduct) {
alert('This product is already added to the order.');
return;
}
var productItem = {
id: product.value,
name: product.label,
sku: product.sku || '',
quantity: 1,
price: product.price || 0
};
selectedProducts.push(productItem);
renderProductsList();
updateProductsJson();
}
// Render products list
function renderProductsList() {
var tbody = $('#selected-products-body');
tbody.empty();
if (selectedProducts.length === 0) {
$('#selected-products-section').hide();
return;
}
$('#selected-products-section').show();
selectedProducts.forEach(function(product, index) {
var row = $('<tr>');
var nameCell = $('<td>').html(
'<strong>' + product.name + '</strong>' +
(product.sku ? '<br><small>SKU: ' + product.sku + '</small>' : '')
);
var quantityCell = $('<td>').html(
'<input type="number" class="form-control form-control-sm" min="1" value="' + product.quantity + '" data-index="' + index + '" />'
);
var priceCell = $('<td>').html(
'<input type="text" class="form-control form-control-sm" value="' + product.price + '" data-index="' + index + '" />'
);
var removeCell = $('<td class="text-center">').html(
'<button type="button" class="btn btn-sm btn-danger" data-index="' + index + '"><i class="fas fa-trash"></i></button>'
);
row.append(nameCell).append(quantityCell).append(priceCell).append(removeCell);
tbody.append(row);
});
}
// Update quantity
$(document).on('change', '#selected-products-body input[type="number"]', function() {
var index = $(this).data('index');
var newQuantity = parseInt($(this).val());
if (newQuantity > 0) {
selectedProducts[index].quantity = newQuantity;
updateProductsJson();
} else {
$(this).val(selectedProducts[index].quantity);
}
});
// Update price
$(document).on('change', '#selected-products-body input[type="text"]', function() {
var index = $(this).data('index');
var newPrice = parseFloat($(this).val());
if (!isNaN(newPrice) && newPrice >= 0) {
selectedProducts[index].price = newPrice;
updateProductsJson();
} else {
$(this).val(selectedProducts[index].price);
}
});
// Remove product
$(document).on('click', '#selected-products-body button[data-index]', function() {
var index = $(this).data('index');
selectedProducts.splice(index, 1);
renderProductsList();
updateProductsJson();
});
// Update hidden JSON field
function updateProductsJson() {
$('#order-products-json').val(JSON.stringify(selectedProducts));
}
// Validate form submission
$('#create-order-form').on('submit', function(e) {
var customerId = $('#create-order-customer-id').val();
if (!customerId || customerId === '0' || customerId === '') {
e.preventDefault();
$('#create-order-customer-error').show();
return false;
}
return true;
});
// Clear error when typing
$('#create-order-customer-search').on('input', function() {
$('#create-order-customer-error').hide();
});
// Reset form when modal is closed
$('#create-order-window').on('hidden.bs.modal', function () {
$('#create-order-customer-search').val('');
$('#create-order-customer-id').val('');
$('#create-order-customer-name').html('');
$('#create-order-customer-error').hide();
$('#create-order-product-search').val('');
$('#product-search-section').hide();
selectedProducts = [];
renderProductsList();
updateProductsJson();
});
});
</script>

View File

@ -1,6 +1,43 @@
@using Nop.Plugin.Misc.FruitBankPlugin.Models.Orders
@model OrderAttributesModel
<!-- InnVoice Invoice Section -->
<div class="card card-default mb-3">
<div class="card-header">
<i class="fas fa-file-invoice"></i>
InnVoice Invoice Management
</div>
<div class="card-body">
<div class="form-group row">
<div class="col-md-12">
<div id="invoiceStatus" class="alert alert-info" style="display: none;">
<i class="fas fa-info-circle"></i> <span id="invoiceStatusMessage"></span>
</div>
<div id="invoiceDetails" style="display: none;">
<p><strong>Invoice Number:</strong> <span id="invoiceNumber"></span></p>
<p><strong>Table ID:</strong> <span id="invoiceTableId"></span></p>
<p>
<a id="invoicePdfLink" href="#" target="_blank" class="btn btn-sm btn-info">
<i class="fas fa-file-pdf"></i> View PDF
</a>
</p>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 text-right">
<button type="button" id="createInvoiceBtn" class="btn btn-success">
<i class="fas fa-file-invoice-dollar"></i> Create & Upload Invoice
</button>
<button type="button" id="checkInvoiceBtn" class="btn btn-secondary" style="display: none;">
<i class="fas fa-sync"></i> Check Invoice Status
</button>
</div>
</div>
</div>
</div>
<!-- Custom Order Attributes Section -->
<div class="card card-default">
<div class="card-header">
<i class="fas fa-tags"></i>
@ -16,7 +53,6 @@
<span asp-validation-for="IsMeasurable"></span>
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<nop-label asp-for="DateOfReceipt" />
@ -26,7 +62,6 @@
<span asp-validation-for="DateOfReceipt"></span>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 text-right">
<button type="button" id="saveAttributesBtn" class="btn btn-primary">
@ -39,6 +74,7 @@
<script>
$(document).ready(function () {
// Save Order Attributes
$("#saveAttributesBtn").click(function () {
$.ajax({
type: "POST",
@ -57,6 +93,106 @@
}
});
});
});
</script>
// Create Invoice
$("#createInvoiceBtn").click(function () {
var btn = $(this);
btn.prop("disabled", true).html('<i class="fas fa-spinner fa-spin"></i> Creating Invoice...');
showInvoiceStatus("Creating invoice, please wait...", "info");
$.ajax({
type: "POST",
url: "@Url.Action("CreateInvoice", "InnVoice")",
data: {
orderId: "@Model.OrderId",
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
},
success: function (response) {
btn.prop("disabled", false).html('<i class="fas fa-file-invoice-dollar"></i> Create & Upload Invoice');
if (response.success) {
showInvoiceStatus("Invoice created successfully!", "success");
displayInvoiceDetails(response.data);
$("#checkInvoiceBtn").show();
} else {
showInvoiceStatus("Error: " + response.message, "danger");
}
},
error: function (xhr) {
btn.prop("disabled", false).html('<i class="fas fa-file-invoice-dollar"></i> Create & Upload Invoice');
var errorMessage = "Error creating invoice";
if (xhr.responseJSON && xhr.responseJSON.message) {
errorMessage = xhr.responseJSON.message;
}
showInvoiceStatus(errorMessage, "danger");
}
});
});
// Check Invoice Status
$("#checkInvoiceBtn").click(function () {
var btn = $(this);
btn.prop("disabled", true).html('<i class="fas fa-spinner fa-spin"></i> Checking...');
$.ajax({
type: "GET",
url: "@Url.Action("GetInvoiceStatus", "InnVoice")",
data: {
orderId: "@Model.OrderId"
},
success: function (response) {
btn.prop("disabled", false).html('<i class="fas fa-sync"></i> Check Invoice Status');
if (response.success && response.data) {
displayInvoiceDetails(response.data);
showInvoiceStatus("Invoice details loaded", "success");
} else {
showInvoiceStatus("No invoice found for this order", "warning");
}
},
error: function () {
btn.prop("disabled", false).html('<i class="fas fa-sync"></i> Check Invoice Status');
showInvoiceStatus("Error checking invoice status", "danger");
}
});
});
function showInvoiceStatus(message, type) {
var statusDiv = $("#invoiceStatus");
statusDiv.removeClass("alert-info alert-success alert-warning alert-danger")
.addClass("alert-" + type);
$("#invoiceStatusMessage").text(message);
statusDiv.show();
}
function displayInvoiceDetails(data) {
$("#invoiceNumber").text(data.invoiceNumber || data.sorszam || "N/A");
$("#invoiceTableId").text(data.tableId || "N/A");
if (data.printUrl) {
$("#invoicePdfLink").attr("href", data.printUrl).show();
} else {
$("#invoicePdfLink").hide();
}
$("#invoiceDetails").show();
}
// Check if invoice exists on page load
$.ajax({
type: "GET",
url: "@Url.Action("GetInvoiceStatus", "InnVoice")",
data: {
orderId: "@Model.OrderId"
},
success: function (response) {
if (response.success && response.data) {
displayInvoiceDetails(response.data);
$("#checkInvoiceBtn").show();
}
}
});
});
</script>