Mango.Nop.Plugins/Nop.Plugin.Misc.AIPlugin/Areas/Admin/Controllers/InnVoiceOrderController.cs

411 lines
17 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Nop.Core;
using Nop.Core.Domain.Orders;
using Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;
using Nop.Plugin.Misc.FruitBankPlugin.Services;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Orders;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers
{
[Area(AreaNames.ADMIN)]
[AuthorizeAdmin]
public class InnVoiceOrderController : BasePluginController
{
private readonly IOrderService _orderService;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly ICustomerService _customerService;
private readonly ICountryService _countryService;
private readonly IProductService _productService;
private readonly InnVoiceOrderService _innVoiceOrderService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly FruitBankDbContext _dbContext;
public InnVoiceOrderController(
IOrderService orderService,
IWorkContext workContext,
IStoreContext storeContext,
ICustomerService customerService,
ICountryService countryService,
IProductService productService,
InnVoiceOrderService innVoiceOrderService,
IGenericAttributeService genericAttributeService,
FruitBankDbContext dbContext)
{
_orderService = orderService;
_workContext = workContext;
_storeContext = storeContext;
_customerService = customerService;
_countryService = countryService;
_productService = productService;
_innVoiceOrderService = innVoiceOrderService;
_genericAttributeService = genericAttributeService;
_dbContext = dbContext;
}
/// <summary>
/// Create an order in InnVoice from a NopCommerce order
/// </summary>
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> CreateOrder(int orderId)
{
try
{
var order = await _orderService.GetOrderByIdAsync(orderId);
if (order == null)
return Json(new { success = false, message = "Order not found" });
var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);
// Get billing address
var billingAddress = await _customerService.GetCustomerBillingAddressAsync(customer);
if (billingAddress == null)
return Json(new { success = false, message = "Billing address not found" });
var billingCountry = await _countryService.GetCountryByAddressAsync(billingAddress);
var billingCountryCode = billingCountry?.TwoLetterIsoCode ?? "HU";
// Get shipping address
var shippingAddress = await _customerService.GetCustomerShippingAddressAsync(customer);
if (shippingAddress == null)
{
shippingAddress = billingAddress;
}
var shippingCountry = shippingAddress != null
? await _countryService.GetCountryByAddressAsync(shippingAddress)
: null;
var shippingCountryCode = shippingCountry?.TwoLetterIsoCode ?? billingCountryCode;
// Create order request
var orderRequest = new OrderCreateRequest
{
VevoNev = $"{billingAddress.FirstName} {billingAddress.LastName}",
VevoIrsz = billingAddress.ZipPostalCode ?? "",
VevoTelep = billingAddress.City ?? "",
VevoUtcaHsz = $"{billingAddress.Address1} {billingAddress.Address2}".Trim(),
VevoOrszag = billingCountryCode,
VevoAdoszam = billingAddress.Company, // Or a custom field for tax number
MegrendelestombID = 1, // Configure this based on your setup
MegrendelesKelte = order.CreatedOnUtc.ToLocalTime(),
Hatarido = DateTime.Now.AddDays(7), // 7 days delivery time
Devizanem = "HUF", //TODO get real deault - A.
FizetesiMod = order.PaymentMethodSystemName ?? "átutalás",
Email = billingAddress.Email,
Telefon = billingAddress.PhoneNumber,
MegrendelesSzamStr = order.Id.ToString()
};
// Add shipping address if different
if (shippingAddress != null)
{
orderRequest.SzallNev = $"{shippingAddress.FirstName} {shippingAddress.LastName}";
orderRequest.SzallIrsz = shippingAddress.ZipPostalCode ?? "";
orderRequest.SzallTelep = shippingAddress.City ?? "";
orderRequest.SzallUtcaHsz = $"{shippingAddress.Address1} {shippingAddress.Address2}".Trim();
orderRequest.SzallOrszag = shippingCountryCode;
}
// Add order items
var orderItems = await _orderService.GetOrderItemsAsync(order.Id);
foreach (var item in orderItems)
{
//var productDTO = await _productService.GetProductByIdAsync(item.ProductId);
var product = _dbContext.ProductDtos.GetById(item.ProductId);
//string unit = product != null && product.IsMeasurable ? "kg" : "kt";
orderRequest.AddItem(new InnVoiceOrderItem
{
TetelNev = product?.Name ?? "Product",
AfaSzoveg = "27%", // Configure VAT rate as needed
Brutto = true,
EgysegAr = item.UnitPriceInclTax,
Mennyiseg = item.Quantity,
MennyisegEgyseg = "kt",
CikkSzam = ""
});
}
// Create order via API
var response = await _innVoiceOrderService.CreateOrderAsync(orderRequest);
if (response.IsSuccess)
{
// Save the TechId, TableId, and PrintUrl to the order for future reference
await _genericAttributeService.SaveAttributeAsync(
order,
"InnVoiceOrderTechId",
response.TechId,
(await _storeContext.GetCurrentStoreAsync()).Id
);
await _genericAttributeService.SaveAttributeAsync(
order,
"InnVoiceOrderTableId",
response.TableId?.ToString(),
(await _storeContext.GetCurrentStoreAsync()).Id
);
await _genericAttributeService.SaveAttributeAsync(
order,
"InnVoiceOrderPrintLink",
response.PrintUrl?.ToString(),
(await _storeContext.GetCurrentStoreAsync()).Id
);
return Json(new
{
success = true,
message = "Order created successfully in InnVoice",
data = new
{
tableId = response.TableId,
techId = response.TechId,
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}"
});
}
}
/// <summary>
/// Get InnVoice order status for a NopCommerce order
/// </summary>
/// <summary>
/// Get InnVoice order status for a NopCommerce order
/// </summary>
[HttpGet]
public async Task<IActionResult> GetOrderStatus(int orderId)
{
try
{
var order = await _orderService.GetOrderByIdAsync(orderId);
if (order == null)
return Json(new { success = false, message = "Order not found" });
var storeId = (await _storeContext.GetCurrentStoreAsync()).Id;
// Get saved InnVoice order TechId
var techId = await _genericAttributeService.GetAttributeAsync<string>(
order,
"InnVoiceOrderTechId",
storeId
);
var printLink = await _genericAttributeService.GetAttributeAsync<string>(
order,
"InnVoiceOrderPrintLink",
storeId
);
if (string.IsNullOrEmpty(techId))
{
return Json(new
{
success = false,
message = "No InnVoice order found for this order"
});
}
// Fetch the order details from InnVoice API using TechId
var innVoiceOrders = await _innVoiceOrderService.GetOrderByTechIdAsync(techId);
if (innVoiceOrders == null || innVoiceOrders.Count == 0)
{
return Json(new
{
success = false,
message = "Order not found in InnVoice"
});
}
var innVoiceOrder = innVoiceOrders.FirstOrDefault();
return Json(new
{
success = true,
data = new
{
tableId = innVoiceOrder.TableId,
techId = innVoiceOrder.TechId,
printUrl = printLink,
customerName = innVoiceOrder.CustomerName,
totalGross = innVoiceOrder.TotalGross,
currency = innVoiceOrder.Currency,
orderDate = innVoiceOrder.OrderDate
}
});
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = $"Error: {ex.Message}"
});
}
}
/// <summary>
/// Create multiple orders in InnVoice from multiple NopCommerce orders
/// </summary>
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> CreateMultipleOrders([FromBody] int[] orderIds)
{
try
{
if (orderIds == null || orderIds.Length == 0)
return Json(new { success = false, message = "No order IDs provided" });
var orderRequests = new List<OrderCreateRequest>();
foreach (var orderId in orderIds)
{
var order = await _orderService.GetOrderByIdAsync(orderId);
if (order == null)
continue;
var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);
var billingAddress = await _customerService.GetCustomerBillingAddressAsync(customer);
if (billingAddress == null)
continue;
var billingCountry = await _countryService.GetCountryByAddressAsync(billingAddress);
var billingCountryCode = billingCountry?.TwoLetterIsoCode ?? "HU";
var orderRequest = new OrderCreateRequest
{
VevoNev = $"{billingAddress.FirstName} {billingAddress.LastName}",
VevoIrsz = billingAddress.ZipPostalCode ?? "",
VevoTelep = billingAddress.City ?? "",
VevoUtcaHsz = $"{billingAddress.Address1} {billingAddress.Address2}".Trim(),
VevoOrszag = billingCountryCode,
MegrendelestombID = 1,
MegrendelesKelte = order.CreatedOnUtc.ToLocalTime(),
Hatarido = DateTime.Now.AddDays(7),
Devizanem = order.CustomerCurrencyCode,
FizetesiMod = order.PaymentMethodSystemName,
Email = billingAddress.Email,
Telefon = billingAddress.PhoneNumber,
MegrendelesSzamStr = order.Id.ToString()
};
// Add order items
var orderItems = await _orderService.GetOrderItemsAsync(order.Id);
foreach (var item in orderItems)
{
var product = await _productService.GetProductByIdAsync(item.ProductId);
orderRequest.AddItem(new InnVoiceOrderItem
{
TetelNev = product?.Name ?? "Product",
AfaSzoveg = "27%",
Brutto = true,
EgysegAr = item.UnitPriceInclTax,
Mennyiseg = item.Quantity,
MennyisegEgyseg = "db",
CikkSzam = product?.Sku
});
}
orderRequests.Add(orderRequest);
}
if (orderRequests.Count == 0)
return Json(new { success = false, message = "No valid orders to create" });
// Create orders via API
var responses = await _innVoiceOrderService.CreateOrdersAsync(orderRequests);
var successCount = responses.Count(r => r.IsSuccess);
var failureCount = responses.Count - successCount;
// Save TechIds for successful orders
var storeId = (await _storeContext.GetCurrentStoreAsync()).Id;
for (int i = 0; i < responses.Count && i < orderIds.Length; i++)
{
if (responses[i].IsSuccess)
{
var order = await _orderService.GetOrderByIdAsync(orderIds[i]);
if (order != null)
{
await _genericAttributeService.SaveAttributeAsync(
order,
"InnVoiceOrderTechId",
responses[i].TechId,
storeId
);
await _genericAttributeService.SaveAttributeAsync(
order,
"InnVoiceOrderTableId",
responses[i].TableId?.ToString(),
storeId
);
}
}
}
return Json(new
{
success = successCount > 0,
message = $"Created {successCount} orders successfully. {failureCount} failed.",
data = new
{
successCount,
failureCount,
responses = responses.Select(r => new
{
success = r.IsSuccess,
tableId = r.TableId,
techId = r.TechId,
message = r.Message,
printUrl = r.PrintUrl
})
}
});
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = $"Error: {ex.Message}"
});
}
}
}
}