using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using rgbc_sds.dal.DB; using rgbc_sds.services.Models; using rgbc_sds.services.Services; using rgbc_sds.website.Controllers.SharePoint; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using static Microsoft.Graph.Constants; using OfficeOpenXml; namespace rgbc_sds.website.Controllers.Shipment { public class ShipmentController : Controller { static ShipmentController() { // Set EPPlus license context for non-commercial use ExcelPackage.LicenseContext = LicenseContext.NonCommercial; } #region [ Variables ] private readonly ShipmentService _shipmentService; private readonly SupplierService _supplierService; private readonly FileUploadService _fileUploadService = new FileUploadService(); private readonly SharePointService _sharepointService; private readonly IConfiguration _configuration; private readonly ILogger _logger; private List files = new List(); #endregion [ Variables ] #region [ Constructor ] public ShipmentController(IConfiguration configuration, SharePointService sharepointService, ILogger logger, ShipmentService shipmentService, SupplierService supplierService) { _configuration = configuration; _sharepointService = sharepointService ?? throw new ArgumentNullException(nameof(sharepointService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger.LogInformation("SharepointService injected successfully."); _shipmentService = shipmentService; _supplierService = supplierService; } #endregion [ Construtor ] #region [ Get ] [HttpGet] [Route("shipment/shipmentlist")] public ActionResult ShipmentList() { var model = _shipmentService.GetShipmentList(); model.LoggedInUserName = HttpContext.Session.GetString("LoggedInUsername"); // populate shipment statuses model = PopulateShipmentStatus(model); return View(model); } #region Import Actions /// /// GET: /shipment/import /// Redirect to import functionality /// [HttpGet] [Route("shipment/import")] public ActionResult Import() { return RedirectToAction("Upload", "Import", new { area = "" }); } /// /// GET: /shipment/importshipments /// Redirect to import functionality (legacy route) /// [HttpGet] [Route("shipment/importshipments")] public ActionResult ImportShipments() { return RedirectToAction("Upload", "Import", new { area = "" }); } #endregion [HttpGet] [Route("shipment/exportshipments")] public ActionResult ExportShipments() { try { var model = _shipmentService.GetShipmentList(); // Create Excel file using EPPlus using (var package = new OfficeOpenXml.ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Shipments"); // Add headers for the fields shown in the form worksheet.Cells[1, 1].Value = "#"; worksheet.Cells[1, 2].Value = "Supplier"; worksheet.Cells[1, 3].Value = "Indent Number"; worksheet.Cells[1, 4].Value = "Shipshape Number"; worksheet.Cells[1, 5].Value = "Mother Vessel"; worksheet.Cells[1, 6].Value = "E.T.A"; worksheet.Cells[1, 7].Value = "Bill of Entry Number"; worksheet.Cells[1, 8].Value = "Container Number"; worksheet.Cells[1, 9].Value = "Offloading Port"; worksheet.Cells[1, 10].Value = "Container Received"; worksheet.Cells[1, 11].Value = "No of Flatcases"; worksheet.Cells[1, 12].Value = "Voyage"; worksheet.Cells[1, 13].Value = "M/BL Number"; worksheet.Cells[1, 14].Value = "Redirect to SACD"; // Style the header row using (var range = worksheet.Cells[1, 1, 1, 14]) { range.Style.Font.Bold = true; range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Maroon); range.Style.Font.Color.SetColor(System.Drawing.Color.White); range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; } // Add data rows int rowCount = 2; foreach (var shipment in model.ShipmentListModel) { worksheet.Cells[rowCount, 1].Value = rowCount - 1; worksheet.Cells[rowCount, 2].Value = shipment.SupplierName; worksheet.Cells[rowCount, 3].Value = shipment.IndentNumber; worksheet.Cells[rowCount, 4].Value = shipment.ShipshapeNumber; worksheet.Cells[rowCount, 5].Value = shipment.MotherVessel; worksheet.Cells[rowCount, 6].Value = shipment.ETA; worksheet.Cells[rowCount, 7].Value = shipment.BillOfEntryNumber; worksheet.Cells[rowCount, 8].Value = shipment.ContainerNumber; worksheet.Cells[rowCount, 9].Value = GetPortName(shipment.PortId); worksheet.Cells[rowCount, 10].Value = shipment.ContainerReceived; worksheet.Cells[rowCount, 11].Value = shipment.NoOfFlatcases; worksheet.Cells[rowCount, 12].Value = shipment.Voyage; worksheet.Cells[rowCount, 13].Value = shipment.MBLNumber; worksheet.Cells[rowCount, 14].Value = shipment.RedirectToSACD; rowCount++; } // Auto-fit columns worksheet.Cells.AutoFitColumns(); // Add borders to all cells using (var range = worksheet.Cells[1, 1, rowCount - 1, 14]) { range.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; range.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; range.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; range.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; } // Return Excel file var fileName = $"Shipments_Export_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx"; var bytes = package.GetAsByteArray(); return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); } } catch (Exception ex) { _logger.LogError(ex, "Error exporting shipments"); return RedirectToAction("ShipmentList"); } } [HttpGet] [Route("shipment/shipmentdetails/{id}")] public async Task ShipmentDetail(int id) { var model = new ShipmentViewModel(); var existingShipment = _shipmentService.GetShipment(id); if (existingShipment != null) { // populate supplier list var suppliersList = _supplierService.GetSupplierList(); if (suppliersList != null) { model.Suppliers = suppliersList.SupplierListModel; } // populate ports list // create list of ports to be selected model = PopulatePortsDropdown(model); model.Id = existingShipment.id; model.SupplierId = existingShipment.supplier_id; model.IndentNumber = existingShipment.indent_number; model.ShipshapeNumber = existingShipment.shipshape_number; model.MotherVessel = existingShipment.mother_vessel; model.ETA = Convert.ToDateTime(existingShipment.eta); model.BillOfEntryNumber = existingShipment.bill_of_entry_number; model.ContainerNumber = existingShipment.container_number; model.PortId = Convert.ToInt32(existingShipment.port_id); model.ContainerReceived = Convert.ToDateTime(existingShipment.container_received); model.NoOfFlatcases = existingShipment.no_of_flatcases; model.Voyage = existingShipment.voyage; model.MBLNumber = existingShipment.mbl_number; model.RedirectToSACD = Convert.ToDateTime(existingShipment.redirect_to_SACD); // files model.ClampingRequestFileName = existingShipment.clamping_request_file; model.ClampingRequestPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.clamping_request_file}"); //model.ClampingRequestPreviewURL = model.ClampingRequestPreviewURL == "File not Found" ? string.Empty : WebUtility.UrlEncode(model.ClampingRequestPreviewURL); model.SupplierInvoiceFileName = existingShipment.supplier_invoice_file; model.SupplierInvoicePreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.supplier_invoice_file}"); //model.SupplierInvoicePreviewURL = model.SupplierInvoicePreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.SupplierInvoicePreviewURL); model.BillOfLadingFileName = existingShipment.bill_of_lading_file; model.BillOfLadingPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.bill_of_lading_file}"); //model.BillOfLadingPreviewURL = model.BillOfLadingPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.BillOfLadingPreviewURL); model.ArrivalInvoiceFileName = existingShipment.arrival_invoice_file; model.ArrivalInvoicePreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.arrival_invoice_file}"); //model.ArrivalInvoicePreviewURL = model.ArrivalInvoicePreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.ArrivalInvoicePreviewURL); model.ArrivalInvoiceFile2Name = existingShipment.arrival_invoice_file2; model.ArrivalInvoice2PreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.arrival_invoice_file2}"); //model.ArrivalInvoice2PreviewURL = model.ArrivalInvoice2PreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.ArrivalInvoicePreviewURL); model.CertificateOfOriginFileName = existingShipment.certificate_of_origin_file; model.CertificateOfOriginPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.certificate_of_origin_file}"); //model.CertificateOfOriginPreviewURL = model.CertificateOfOriginPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.CertificateOfOriginPreviewURL); model.PackingListFileName = existingShipment.packing_list_file; model.PackingListPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.packing_list_file}"); //model.PackingListPreviewURL = model.PackingListPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.PackingListPreviewURL); model.DROToTransportFileName = existingShipment.dro_to_transport_file; model.DROToTransportPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.dro_to_transport_file}"); //model.DROToTransportPreviewURL = model.DROToTransportPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.DROToTransportPreviewURL); model.CertificateOfRemovalFileName = existingShipment.certificate_of_removal_file; model.CertificateOfRemovalPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.certificate_of_removal_file}"); //model.CertificateOfRemovalPreviewURL = model.CertificateOfRemovalPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.CertificateOfRemovalPreviewURL); model.ExtendedDetentionFileName = existingShipment.extended_detention_file; model.ExtendedDetentionPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.extended_detention_file}"); //model.ExtendedDetentionPreviewURL = model.ExtendedDetentionPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.ExtendedDetentionPreviewURL); model.VOCFileName = existingShipment.voc_file; model.VOCPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.voc_file}"); //model.VOCPreviewURL = model.VOCPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.VOCPreviewURL); model.DeptOfHealthFileName = existingShipment.dept_of_health_inspection_file; model.DeptOfHealthPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.dept_of_health_inspection_file}"); //model.DeptOfHealthPreviewURL = model.DeptOfHealthPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.DeptOfHealthPreviewURL); model.SARSDocumentsFileName = existingShipment.sars_documents_file; model.SARSDocumentsPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.sars_documents_file}"); //model.SARSDocumentsPreviewURL = model.SARSDocumentsPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.SARSDocumentsPreviewURL); model.GRVCompleteRGBCFileName = existingShipment.grv_complete_RGBC_file; model.GRVCompleteRGBCPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.grv_complete_RGBC_file}"); //model.GRVCompleteRGBCPreviewURL = model.GRVCompleteRGBCPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.GRVCompleteRGBCPreviewURL); model.GRVEdwardSnellFileName = existingShipment.grv_edward_snell_file; model.GRVEdwardSnellPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.grv_edward_snell_file}"); //model.GRVEdwardSnellPreviewURL = model.GRVEdwardSnellPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.GRVEdwardSnellPreviewURL); model.ACCPACReceiptsFileName = existingShipment.accpac_receipts_file; model.ACCPACReceiptsPreviewURL = await _sharepointService.GetSharepointPreviewURL($"/Shipment Checklist/{existingShipment.indent_number}", $"{existingShipment.indent_number}_{existingShipment.accpac_receipts_file}"); //model.ACCPACReceiptsPreviewURL = model.ACCPACReceiptsPreviewURL == "File not Found" ? string.Empty : ObfuscateUrl(model.ACCPACReceiptsPreviewURL); model.Process = "UPDATE"; model.LoggedInUserRole = HttpContext.Session.GetString("LoggedInUserRole"); model.LoggedInUserName = HttpContext.Session.GetString("LoggedInUsername"); model.CancelReason = existingShipment.cancel_reason; model.ShipmentStatus = existingShipment.shipment_status; model.CanSubmit = _shipmentService.CheckShipmentSubmitStatus(existingShipment); var editedBy = !existingShipment.updated_by.IsNullOrEmpty() ? existingShipment.updated_by : ""; var editByDate = existingShipment.updated_at != null ? existingShipment.updated_at.Value.ToString("yyyy-MM-dd") : ""; var lastEdit = existingShipment.updated_at != null ? existingShipment.updated_at.Value.ToString("dd MMMM yyyy HH:mm") : ""; model.EditedBy = editedBy + " - " + editByDate; model.LastEdit = lastEdit; ViewBag.SupplierList = model.Suppliers; ViewBag.PortList = model.Ports; } return View("~/Views/Shipment/UpdateShipment.cshtml", model); } [HttpPost] [Route("shipment/addnewshipment/")] public ActionResult AddNewShipment() { var model = new ShipmentViewModel(); var suppliersList = _supplierService.GetSupplierList(); if (suppliersList != null) { model.Suppliers = suppliersList.SupplierListModel.Where(x => x.IsActive == true).ToList(); } // create list of ports to be selected model = PopulatePortsDropdown(model); ViewBag.SupplierList = model.Suppliers; ViewBag.PortList = model.Ports; model.LoggedInUserName = HttpContext.Session.GetString("LoggedInUsername"); model.LoggedInUserRole = HttpContext.Session.GetString("LoggedInUserRole"); model.Process = "ADD"; model.ETA = DateTime.Now; model.ContainerReceived = DateTime.Now; model.RedirectToSACD = DateTime.Now; return View("~/Views/Shipment/AddShipment.cshtml", model); } [HttpGet] [Route("shipment/filtershipmentlist")] public ActionResult FilterShipmentList(ShipmentModel model) { var returnModel = _shipmentService.FilterShipmentList(model.SearchString, model.ShipmentStatus); // populate shipment statuses returnModel = PopulateShipmentStatus(returnModel); return View("~/Views/Shipment/ShipmentList.cshtml", returnModel); } #endregion [ Get ] #region [ Post ] [HttpPost] [Route("shipment/saveshipment")] public async Task SaveShipment(ShipmentViewModel model, List files) { // determine if you have to save or update if (model.Id == 0) { // save return await AddShipment(model, files); } else { // update model.Process = "UPDATE"; return await UpdateShipment(model); } } [HttpPost] [Route("shipment/addshipment")] public async Task AddShipment(ShipmentViewModel model, List files) { model.Process = "SAVE"; if (!ValidateScreen(model)) { var suppliersList = _supplierService.GetSupplierList(); if (suppliersList != null) { model.Suppliers = suppliersList.SupplierListModel; } // create list of ports to be selected model = PopulatePortsDropdown(model); ViewBag.SupplierList = model.Suppliers; ViewBag.PortList = model.Ports; model.LoggedInUserRole = HttpContext.Session.GetString("LoggedInUserRole"); model.Process = "ADD"; model.ETA = DateTime.Now; model.ContainerReceived = DateTime.Now; model.RedirectToSACD = DateTime.Now; return View("~/Views/Shipment/AddShipment.cshtml", model); } // create and populate a model for saving the shipment details var shipmentModel = new sdsShipment(); shipmentModel.user_id = HttpContext.Session.GetInt32("LoggedInUserId"); ; // need to sort out the session variable, as they are coming through as null here shipmentModel.supplier_id = model.SupplierId; shipmentModel.indent_number = model.IndentNumber; shipmentModel.shipshape_number = model.ShipshapeNumber; shipmentModel.mother_vessel = model.MotherVessel; shipmentModel.eta = model.ETA; shipmentModel.bill_of_entry_number = model.BillOfEntryNumber; shipmentModel.container_number = model.ContainerNumber; shipmentModel.port_id = model.PortId; shipmentModel.container_received = model.ContainerReceived; shipmentModel.no_of_flatcases = model.NoOfFlatcases; shipmentModel.voyage = model.Voyage; shipmentModel.mbl_number = model.MBLNumber; shipmentModel.redirect_to_SACD = model.RedirectToSACD; shipmentModel.created_by = HttpContext.Session.GetString("LoggedInUsername"); shipmentModel.created_at = DateTime.Now; shipmentModel.shipment_status = "SAVED"; var result = _shipmentService.AddShipment(shipmentModel); shipmentModel.id = result.id; //Await to ensure the update happens before uploading the files await _shipmentService.UpdateShipmentAsync(FileHelper(result, model)); //Upload files to SharePoint await _sharepointService.UploadFilesAsync(result, model.SharepointFiles); TempData["SuccessMessage"] = "Shipment Created Successfully"; //return RedirectToAction("ShipmentList", "Shipment"); //return await ShipmentDetail(shipmentModel.id); return RedirectToRoute(new { controller = "Shipment", action = "ShipmentDetail", id = shipmentModel.id }); } [HttpPost] [Route("shipment/updateshipment")] public async Task UpdateShipment(ShipmentViewModel model) { // variable to decide if files and folders need updating bool letsUpdate = false; string oldIndentNumber = ""; string newIndentNumber = ""; model.Process = "UPDATE"; // get the shipment to update var shipment = _shipmentService.GetShipment(model.Id); if (shipment != null) { // validate screen inputs if (ValidateScreen(model)) { shipment.supplier_id = model.SupplierId; // check if indent number has changed if (shipment.indent_number != model.IndentNumber) { // need to update folders and files letsUpdate = true; oldIndentNumber = shipment.indent_number; newIndentNumber = model.IndentNumber; } shipment.indent_number = model.IndentNumber; shipment.shipshape_number = model.ShipshapeNumber; shipment.mother_vessel = model.MotherVessel; shipment.eta = model.ETA; shipment.bill_of_entry_number = model.BillOfEntryNumber; shipment.container_number = model.ContainerNumber; shipment.port_id = model.PortId; shipment.container_received = model.ContainerReceived; shipment.no_of_flatcases = model.NoOfFlatcases; shipment.voyage = model.Voyage; shipment.mbl_number = model.MBLNumber; shipment.redirect_to_SACD = model.RedirectToSACD; shipment.updated_by = HttpContext.Session.GetString("LoggedInUsername"); shipment.updated_at = DateTime.Now; shipment.shipment_status = model.ShipmentStatus; shipment.cancel_reason = model.CancelReason; //await _sharepointService.UploadFilesAsync(shipment, model.files); await _shipmentService.UpdateShipmentAsync(FileHelper(shipment, model)); if (letsUpdate) { var fileList = GetShipmentFilesNames(shipment); await _sharepointService.RenameFoldersFiles(oldIndentNumber, "Shipment Checklist", newIndentNumber, fileList); } // updating and uploading files await _sharepointService.UploadFilesAsync(shipment, model.SharepointFiles); TempData["SuccessMessage"] = "Shipment Updated Successfully"; } } return RedirectToRoute(new { controller = "Shipment", action = "ShipmentDetail", id = model.Id }); } [HttpPost] [Route("shipment/submitshipment")] public async Task SubmitShipment(int id) { // get the shipment to update var shipment = _shipmentService.GetShipment(id); shipment.shipment_status = "SUBMITTED"; shipment.updated_by = HttpContext.Session.GetString("LoggedInUsername"); shipment.updated_at = DateTime.Now; await _shipmentService.UpdateShipmentAsync(shipment); TempData["SuccessMessage"] = "Shipment Submitted Successfully"; return RedirectToAction("ShipmentList", "Shipment"); } [HttpPost] [Route("shipment/cancelshipment")] public IActionResult CancelShipment(ShipmentViewModel model) { if (string.IsNullOrEmpty(model.CancelReason)) { // populate supplier list var suppliersList = _supplierService.GetSupplierList(); if (suppliersList != null) { model.Suppliers = suppliersList.SupplierListModel; } model = PopulatePortsDropdown(model); ViewBag.SupplierList = model.Suppliers; ViewBag.PortList = model.Ports; model.LoggedInUserRole = HttpContext.Session.GetString("LoggedInUserRole"); TempData["ErrorMessage"] = "Please enter a Cancel Reason before Cancelling Shipment."; return View("~/Views/Shipment/UpdateShipment.cshtml", model); } var updateModel = new ShipmentModel(); updateModel.Id = model.Id; updateModel.CancelReason = model.CancelReason; updateModel.UpdatedBy = HttpContext.Session.GetString("LoggedInUsername"); updateModel.UpdatedAt = DateTime.Now; _shipmentService.CancelShipment(updateModel); TempData["SuccessMessage"] = "Shipment Cancelled Successfully"; return RedirectToAction("ShipmentList", "Shipment"); } [HttpPost] [Route("shipment/deletefile")] public async Task DeleteFile(int id, string documentType) { var folderPath = ""; var fileName = ""; // get the shipment to update var s = _shipmentService.GetShipment(id); switch (documentType) { case "ClampingRequest": fileName = $"{s.indent_number}_{s.clamping_request_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.clamping_request_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "SupplierInvoice": fileName = $"{s.indent_number}_{s.supplier_invoice_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.supplier_invoice_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "BillOfLading": fileName = $"{s.indent_number}_{s.bill_of_lading_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.bill_of_lading_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "ArrivalInvoice": fileName = $"{s.indent_number}_{s.arrival_invoice_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.arrival_invoice_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "ArrivalInvoice2": fileName = $"{s.indent_number}_{s.arrival_invoice_file2}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.arrival_invoice_file2 = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "CerificateOfOrigin": fileName = $"{s.indent_number}_{s.certificate_of_origin_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.certificate_of_origin_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "PackingList": fileName = $"{s.indent_number}_{s.packing_list_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.packing_list_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "DROToTransport": fileName = $"{s.indent_number}_{s.dro_to_transport_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.dro_to_transport_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "CertificateOfRemoval": fileName = $"{s.indent_number}_{s.certificate_of_removal_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.certificate_of_removal_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "ExtendedDetention": fileName = $"{s.indent_number}_{s.extended_detention_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.extended_detention_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "VOC": fileName = $"{s.indent_number}_{s.voc_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.voc_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "DeptOfHealth": fileName = $"{s.indent_number}_{s.dept_of_health_inspection_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.dept_of_health_inspection_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "SARSDocuments": fileName = $"{s.indent_number}_{s.sars_documents_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.sars_documents_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "GRVCompleteRGBC": fileName = $"{s.indent_number}_{s.grv_complete_RGBC_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.grv_complete_RGBC_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "GRVEdwardSnell": fileName = $"{s.indent_number}_{s.grv_edward_snell_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.grv_edward_snell_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; case "ACCPACReceipts": fileName = $"{s.indent_number}_{s.accpac_receipts_file}"; folderPath = $"/Shipment Checklist/{s.indent_number}"; //remove filename from database s.accpac_receipts_file = ""; await _shipmentService.UpdateShipmentAsync(s); //delete file from sharepoint await _sharepointService.DeleteFileHelper(folderPath, fileName); break; default: break; } return RedirectToAction("ShipmentDetail", "Shipment", new { id }); } #endregion [ Post ] #region [ Helper Methods ] public bool ValidateScreen(ShipmentViewModel model) { bool isValid = true; string errorMessage = Environment.NewLine; if (model.SupplierId == 0) { errorMessage += "Please select a Supplier." + Environment.NewLine; isValid = false; } if (model.IndentNumber.IsNullOrEmpty()) { errorMessage += "Please enter a valid Indent Number." + Environment.NewLine; isValid = false; } else { if (!IsValidFolderName(model.IndentNumber)) { errorMessage += "Please refrain from using invalid characters." + Environment.NewLine; isValid = false; } } // check if indent number already exist in the database (only when creating new shipment) // indent numbers can't be duplicate if (model.Process == "SAVE") { if (DuplicateIndentNumber(model.IndentNumber)) { errorMessage += "Indent Number entered already exists." + Environment.NewLine; isValid = false; } } if (model.ShipshapeNumber.IsNullOrEmpty()) { errorMessage += "Please enter a valid Shipshape Number." + Environment.NewLine; isValid = false; } if (model.MotherVessel.IsNullOrEmpty()) { errorMessage += "Please enter a valid Mother Vessel." + Environment.NewLine; isValid = false; } if (model.BillOfEntryNumber.IsNullOrEmpty()) { errorMessage += "Please enter a valid Bill of Entry Number." + Environment.NewLine; isValid = false; } else { int num = 0; bool isNumeric = int.TryParse(model.BillOfEntryNumber, out num); if (!isNumeric) { errorMessage += "Please enter a valid Bill of Entry Number (Numbers Only)." + Environment.NewLine; isValid = false; } } if (model.ContainerNumber.IsNullOrEmpty()) { errorMessage += "Please enter a valid Container Number." + Environment.NewLine; isValid = false; } if (model.PortId == 0) { errorMessage += "Please select a valid Offloading Port." + Environment.NewLine; isValid = false; } if (model.NoOfFlatcases.IsNullOrEmpty()) { errorMessage += "Please enter a valid No of Flatcases" + Environment.NewLine; isValid = false; } else { int num = 0; bool isNumeric = int.TryParse(model.NoOfFlatcases, out num); if (!isNumeric) { errorMessage += "Please enter a valid No of Flatcases (Numbers Only)." + Environment.NewLine; isValid = false; } } if (model.Voyage.IsNullOrEmpty()) { errorMessage += "Please enter a valid Voyage." + Environment.NewLine; isValid = false; } if (model.MBLNumber.IsNullOrEmpty()) { errorMessage += "Please enter a valid M/BL Number." + Environment.NewLine; isValid = false; } //else //{ // int num = 0; // bool isNumeric = int.TryParse(model.MBLNumber, out num); // if (!isNumeric) // { // errorMessage += "Please enter a valid M/BL Number (Numbers Only)." + Environment.NewLine; // isValid = false; // } //} if (errorMessage.Length > 5) { TempData["ErrorMessage"] = errorMessage; } return isValid; } public sdsShipment FileHelper(sdsShipment shipmentModel, ShipmentViewModel shipmentViewModel) { //SharepointFileUploadModel uploadFiles = new SharepointFileUploadModel(); // check if any files have been selected for uploading, if so, upload the file // Clamping Request File if (shipmentViewModel.ClampingRequestFile != null) { SharepointFileUploadModel clampingRequestFile = new SharepointFileUploadModel(); // upload file to sharpoint clampingRequestFile.DocumentType = "ClampingRequest"; clampingRequestFile.File = shipmentViewModel.ClampingRequestFile; clampingRequestFile.OldFileName = shipmentModel.clamping_request_file; // get the file name to save to the database shipmentModel.clamping_request_file = shipmentViewModel.ClampingRequestFile.FileName; shipmentViewModel.SharepointFiles.Add(clampingRequestFile); } // Supplier Invoice File if (shipmentViewModel.SupplierInvoiceFile != null) { SharepointFileUploadModel supplierInvoiceFile = new SharepointFileUploadModel(); // upload file to sharepoint supplierInvoiceFile.DocumentType = "SupplierInvoice"; supplierInvoiceFile.File = shipmentViewModel.SupplierInvoiceFile; supplierInvoiceFile.OldFileName = shipmentModel.supplier_invoice_file; // get the file name to save to the database shipmentModel.supplier_invoice_file = shipmentViewModel.SupplierInvoiceFile.FileName; shipmentViewModel.SharepointFiles.Add(supplierInvoiceFile); } // Bill of Lading file if (shipmentViewModel.BillOfLadingFile != null) { SharepointFileUploadModel billOfLadingFile = new SharepointFileUploadModel(); // upload file to sharepoint billOfLadingFile.DocumentType = "BillOfLading"; billOfLadingFile.File = shipmentViewModel.BillOfLadingFile; billOfLadingFile.OldFileName = shipmentModel.bill_of_lading_file; // get the file name to save to the database shipmentModel.bill_of_lading_file = shipmentViewModel.BillOfLadingFile.FileName; shipmentViewModel.SharepointFiles.Add(billOfLadingFile); } // arrival invoice if (shipmentViewModel.ArrivalInvoiceFile != null) { SharepointFileUploadModel arrivalInvoiceFile = new SharepointFileUploadModel(); // upload file to sharepoint arrivalInvoiceFile.DocumentType = "ArrivalInvoice"; arrivalInvoiceFile.File = shipmentViewModel.ArrivalInvoiceFile; arrivalInvoiceFile.OldFileName = shipmentModel.arrival_invoice_file; // get the file name to save to the database shipmentModel.arrival_invoice_file = shipmentViewModel.ArrivalInvoiceFile.FileName; shipmentViewModel.SharepointFiles.Add(arrivalInvoiceFile); } // arrival invoice 2 if (shipmentViewModel.ArrivalInvoiceFile2 != null) { SharepointFileUploadModel arrivalInvoice2File = new SharepointFileUploadModel(); // upload file to sharepoint arrivalInvoice2File.DocumentType = "ArrivalInvoice2"; arrivalInvoice2File.File = shipmentViewModel.ArrivalInvoiceFile2; arrivalInvoice2File.OldFileName = shipmentModel.arrival_invoice_file2; // get the file name to save to the database shipmentModel.arrival_invoice_file2 = shipmentViewModel.ArrivalInvoiceFile2.FileName; shipmentViewModel.SharepointFiles.Add(arrivalInvoice2File); } // certificate of origin if (shipmentViewModel.CertificateOfOriginFile != null) { SharepointFileUploadModel certificateofOriginFile = new SharepointFileUploadModel(); // upload file to sharepoint certificateofOriginFile.DocumentType = "CertificateOfOrigin"; certificateofOriginFile.File = shipmentViewModel.CertificateOfOriginFile; certificateofOriginFile.OldFileName = shipmentModel.certificate_of_origin_file; // get the file name to save to the database shipmentModel.certificate_of_origin_file = shipmentViewModel.CertificateOfOriginFile.FileName; shipmentViewModel.SharepointFiles.Add(certificateofOriginFile); } // packing list if (shipmentViewModel.PackingListFile != null) { SharepointFileUploadModel packingListFile = new SharepointFileUploadModel(); // upload file to sharepoint packingListFile.DocumentType = "PackingList"; packingListFile.File = shipmentViewModel.PackingListFile; packingListFile.OldFileName = shipmentModel.packing_list_file; // get the file name to save to the database shipmentModel.packing_list_file = shipmentViewModel.PackingListFile.FileName; shipmentViewModel.SharepointFiles.Add(packingListFile); } // dro to transport if (shipmentViewModel.DROToTransportFile != null) { SharepointFileUploadModel droToTransportFile = new SharepointFileUploadModel(); // upload file to sharepoint droToTransportFile.DocumentType = "DROToTransport"; droToTransportFile.File = shipmentViewModel.DROToTransportFile; droToTransportFile.OldFileName = shipmentModel.dro_to_transport_file; // get the file name to save to the database shipmentModel.dro_to_transport_file = shipmentViewModel.DROToTransportFile.FileName; shipmentViewModel.SharepointFiles.Add(droToTransportFile); } // certificate of removal if (shipmentViewModel.CertificateOfRemovalFile != null) { SharepointFileUploadModel certificateOfRemovalFile = new SharepointFileUploadModel(); // upload file to sharepoint certificateOfRemovalFile.DocumentType = "CertificateOfRemoval"; certificateOfRemovalFile.File = shipmentViewModel.CertificateOfRemovalFile; certificateOfRemovalFile.OldFileName = shipmentModel.certificate_of_removal_file; // get the file name to save to the database shipmentModel.certificate_of_removal_file = shipmentViewModel.CertificateOfRemovalFile.FileName; shipmentViewModel.SharepointFiles.Add(certificateOfRemovalFile); } // extended detention if (shipmentViewModel.ExtendedDetentionFile != null) { SharepointFileUploadModel extendedDetentionFile = new SharepointFileUploadModel(); // upload file to sharepoint extendedDetentionFile.DocumentType = "ExtendedDetention"; extendedDetentionFile.File = shipmentViewModel.ExtendedDetentionFile; extendedDetentionFile.OldFileName = shipmentModel.extended_detention_file; // get the file name to save to the database shipmentModel.extended_detention_file = shipmentViewModel.ExtendedDetentionFile.FileName; shipmentViewModel.SharepointFiles.Add(extendedDetentionFile); } // voc file if (shipmentViewModel.VOCFile != null) { SharepointFileUploadModel vocFile = new SharepointFileUploadModel(); // upload file to sharepoint vocFile.DocumentType = "VOC"; vocFile.File = shipmentViewModel.VOCFile; vocFile.OldFileName = shipmentModel.voc_file; // get the file name to save to the database shipmentModel.voc_file = shipmentViewModel.VOCFile.FileName; shipmentViewModel.SharepointFiles.Add(vocFile); } // dept of health if (shipmentViewModel.DeptOfHealthFile != null) { SharepointFileUploadModel deptOfHealthFile = new SharepointFileUploadModel(); // upload file to sharepoint deptOfHealthFile.DocumentType = "DeptOfHealth"; deptOfHealthFile.File = shipmentViewModel.DeptOfHealthFile; deptOfHealthFile.OldFileName = shipmentModel.dept_of_health_inspection_file; // get the file name to save to the database shipmentModel.dept_of_health_inspection_file = shipmentViewModel.DeptOfHealthFile.FileName; shipmentViewModel.SharepointFiles.Add(deptOfHealthFile); } // sars documents if (shipmentViewModel.SARSDocumentsFile != null) { SharepointFileUploadModel sarsDocumentsFile = new SharepointFileUploadModel(); // upload file to sharepoint sarsDocumentsFile.DocumentType = "SARSDocuments"; sarsDocumentsFile.File = shipmentViewModel.SARSDocumentsFile; sarsDocumentsFile.OldFileName = shipmentModel.sars_documents_file; // get the file name to save to the database shipmentModel.sars_documents_file = shipmentViewModel.SARSDocumentsFile.FileName; shipmentViewModel.SharepointFiles.Add(sarsDocumentsFile); } // grv complete rgbc if (shipmentViewModel.GRVCompleteRGBCFile != null) { SharepointFileUploadModel grvCompleteRGBCFile = new SharepointFileUploadModel(); // upload file to sharepoint grvCompleteRGBCFile.DocumentType = "GRVCompleteRGBC"; grvCompleteRGBCFile.File = shipmentViewModel.GRVCompleteRGBCFile; grvCompleteRGBCFile.OldFileName = shipmentModel.grv_complete_RGBC_file; // get the file name to save to the database shipmentModel.grv_complete_RGBC_file = shipmentViewModel.GRVCompleteRGBCFile.FileName; shipmentViewModel.SharepointFiles.Add(grvCompleteRGBCFile); } // grv edward snell if (shipmentViewModel.GRVEdwardSnellFile != null) { SharepointFileUploadModel grvEdwardSnellFile = new SharepointFileUploadModel(); // upload file to sharepoint grvEdwardSnellFile.DocumentType = "GRVEdwardSnell"; grvEdwardSnellFile.File = shipmentViewModel.GRVEdwardSnellFile; grvEdwardSnellFile.OldFileName = shipmentModel.grv_edward_snell_file; // get the file name to save to the database shipmentModel.grv_edward_snell_file = shipmentViewModel.GRVEdwardSnellFile.FileName; shipmentViewModel.SharepointFiles.Add(grvEdwardSnellFile); } // accpac receipts if (shipmentViewModel.ACCPACReceiptsFile != null) { SharepointFileUploadModel accpaReceiptsFile = new SharepointFileUploadModel(); // upload file to sharepoint accpaReceiptsFile.DocumentType = "ACCPACReceipts"; accpaReceiptsFile.File = shipmentViewModel.ACCPACReceiptsFile; accpaReceiptsFile.OldFileName = shipmentModel.accpac_receipts_file; // get the file name to save to the database shipmentModel.accpac_receipts_file = shipmentViewModel.ACCPACReceiptsFile.FileName; shipmentViewModel.SharepointFiles.Add(accpaReceiptsFile); } return shipmentModel; } public ShipmentModel PopulateShipmentStatus(ShipmentModel model) { // create list of ports to be selected model.ShipmentStatusList.Add(new ShipmentStatusModel { Id = 1, Status = "Saved" }); model.ShipmentStatusList.Add(new ShipmentStatusModel { Id = 2, Status = "Submitted" }); model.ShipmentStatusList.Add(new ShipmentStatusModel { Id = 3, Status = "Cancelled" }); return model; } public ShipmentViewModel PopulatePortsDropdown(ShipmentViewModel model) { // create list of ports to be selected model.Ports.Add(new PortModel { Id = 1, Name = "Cape Town" }); model.Ports.Add(new PortModel { Id = 2, Name = "Coega" }); model.Ports.Add(new PortModel { Id = 3, Name = "Durban" }); model.Ports.Add(new PortModel { Id = 4, Name = "P.E." }); return model; } static bool IsValidFolderName(string folderName) { // Define a regex pattern to match invalid characters string pattern = "[\\\\/:*?\"<>|]"; // Invalid characters for Windows folder names // Check if the folderName contains any of the invalid characters return !Regex.IsMatch(folderName, pattern); } public List GetShipmentFilesNames(sdsShipment shipment) { var shipmentFileList = new List(); if (!shipment.clamping_request_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.clamping_request_file); } if (!shipment.supplier_invoice_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.supplier_invoice_file); } if (!shipment.bill_of_lading_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.bill_of_lading_file); } if (!shipment.arrival_invoice_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.arrival_invoice_file); } if (!shipment.arrival_invoice_file2.IsNullOrEmpty()) { shipmentFileList.Add(shipment.arrival_invoice_file2); } if (!shipment.certificate_of_origin_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.certificate_of_origin_file); } if (!shipment.packing_list_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.packing_list_file); } if (!shipment.dro_to_transport_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.dro_to_transport_file); } if (!shipment.certificate_of_removal_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.certificate_of_removal_file); } if (!shipment.extended_detention_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.extended_detention_file); } if (!shipment.voc_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.voc_file); } if (!shipment.dept_of_health_inspection_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.dept_of_health_inspection_file); } if (!shipment.sars_documents_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.sars_documents_file); } if (!shipment.grv_complete_RGBC_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.grv_complete_RGBC_file); } if (!shipment.grv_edward_snell_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.grv_edward_snell_file); } if (!shipment.accpac_receipts_file.IsNullOrEmpty()) { shipmentFileList.Add(shipment.accpac_receipts_file); } return shipmentFileList; } public bool DuplicateIndentNumber(string indent_number) { var shipment = _shipmentService.GetShipmentByIndentNumber(indent_number); return shipment; } private string GetPortName(int? portId) { if (!portId.HasValue) return "N/A"; switch (portId.Value) { case 1: return "Cape Town"; case 2: return "Coega"; case 3: return "Durban"; case 4: return "P.E."; default: return "N/A"; } } #endregion [ Helper Methods ] } }