using Microsoft.AspNetCore.Http; using ODCWeb.DataAccess.Repository.IRepository; using ODCWeb.Models; using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ODCWeb.DataAccess.Repository { public class TemplateService : ITemplateService { private readonly IUnitOfWork _unitOfWork; public TemplateService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public async Task<(bool isValid, string message)> ValidateTemplate(IFormFile file) { if (file == null || file.Length == 0) return (false, "No file uploaded"); if (!file.ContentType.Contains("spreadsheet")) return (false, "File must be an Excel spreadsheet"); using (var stream = new MemoryStream()) { await file.CopyToAsync(stream); stream.Position = 0; // Reset stream position using (ExcelEngine excelEngine = new ExcelEngine()) { IApplication application = excelEngine.Excel; try { IWorkbook workbook = application.Workbooks.Open(stream); IWorksheet worksheet = workbook.Worksheets[0]; var range = worksheet.UsedRange; int firstCol = range.Column; int lastCol = range.End.Column; int firstRow = range.Row; int lastRow = range.End.Row; if (lastCol > 9) return (false, "Template should not exceed column I"); if (firstCol != 1) return (false, "Template should start from column A"); if (worksheet.PageSetup.PaperSize != ExcelPaperSize.PaperA4) return (false, "Template must be set up for A4 paper size"); int rowCount = lastRow - firstRow + 1; if (rowCount > 250) return (false, "Template content must fit on one A4 page"); return (true, "Template is valid"); } catch (Exception ex) { return (false, $"Invalid template format: {ex.Message}"); } } } } public async Task SaveTemplate(IFormFile file, string userId) { using (var ms = new MemoryStream()) { await file.CopyToAsync(ms); // Delete existing templates first var existingTemplates = _unitOfWork.ExcelTemplate.GetAll(); foreach (var templatee in existingTemplates) { _unitOfWork.ExcelTemplate.Remove(templatee); } _unitOfWork.save(); // Save new template var template = new ExcelTemplate { Name = file.FileName, FileContent = ms.ToArray(), UploadedDate = DateTime.UtcNow, UploadedBy = userId }; _unitOfWork.ExcelTemplate.Add(template); _unitOfWork.save(); return template; } } } }