Files
DiunaBI/WebAPI/Controllers/LayersController.cs

609 lines
26 KiB
C#
Raw Normal View History

using System.Globalization;
using System.Xml.Serialization;
2023-02-22 12:12:38 +01:00
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.dataParsers;
2023-10-02 19:59:43 +02:00
using WebAPI.dataProcessors;
2023-02-22 12:12:38 +01:00
using WebAPI.Exports;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
2023-08-21 12:30:18 +02:00
2023-02-22 12:12:38 +01:00
public class LayersController : Controller
{
private readonly AppDbContext db;
private SpreadsheetsResource.ValuesResource googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
2023-08-29 14:55:31 +02:00
private GoogleSheetsHelper googleSheetsHelper;
2023-02-22 12:12:38 +01:00
private readonly IConfiguration configuration;
private readonly LogsController logsController;
2023-02-22 12:12:38 +01:00
public LayersController(
AppDbContext _db,
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
db = _db;
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
2023-08-29 14:55:31 +02:00
googleSheetsHelper = _googleSheetsHelper;
2023-02-22 12:12:38 +01:00
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration);
2023-02-22 12:12:38 +01:00
}
[HttpGet]
2023-10-20 13:56:40 +02:00
public IActionResult GetAll(int start, int limit, string? name, LayerType? type)
2023-02-22 12:12:38 +01:00
{
try
2023-08-29 14:55:31 +02:00
{
2023-10-20 13:56:40 +02:00
IQueryable<Layer> response = db.Layers.Where(x => !x.IsDeleted);
2023-11-06 17:19:20 +01:00
if (name != null)
2023-08-29 14:55:31 +02:00
{
2023-11-06 17:19:20 +01:00
response = response.Where(x => x.Name.Contains(name));
}
2023-11-06 17:19:20 +01:00
if (type != null)
2023-08-29 14:55:31 +02:00
{
2023-11-06 17:19:20 +01:00
response = response.Where(x => x.Type == type);
2023-06-25 19:08:26 +02:00
}
2023-10-20 13:56:40 +02:00
return Ok(response
.OrderByDescending(x => x.Number)
.Skip(start).Take(limit).ToList());
2023-11-06 17:19:20 +01:00
2023-02-22 12:12:38 +01:00
}
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(AddLayer(input, currentUserId).Id);
}
catch (Exception e)
2023-02-22 12:12:38 +01:00
{
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("parseGoogleSheet/{sheetId}")]
public IActionResult ParseGoogleSheet(string sheetId)
{
string sheetName = "KOSZTY";
Layer layer = new Layer();
layer.Source = "GoogleSheet";
layer.Number = db.Layers.Count() + 1;
var parser = new googleSheetParser(googleSheetValues);
dynamic parsedSheet = parser.parse(sheetId);
layer.Records = parsedSheet.records;
layer.Name = $"W{layer.Number}-I-{sheetName}-{parsedSheet.date}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
return Ok(layer);
}
[HttpPost]
[DisableRequestSizeLimit]
[Route("parseFile")]
public IActionResult ParseFile()
{
var parser = new csvParser();
return Ok(parser.parse(Request.Form.Files[0]));
}
[HttpGet]
[Route("exportToGoogleSheet/{id}")]
public IActionResult ExportToGoogleSheet(Guid id)
{
Layer layer = db.Layers
2023-08-23 17:30:25 +02:00
.Include(x => x.Records!.OrderByDescending(x => x.Code))
2023-02-22 12:12:38 +01:00
.Where(x => x.Id == id && !x.IsDeleted).First();
2023-08-23 17:30:25 +02:00
var export = new googleSheetExport(googleDriveHelper, googleSheetValues, configuration);
2023-02-22 12:12:38 +01:00
export.export(layer);
return Ok(true);
}
[HttpGet]
2023-08-29 14:55:31 +02:00
[Route("AutoImport/{apiKey}")]
2023-02-22 12:12:38 +01:00
[AllowAnonymous]
2023-08-29 14:55:31 +02:00
public IActionResult AutoImport(string apiKey)
2023-02-22 12:12:38 +01:00
{
2023-08-30 23:18:54 +02:00
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
2023-02-22 12:12:38 +01:00
{
return Unauthorized();
}
List<Layer> importWorkerLayers;
List<Layer> layersToImport; ;
try
{
importWorkerLayers = db.Layers
.Include(x => x.Records)
.Where(x => x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ImportWorker"))
.ToList();
layersToImport = new List<Layer>();
foreach (Layer layer in importWorkerLayers)
{
string startDate = layer.Records!.Where(x => x.Code == "StartDate").First().Desc1!;
string endDate = layer.Records!.Where(x => x.Code == "EndDate").First().Desc1!;
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)
{
processImportWorker(layer);
}
}
}
catch (Exception e)
{
logsController.AddEntry(new LogEntry
2023-08-29 14:55:31 +02:00
{
Title = "Import error",
Type = LogEntryType.error,
2023-09-01 18:23:53 +02:00
LogType = LogType.import,
2023-08-29 14:55:31 +02:00
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
2023-08-29 14:55:31 +02:00
return BadRequest(e.ToString());
}
return Ok();
2023-10-02 19:59:43 +02:00
}
2023-08-20 13:05:10 +02:00
[HttpGet]
2023-11-08 18:09:01 +01:00
[Route("AutoProcess/{apiKey}/{type}")]
2023-08-20 13:05:10 +02:00
[AllowAnonymous]
2023-11-08 18:09:01 +01:00
public IActionResult AutoProcess(string apiKey, string type)
2023-08-20 13:05:10 +02:00
{
2023-08-30 23:18:54 +02:00
if (Request.Host.Value != configuration["apiLocalUrl"] || apiKey != configuration["apiKey"])
2023-08-20 13:05:10 +02:00
{
return Unauthorized();
}
2023-08-29 14:55:31 +02:00
2023-09-17 13:00:24 +02:00
try
{
List<Layer> processWorkerLayers = db.Layers
2023-09-17 13:00:24 +02:00
.Include(x => x.Records)
2023-10-30 15:22:57 +01:00
.Where(x =>
x.Records!.Any(x => x.Code == "Type" && x.Desc1 == "ProcessWorker") &&
2023-11-08 18:09:01 +01:00
x.Records!.Any(x => x.Code == "IsEnabled" && x.Desc1 == "True") &&
x.Records!.Any(x => x.Code == "ProcessType" && x.Desc1 == type)
2023-10-30 16:39:13 +01:00
)
.OrderBy(x => x.CreatedAt)
2023-09-17 13:00:24 +02:00
.ToList();
2023-08-20 13:05:10 +02:00
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;
}
2023-11-06 23:11:30 +01:00
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;
}
}
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();
2023-11-06 17:19:20 +01:00
2023-09-18 19:41:39 +02:00
foreach (Layer processWorker in processWorkerLayers)
2023-09-17 13:00:24 +02:00
{
2023-11-06 17:19:20 +01:00
string? processType = processWorker?.Records?.Single(x => x.Code == "ProcessType")?.Desc1;
if (processType == null)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.import,
Message = processWorker?.Name + " ProcessType record not found",
CreatedAt = DateTime.UtcNow
});
return BadRequest();
}
List<Record>? sources = processWorker?.Records?.Where(x => x.Code == "Source").ToList();
if (sources != null && sources.Count() == 0)
2023-10-02 19:59:43 +02:00
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.import,
Message = processWorker?.Name + " Source record not found",
CreatedAt = DateTime.UtcNow
});
return BadRequest();
2023-11-06 17:19:20 +01:00
}
if (processType == "T3-SourceSummary")
{
if (processWorker != null)
{
//T3SourceYearSummaryProcessor processor = new T3SourceYearSummaryProcessor(db, googleSheetValues, this);
// processor.process(processWorker);
2023-11-06 17:19:20 +01:00
}
} else if (processType == "T3-MultiSourceSummary")
{
var tst = 5;
} else
2023-09-17 13:00:24 +02:00
{
2023-11-06 17:19:20 +01:00
2023-10-02 19:59:43 +02:00
Layer sourceLayer = db.Layers.Include(x => x.Records)
.Single(x => x.Name == sources!.First().Desc1);
2023-10-02 19:59:43 +02:00
if (sourceLayer == null)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
LogType = LogType.import,
Message = processWorker?.Name + " Source layer not found " + sourceLayer,
CreatedAt = DateTime.UtcNow
});
return BadRequest();
2023-11-06 17:19:20 +01:00
}
string startDate = sourceLayer.Records!.Where(x => x.Code == "StartDate").First().Desc1!;
string endDate = sourceLayer.Records!.Where(x => x.Code == "EndDate").First().Desc1!;
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)
2023-10-02 19:59:43 +02:00
{
2023-11-06 17:19:20 +01:00
logsController.AddEntry(new LogEntry
{
Title = $"Process Success, {sourceLayer.Name}",
Type = LogEntryType.info,
LogType = LogType.process,
CreatedAt = DateTime.UtcNow
});
} else if (endDateParsed.Date >= DateTime.UtcNow.Date)
{
// TODO: make isEnabled = false - layer is out of date
var name = processWorker.Name;
2023-10-02 19:59:43 +02:00
}
2023-09-17 13:00:24 +02:00
}
}
2023-11-06 17:19:20 +01:00
2023-09-18 19:41:39 +02:00
return Ok();
2023-09-17 13:00:24 +02:00
}
catch (Exception e)
{
logsController.AddEntry(new LogEntry
{
Title = "Process error",
Type = LogEntryType.error,
2023-09-18 19:41:39 +02:00
LogType = LogType.process,
2023-09-17 13:00:24 +02:00
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
2023-10-02 19:59:43 +02:00
}
2023-08-21 12:30:18 +02:00
[HttpGet]
[Route("checkDates")]
public IActionResult checkDates()
2023-08-21 12:30:18 +02:00
{
2023-08-29 14:55:31 +02:00
var warsawTZ = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
DateTime date = DateTime.UtcNow;
return Ok(date);
2023-02-22 12:12:38 +01:00
}
//
private void processImportWorker(Layer importWorker)
{
// get and check settings
string? sheetId = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
if (sheetId == null)
{
throw new Exception($"SheetId not found, {importWorker.Name}");
}
string? sheetTabName = importWorker.Records!.Where(x => x.Code == "SheetTabName").FirstOrDefault()?.Desc1;
2023-10-02 21:14:15 +02:00
if (sheetTabName == null)
{
throw new Exception($"SheetTabName not found, {importWorker.Name}");
}
string? importYearCell = importWorker.Records!.Where(x => x.Code == "ImportYear").FirstOrDefault()?.Desc1;
if (importYearCell == null)
{
throw new Exception($"ImportYear not found, {importWorker.Name}");
}
string? importMonthCell = importWorker.Records!.Where(x => x.Code == "ImportMonth").FirstOrDefault()?.Desc1;
if (importMonthCell == null)
{
throw new Exception($"ImportMonth not found, {importWorker.Name}");
}
string? importNameCell = importWorker.Records!.Where(x => x.Code == "ImportName").FirstOrDefault()?.Desc1;
if (importNameCell == null)
{
throw new Exception($"ImportName not found, {importWorker.Name}");
}
string? checkSumCell = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
if (checkSumCell == null)
{
throw new Exception($"SheetId not found, {importWorker.Name}");
}
string? dataRange = importWorker.Records!.Where(x => x.Code == "DataRange").FirstOrDefault()?.Desc1;
if (dataRange == null)
{
throw new Exception($"DataRange not found, {importWorker.Name}");
}
// open excel and read data
var nameResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{importNameCell}:{importNameCell}").Execute();
2023-10-02 21:14:15 +02:00
string? name = nameResponse.Values?[0][0].ToString();
if (name == null)
{
throw new Exception($"ImportName cell is empty, {importWorker.Name}");
}
var yearResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{importYearCell}:{importYearCell}").Execute();
string? year = yearResponse.Values[0][0].ToString();
if (year == null)
{
throw new Exception($"ImportYear cell is empty, {importWorker.Name}");
}
var monthResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{importMonthCell}:{importMonthCell}").Execute();
string? month = monthResponse.Values[0][0].ToString();
if (month == null)
{
throw new Exception($"ImportMonth cell is empty, {importWorker.Name}");
}
Layer layer = new Layer
{
Source = "GoogleSheet",
2023-09-18 11:29:25 +02:00
Number = db.Layers.Count() + 1,
ParentId = importWorker.Id
};
layer.Name = $"L{layer.Number}-I-{name}-{year}/{month}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
layer.Type = LayerType.import;
layer.Records = new List<Record>();
var dataRangeResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{dataRange}").Execute();
var data = dataRangeResponse.Values;
for (int i = 0; i < data[1].Count; i++)
{
float value;
if (
data[0][i].ToString()?.Length > 0 &&
float.TryParse(data[1][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out value))
{
Record record = new Record
{
Id = Guid.NewGuid(),
Code = data[0][i].ToString(),
Value1 = value,
CreatedAt = DateTime.UtcNow,
ModifiedAt = DateTime.UtcNow
};
layer.Records.Add(record);
};
}
2023-11-06 17:19:20 +01:00
2023-09-02 12:01:35 +02:00
AddLayer(layer, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
2023-11-06 17:19:20 +01:00
logsController.AddEntry(new LogEntry
{
Title = $"Import Success, {importWorker.Name}",
Type = LogEntryType.info,
2023-09-01 18:23:53 +02:00
LogType = LogType.import,
CreatedAt = DateTime.UtcNow
});
2023-11-06 17:19:20 +01:00
}
2023-10-20 09:28:42 +02:00
internal Layer AddLayer(Layer input, Guid currentUserId)
2023-02-22 12:12:38 +01:00
{
input.CreatedById = currentUserId;
input.ModifiedById = currentUserId;
input.CreatedAt = DateTime.UtcNow;
input.ModifiedAt = DateTime.UtcNow;
db.Layers.Add(input);
SaveRecords(input.Id, input.Records!, currentUserId);
db.SaveChanges();
return input;
}
2023-10-20 09:28:42 +02:00
internal void SaveRecords(Guid id, ICollection<Record> records, Guid currentUserId)
2023-02-22 12:12:38 +01:00
{
try
{
2023-11-06 17:19:20 +01:00
List<Record> toDelete = db.Records.Where(x => x.LayerId == id).ToList();
if (toDelete.Count > 0)
{
db.Records.RemoveRange(toDelete);
}
2023-02-22 12:12:38 +01:00
foreach (Record record in records)
{
record.CreatedById = currentUserId;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedById = currentUserId;
record.ModifiedAt = DateTime.UtcNow;
record.LayerId = id;
2023-02-22 12:12:38 +01:00
db.Records.Add(record);
}
}
catch (Exception)
{
throw;
}
2023-10-02 19:59:43 +02:00
}
2023-09-18 19:41:39 +02:00
private void SaveSources(ICollection<ProcessSource> sources)
{
try
{
foreach (ProcessSource processSource in sources)
{
Console.WriteLine($"{processSource.LayerId} {processSource.SourceId}");
2023-10-03 22:29:42 +02:00
db.ProcessSources.Add(processSource);
2023-09-18 19:41:39 +02:00
}
}
catch (Exception)
{
throw;
}
2023-02-22 12:12:38 +01:00
}
}
2022-12-11 23:40:16 +01:00
}