Skip to content

Commit

Permalink
Merge pull request #79 from medhatelmasry/51-fix-allocations
Browse files Browse the repository at this point in the history
51 fix allocations
  • Loading branch information
medhatelmasry authored Dec 9, 2024
2 parents f381945 + 04ef7ad commit 9b72ab3
Show file tree
Hide file tree
Showing 4 changed files with 297 additions and 104 deletions.
183 changes: 125 additions & 58 deletions src/AccountGoWeb/Controllers/SalesController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using AccountGoWeb.Models;
using Dto.Sales;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace AccountGoWeb.Controllers
{
Expand Down Expand Up @@ -248,11 +249,14 @@ public async System.Threading.Tasks.Task<IActionResult> AddSalesInvoice(SalesInv
}
else if (ModelState.IsValid)
{
_logger.LogInformation("Posted value received: {Posted}", Dto.Posted);
var serialize = Newtonsoft.Json.JsonConvert.SerializeObject(Dto);
var content = new StringContent(serialize);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

_logger.LogInformation("AddSalesInvoice: " + await content.ReadAsStringAsync());
var response = Post("Sales/CreateSalesInvoice", content);

_logger.LogInformation("AddSalesInvoice response: " + response.ToString());
if (response.IsSuccessStatusCode)
return RedirectToAction("salesinvoices");
Expand All @@ -269,71 +273,102 @@ public async System.Threading.Tasks.Task<IActionResult> AddSalesInvoice(SalesInv
public async System.Threading.Tasks.Task<IActionResult> SalesReceipts()
{
ViewBag.PageContentHeader = "Sales Receipts";
using (var client = new HttpClient())
try
{
var baseUri = _configuration!["ApiUrl"];
client.BaseAddress = new System.Uri(baseUri!);
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.GetAsync(baseUri + "sales/salesreceipts");
if (response.IsSuccessStatusCode)
using (var client = new HttpClient())
{
var responseJson = await response.Content.ReadAsStringAsync();
return View(model: responseJson);
var baseUri = _configuration!["ApiUrl"];
client.BaseAddress = new Uri(baseUri!);
client.DefaultRequestHeaders.Accept.Clear();

var response = await client.GetAsync("sales/salesreceipts");
if (response.IsSuccessStatusCode)
{
var responseJson = await response.Content.ReadAsStringAsync();
return View(model: responseJson);
}
else
{
_logger.LogError("Failed to fetch sales receipts. API returned status code: {StatusCode}", response.StatusCode);
ViewBag.ErrorMessage = "Failed to load sales receipts. Please try again later.";
}
}
}
return View();
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while fetching sales receipts.");
ViewBag.ErrorMessage = "An unexpected error occurred while loading sales receipts.";
}

// Return the view with an error message if the API call fails
return View(model: "[]");
}

[HttpGet]
public IActionResult AddReceipt()
{

var model = new Models.Sales.AddReceipt();

if (ModelState.IsValid)
try
{
var serialize = Newtonsoft.Json.JsonConvert.SerializeObject(model);
var content = new StringContent(serialize);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = Post("Sales/SaveReceipt", content);
if (response.IsSuccessStatusCode)
return RedirectToAction("salesreceipts");
ViewBag.PageContentHeader = "New Receipt";
ViewBag.Customers = Models.SelectListItemHelper.Customers();
ViewBag.DebitAccounts = Models.SelectListItemHelper.CashBanks();
ViewBag.CreditAccounts = Models.SelectListItemHelper.Accounts();
ViewBag.CustomersDetail = Newtonsoft.Json.JsonConvert.SerializeObject(
GetAsync<IEnumerable<Customer>>("sales/customers").Result
);

var model = new Models.Sales.AddReceipt();
return View(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while preparing the Add Receipt page.");
ViewBag.ErrorMessage = "Failed to load the page for adding a receipt. Please try again later.";
return View(new Models.Sales.AddReceipt());
}

ViewBag.PageContentHeader = "New Receipt";

ViewBag.Customers = Models.SelectListItemHelper.Customers();
ViewBag.DebitAccounts = Models.SelectListItemHelper.CashBanks();
ViewBag.CreditAccounts = Models.SelectListItemHelper.Accounts();
ViewBag.CustomersDetail = Newtonsoft.Json.JsonConvert.SerializeObject(GetAsync<IEnumerable<Customer>>("sales/customers").Result);

return View(model);
}

[HttpPost]
public IActionResult AddReceipt(Models.Sales.AddReceipt model)
{
if (ModelState.IsValid)
{
var serialize = Newtonsoft.Json.JsonConvert.SerializeObject(model);
var content = new StringContent(serialize);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = Post("sales/savereceipt", content);
if (response.IsSuccessStatusCode)
return RedirectToAction("salesreceipts");
try
{
var serialize = Newtonsoft.Json.JsonConvert.SerializeObject(model);
var content = new StringContent(serialize);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

var response = Post("sales/savereceipt", content);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("SalesReceipts");
}
else
{
_logger.LogError("Failed to save receipt. API returned status code: {StatusCode}", response.StatusCode);
ViewBag.ErrorMessage = "Failed to save the receipt. Please try again.";
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while saving the receipt.");
ViewBag.ErrorMessage = "An unexpected error occurred. Please try again.";
}
}

// Reload dropdowns and return the view if validation or API call fails
ViewBag.PageContentHeader = "New Receipt";

ViewBag.Customers = Models.SelectListItemHelper.Customers();
ViewBag.DebitAccounts = Models.SelectListItemHelper.CashBanks();
ViewBag.CreditAccounts = Models.SelectListItemHelper.Accounts();
ViewBag.CustomersDetail = Newtonsoft.Json.JsonConvert.SerializeObject(GetAsync<IEnumerable<Customer>>("sales/customers").Result);
ViewBag.CustomersDetail = Newtonsoft.Json.JsonConvert.SerializeObject(
GetAsync<IEnumerable<Customer>>("sales/customers").Result
);

return View(model);
}


public async System.Threading.Tasks.Task<IActionResult> Customers()
{
ViewBag.PageContentHeader = "Customers";
Expand Down Expand Up @@ -433,39 +468,71 @@ public IActionResult CustomerAllocations(int id)
return View();
}

// [HttpGet]
public IActionResult Allocate(int id)
{
ViewBag.PageContentHeader = "Receipt Allocation";
Console.WriteLine($"Allocate called with ID: {id}");

var model = new Models.Sales.Allocate();
try
{
ViewBag.PageContentHeader = "Receipt Allocation";

var receipt = GetAsync<Dto.Sales.SalesReceipt>("sales/salesreceipt?id=" + id).Result;
var model = new Models.Sales.Allocate();

ViewBag.CustomerName = receipt.CustomerName;
ViewBag.ReceiptNo = receipt.ReceiptNo;
// Fetch receipt details
var receipt = GetAsync<Dto.Sales.SalesReceipt>("sales/salesreceipt?id=" + id).Result;
if (receipt == null)
{
Console.WriteLine($"Receipt not found for ID: {id}");
_logger.LogError("Failed to fetch receipt with id: {id}", id);
return NotFound($"Receipt with id {id} not found.");
}

model.CustomerId = receipt.CustomerId;
model.ReceiptId = receipt.Id;
model.Date = receipt.ReceiptDate;
model.Amount = receipt.Amount;
model.RemainingAmountToAllocate = receipt.RemainingAmountToAllocate;
ViewBag.CustomerName = receipt.CustomerName;
ViewBag.ReceiptNo = receipt.ReceiptNo;

var invoices = GetAsync<IEnumerable<Dto.Sales.SalesInvoice>>("sales/customerinvoices?id=" + receipt.CustomerId).Result;
model.CustomerId = receipt.CustomerId;
model.ReceiptId = receipt.Id;
model.Date = receipt.ReceiptDate;
model.Amount = receipt.Amount;
model.RemainingAmountToAllocate = receipt.RemainingAmountToAllocate;

foreach (var invoice in invoices)
{
if (invoice.Posted && invoice.TotalAllocatedAmount < invoice.Amount)
// Fetch customer invoices
_logger.LogInformation("Calling API: sales/customerinvoices?id={id}", receipt.CustomerId);

var invoices = GetAsync<IEnumerable<Dto.Sales.SalesInvoice>>("sales/customerinvoices?id=" + receipt.CustomerId).Result;
if (invoices == null)
{
_logger.LogError("Failed to fetch invoices for customer with id: {CustomerId}", receipt.CustomerId);
return NotFound($"Invoices for customer with id {receipt.CustomerId} not found.");
}

foreach (var invoice in invoices)
{
model.AllocationLines.Add(new Models.Sales.AllocationLine()
_logger.LogInformation("Invoice: {Invoice}", JsonConvert.SerializeObject(invoice));
if (invoice.Posted && invoice.TotalAllocatedAmount < invoice.Amount)
{
InvoiceId = invoice.Id,
Amount = invoice.Amount,
AllocatedAmount = invoice.TotalAllocatedAmount
});
model.AllocationLines.Add(new Models.Sales.AllocationLine()
{
InvoiceId = invoice.Id,
Amount = invoice.Amount,
AllocatedAmount = invoice.TotalAllocatedAmount
});
}
else
{
_logger.LogInformation("Invoice excluded: Posted={Posted}, TotalAllocatedAmount={TotalAllocatedAmount}, Amount={Amount}",
invoice.Posted, invoice.TotalAllocatedAmount, invoice.Amount);
}
}
}

return View(model);
return View(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while processing the Allocate action for id: {id}", id);
return StatusCode(500, "An error occurred while processing your request.");
}
}

[HttpPost]
Expand Down
Loading

0 comments on commit 9b72ab3

Please sign in to comment.