using DiunaBIWebAPI.dataImporters; using Google.Apis.Sheets.v4; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebAPI.dataProcessors; using WebAPI.Exports; using WebAPI.Models; namespace WebAPI.Controllers { [ApiController] [Route("api/[controller]")] public class LayersController : Controller { private readonly AppDbContext db; private SpreadsheetsResource.ValuesResource? googleSheetValues; private GoogleDriveHelper googleDriveHelper; private GoogleSheetsHelper googleSheetsHelper; private readonly IConfiguration configuration; private readonly LogsController logsController; public LayersController( AppDbContext _db, GoogleSheetsHelper _googleSheetsHelper, GoogleDriveHelper _googleDriveHelper, IConfiguration _configuration) { db = _db; if (_googleSheetsHelper.Service is not null) { googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values; } googleSheetsHelper = _googleSheetsHelper; googleDriveHelper = _googleDriveHelper; configuration = _configuration; logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration); } [HttpGet] public IActionResult GetAll(int start, int limit, string? name, LayerType? type) { try { IQueryable response = db.Layers.Where(x => !x.IsDeleted); if (name != null) { response = response.Where(x => x.Name!=null && x.Name.Contains(name)); } if (type != null) { response = response.Where(x => x.Type == type); } return Ok(response .OrderByDescending(x => x.Number) .Skip(start).Take(limit).ToList()); } catch (Exception e) { return BadRequest(e.ToString()); } } [HttpPost] public IActionResult Save(Layer input) { try { //Request.Headers.TryGetValue("userId", out var value); //Guid currentUserId = new Guid(value!); return Ok(); } catch (Exception e) { return BadRequest(e.ToString()); } } [HttpGet] [Route("{id}")] public IActionResult Get(Guid id) { try { return Ok(db.Layers .Include(x => x.CreatedBy) .Include(x => x.Records) .Where(x => x.Id == id && !x.IsDeleted).First()); } catch (Exception e) { return BadRequest(e.ToString()); } } [HttpGet] [Route("getByNumber/{apiKey}/{number}")] public IActionResult GetByNumber(string apiKey, int number) { if (apiKey != configuration["apiKey"]) { return Unauthorized(); } try { return Ok(db.Layers .Include(x => x.CreatedBy) .Include(x => x.Records) .Where(x => x.Number == number && !x.IsDeleted).First()); } catch (Exception e) { return BadRequest(e.ToString()); } } [HttpGet] [Route("exportToGoogleSheet/{id}")] public IActionResult ExportToGoogleSheet(Guid id) { if (googleSheetValues is null) { throw new Exception("Google Sheets API not initialized"); } Layer layer = db.Layers .Include(x => x.Records!.OrderByDescending(x => x.Code)) .Where(x => x.Id == id && !x.IsDeleted).First(); var export = new googleSheetExport(googleDriveHelper, googleSheetValues, configuration); export.export(layer); return Ok(true); } [HttpGet] [Route("AutoImport/{apiKey}")] [AllowAnonymous] public IActionResult AutoImport(string apiKey) { if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"]) { return Unauthorized(); } if (googleSheetValues is null) { throw new Exception("Google Sheets API not initialized"); } try { List importWorkerLayers; importWorkerLayers = db.Layers .Include(x => x.Records) .Where(x => x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ImportWorker") && x.Records!.Any(x => x.Code == "IsEnabled" && x.Desc1 == "True") ) .OrderBy(x => x.CreatedAt) .ToList(); if (importWorkerLayers.Count() == 0) { logsController.AddEntry(new LogEntry { Title = "No Layers to import.", Type = LogEntryType.info, LogType = LogType.import, CreatedAt = DateTime.UtcNow, }); return Ok(); } foreach (Layer importWorker in importWorkerLayers) { try { string? startDate = importWorker.Records!.FirstOrDefault(x => x.Code == "StartDate")?.Desc1; if (startDate == null) { throw new Exception("Year record nod found"); } string? endDate = importWorker.Records!.Where(x => x.Code == "EndDate").First().Desc1; if (endDate == null) { throw new Exception("Year record nod found"); } var startDateParsed = DateTime.ParseExact(startDate!, "yyyy.MM.dd", null); var endDateParsed = DateTime.ParseExact(endDate!, "yyyy.MM.dd", null); if (startDateParsed.Date <= DateTime.UtcNow.Date && endDateParsed.Date >= DateTime.UtcNow.Date) { MorskaImporter importer = new MorskaImporter(db, googleSheetValues, this); importer.import(importWorker); logsController.AddEntry(new LogEntry { Title = $"{importWorker!.Name}, {importWorker.Id}", Type = LogEntryType.info, LogType = LogType.import, Message = "Success", CreatedAt = DateTime.UtcNow }); } else { logsController.AddEntry(new LogEntry { Title = $"{importWorker!.Name}, {importWorker.Id}", Type = LogEntryType.warning, LogType = LogType.import, Message = "importLayer is out of date. Should be disabled. Not processed.", CreatedAt = DateTime.UtcNow }); } } catch(Exception e) { logsController.AddEntry(new LogEntry { Title = $"{importWorker!.Name}, {importWorker.Id}", Type = LogEntryType.error, LogType = LogType.import, Message = e.ToString(), CreatedAt = DateTime.UtcNow }); } } return Ok(); } catch(Exception e) { logsController.AddEntry(new LogEntry { Title = "Process error", Type = LogEntryType.error, LogType = LogType.import, Message = e.ToString(), CreatedAt = DateTime.UtcNow }); return BadRequest(e.ToString()); } } [HttpGet] [Route("AutoProcess/{apiKey}/{type}")] [AllowAnonymous] public IActionResult AutoProcess(string apiKey, string type) { if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"]) { return Unauthorized(); } if (googleSheetValues is null) { throw new Exception("Google Sheets API not initialized"); } try { List processWorkerLayers = db.Layers .Include(x => x.Records) .Where(x => x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ProcessWorker") && x.Records!.Any(x => x.Code == "IsEnabled" && x.Desc1 == "True") && x.Records!.Any(x => x.Code == "ProcessType" && x.Desc1 == type) ) .OrderBy(x => x.CreatedAt) .ToList(); if (processWorkerLayers.Count() == 0) { logsController.AddEntry(new LogEntry { Title = "No Layers to process.", Type = LogEntryType.info, LogType = LogType.process, CreatedAt = DateTime.UtcNow, }); return Ok(); } foreach (Layer processWorker in processWorkerLayers) { try { string? name = processWorker.Name; string? year = processWorker?.Records?.SingleOrDefault(x => x.Code == "Year")?.Desc1; if (year == null) { throw new Exception("Year record nod found"); } if (int.Parse(year!) < DateTime.UtcNow.Year) { logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.warning, LogType = LogType.process, Message = "processLayer is out of date. Should be disabled. Not processed.", CreatedAt = DateTime.UtcNow }); continue; } string? processType = processWorker?.Records?.SingleOrDefault(x => x.Code == "ProcessType")?.Desc1; if (processType == null) { throw new Exception("ProcessType record not found"); } if (processType == "T3-SourceYearSummary") { if (int.Parse(year!) < DateTime.UtcNow.Year) { logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.warning, LogType = LogType.process, Message = "processLayer is out of date. Should be disabled. Not processed", CreatedAt = DateTime.UtcNow }); continue; } T3SourceYearSummaryProcessor processor = new T3SourceYearSummaryProcessor(db, googleSheetValues, this); processor.process(processWorker!); logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.info, LogType = LogType.process, Message = "Success", CreatedAt = DateTime.UtcNow }); continue; } if (processType == "T3-MultiSourceYearSummary") { if (int.Parse(year!) < DateTime.UtcNow.Year) { logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.warning, LogType = LogType.process, Message = "processLayer is out of date. Should be disabled. Not processed", CreatedAt = DateTime.UtcNow }); continue; } T3MultiSourceYearSummaryProcessor processor = new T3MultiSourceYearSummaryProcessor(db, googleSheetValues, this); processor.process(processWorker!); logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.info, LogType = LogType.process, Message = "Success", CreatedAt = DateTime.UtcNow }); continue; } string? month = processWorker?.Records?.SingleOrDefault(x => x.Code == "Month")?.Desc1; if (month == null) { throw new Exception("Month record not found"); } if (int.Parse(month!) < DateTime.UtcNow.Month) { logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.warning, LogType = LogType.process, Message = "processLayer is out of date. Should be disabled.", CreatedAt = DateTime.UtcNow }); } switch (processType!) { case "T3-SingleSource": { T3SingleSourceProcessor processor = new T3SingleSourceProcessor(db, googleSheetValues, this); processor.process(processWorker!); break; } case "T3-MultiSourceSummary": { T3MultiSourceSummaryProcessor processor = new T3MultiSourceSummaryProcessor(db, googleSheetValues, this); processor.process(processWorker!); break; } case "T3-MultiSourceCopySelectedCodes": { T3MultiSourceCopySelectedCodesProcessor processor = new T3MultiSourceCopySelectedCodesProcessor(db, googleSheetValues, this); processor.process(processWorker!); processor.updateReport(); break; } } logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.info, LogType = LogType.process, Message = "Success", CreatedAt = DateTime.UtcNow }); } catch (Exception e) { logsController.AddEntry(new LogEntry { Title = $"{processWorker!.Name}, {processWorker.Id}", Type = LogEntryType.error, LogType = LogType.process, Message = e.ToString(), CreatedAt = DateTime.UtcNow }); } } return Ok(); } catch (Exception e) { logsController.AddEntry(new LogEntry { Title = "Process error", Type = LogEntryType.error, LogType = LogType.process, Message = e.ToString(), CreatedAt = DateTime.UtcNow }); return BadRequest(e.ToString()); } } internal void SaveRecords(Guid id, ICollection records, Guid currentUserId) { try { List toDelete = db.Records.Where(x => x.LayerId == id).ToList(); if (toDelete.Count > 0) { db.Records.RemoveRange(toDelete); } foreach (Record record in records) { record.CreatedById = currentUserId; record.CreatedAt = DateTime.UtcNow; record.ModifiedById = currentUserId; record.ModifiedAt = DateTime.UtcNow; record.LayerId = id; db.Records.Add(record); } } catch (Exception) { throw; } } } }