WIP: refactor
This commit is contained in:
@@ -1,11 +1,10 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Collections.Generic;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI
|
||||
namespace WebAPI;
|
||||
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public DbSet<User> Users { get; init; }
|
||||
public DbSet<Layer> Layers { get; init; }
|
||||
public DbSet<Record> Records { get; init; }
|
||||
@@ -33,5 +32,4 @@ namespace WebAPI
|
||||
{
|
||||
optionsBuilder.UseLoggerFactory(MyLoggerFactory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ public class BaseCalc
|
||||
}
|
||||
|
||||
Entity expr = formula;
|
||||
ProcessHelper.setValue(result, i, (double)expr.EvalNumerical());
|
||||
ProcessHelper.SetValue(result, i, (double)expr.EvalNumerical());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -3,14 +3,13 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using WebAPI.Models;
|
||||
using static Google.Apis.Drive.v3.FilesResource;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
namespace WebAPI.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AdminController : Controller
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AdminController : Controller
|
||||
{
|
||||
private readonly GoogleDriveHelper _googleDriveHelper;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly LogsController _logsController;
|
||||
@@ -37,18 +36,20 @@ namespace WebAPI.Controllers
|
||||
|
||||
try
|
||||
{
|
||||
var databaseName = "diunabi-morska";
|
||||
const string databaseName = "diunabi-morska";
|
||||
var localDatabasePath = $"{_configuration["dbBackupFile"]}-{DateTime.UtcNow.Day}.bak";
|
||||
var formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
|
||||
var formatName = $"Full Backup of {databaseName}";
|
||||
const string formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
|
||||
const string formatName = $"Full Backup of {databaseName}";
|
||||
|
||||
var connection = new SqlConnection(_configuration.GetConnectionString("SQLDatabase"));
|
||||
|
||||
var sql = @"BACKUP DATABASE @databaseName
|
||||
const string sql = """
|
||||
BACKUP DATABASE @databaseName
|
||||
TO DISK = @localDatabasePath
|
||||
WITH FORMAT,
|
||||
MEDIANAME = @formatMediaName,
|
||||
NAME = @formatName";
|
||||
NAME = @formatName
|
||||
""";
|
||||
|
||||
connection.Open();
|
||||
var command = new SqlCommand(sql, connection);
|
||||
@@ -62,7 +63,7 @@ namespace WebAPI.Controllers
|
||||
|
||||
command.ExecuteNonQuery();
|
||||
|
||||
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File
|
||||
var body = new Google.Apis.Drive.v3.Data.File
|
||||
{
|
||||
Name = Path.GetFileName(localDatabasePath),
|
||||
Parents = new List<string?> { _configuration["GDriveBackupDirectory"] },
|
||||
@@ -103,5 +104,4 @@ namespace WebAPI.Controllers
|
||||
return BadRequest(e.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +1,40 @@
|
||||
using Google.Apis.Auth;
|
||||
using Google.Apis.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Configuration;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
namespace WebAPI.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
// [Authorize]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
// [Authorize]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
private readonly AppDbContext db;
|
||||
private readonly IConfiguration configuration;
|
||||
private readonly AppDbContext _db;
|
||||
private readonly IConfiguration _configuration;
|
||||
public AuthController(
|
||||
AppDbContext _db, IConfiguration _configuration)
|
||||
{ db = _db; configuration = _configuration; }
|
||||
AppDbContext db, IConfiguration configuration)
|
||||
{ _db = db; _configuration = configuration; }
|
||||
|
||||
[HttpPost]
|
||||
[Route("apiToken")]
|
||||
public async Task<IActionResult> apiToken([FromBody] string credential)
|
||||
public async Task<IActionResult> ApiToken([FromBody] string credential)
|
||||
{
|
||||
var settings = new GoogleJsonWebSignature.ValidationSettings()
|
||||
var settings = new GoogleJsonWebSignature.ValidationSettings
|
||||
{
|
||||
Audience = new List<string> { configuration.GetValue<string>("GoogleClientId")! }
|
||||
Audience = new List<string> { _configuration.GetValue<string>("GoogleClientId")! }
|
||||
};
|
||||
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
|
||||
var user = db.Users.Where(x => x.Email == payload.Email).FirstOrDefault();
|
||||
if (user != null)
|
||||
{
|
||||
return Ok(JWTGenerator(user));
|
||||
}
|
||||
else
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
var user = _db.Users.FirstOrDefault(x => x.Email == payload.Email);
|
||||
return user != null ? (IActionResult)Ok(JwtGenerator(user)) : Unauthorized();
|
||||
}
|
||||
|
||||
private dynamic JWTGenerator(User user)
|
||||
private dynamic JwtGenerator(User user)
|
||||
{
|
||||
var key = Encoding.ASCII.GetBytes(configuration.GetValue<string>("Secret")!);
|
||||
var key = Encoding.ASCII.GetBytes(_configuration.GetValue<string>("Secret")!);
|
||||
var expirationTime = DateTime.UtcNow.AddMinutes(5);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
@@ -64,9 +52,7 @@ namespace WebAPI.Controllers
|
||||
};
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
var jwtToken = tokenHandler.WriteToken(token);
|
||||
var stringToken = tokenHandler.WriteToken(token);
|
||||
return new { token = stringToken, id = user.Id, expirationTime };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,16 +9,15 @@ using WebAPI.dataProcessors;
|
||||
using WebAPI.Exports;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
namespace WebAPI.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class LayersController : Controller
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class LayersController : Controller
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly SpreadsheetsResource.ValuesResource? _googleSheetValues;
|
||||
private readonly GoogleDriveHelper _googleDriveHelper;
|
||||
// private GoogleSheetsHelper _googleSheetsHelper;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly LogsController _logsController;
|
||||
|
||||
@@ -26,7 +25,8 @@ namespace WebAPI.Controllers
|
||||
AppDbContext db,
|
||||
GoogleSheetsHelper googleSheetsHelper,
|
||||
GoogleDriveHelper googleDriveHelper,
|
||||
IConfiguration configuration)
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
_db = db;
|
||||
if (googleSheetsHelper.Service is not null)
|
||||
@@ -34,10 +34,9 @@ namespace WebAPI.Controllers
|
||||
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
|
||||
}
|
||||
|
||||
//_googleSheetsHelper = googleSheetsHelper;
|
||||
_googleDriveHelper = googleDriveHelper;
|
||||
_configuration = configuration;
|
||||
_logsController = new LogsController(googleSheetsHelper, googleDriveHelper, configuration);
|
||||
_logsController = new LogsController(googleSheetsHelper, _configuration);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
@@ -67,7 +66,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("{id}")]
|
||||
[Route("{id:guid}")]
|
||||
public IActionResult Get(Guid id)
|
||||
{
|
||||
try
|
||||
@@ -83,7 +82,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("getForPowerBI/{apiKey}/{number}")]
|
||||
[Route("getForPowerBI/{apiKey}/{number:int}")]
|
||||
public IActionResult GetByNumber(string apiKey, int number)
|
||||
{
|
||||
if (apiKey != _configuration["apiKey"])
|
||||
@@ -93,7 +92,7 @@ namespace WebAPI.Controllers
|
||||
Title = $"Unauthorized request - wrong apiKey ({number})",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return Unauthorized();
|
||||
}
|
||||
@@ -108,7 +107,7 @@ namespace WebAPI.Controllers
|
||||
Title = $"Unauthorized request - no authorization header ({number})",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return Unauthorized();
|
||||
}
|
||||
@@ -121,7 +120,7 @@ namespace WebAPI.Controllers
|
||||
Title = $"Unauthorized request - wrong auth header format ({number})",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return Unauthorized();
|
||||
}
|
||||
@@ -136,7 +135,7 @@ namespace WebAPI.Controllers
|
||||
Title = $"Unauthorized request - bad credentials ({number})",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return Unauthorized();
|
||||
}
|
||||
@@ -146,7 +145,7 @@ namespace WebAPI.Controllers
|
||||
Title = $"Sending data for layer {number}",
|
||||
Type = LogEntryType.info,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
return Ok(_db.Layers
|
||||
@@ -160,14 +159,14 @@ namespace WebAPI.Controllers
|
||||
Title = e.ToString(),
|
||||
Type = LogEntryType.error,
|
||||
LogType = LogType.powerBI,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return BadRequest(e.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("exportToGoogleSheet/{id}")]
|
||||
[Route("exportToGoogleSheet/{id:guid}")]
|
||||
public IActionResult ExportToGoogleSheet(Guid id)
|
||||
{
|
||||
if (_googleSheetValues is null)
|
||||
@@ -178,8 +177,8 @@ namespace WebAPI.Controllers
|
||||
var layer = _db.Layers
|
||||
.Include(x => x.Records!.OrderByDescending(y => y.Code)).First(x => x.Id == id && !x.IsDeleted);
|
||||
|
||||
var export = new googleSheetExport(_googleDriveHelper, _googleSheetValues, _configuration);
|
||||
export.export(layer);
|
||||
var export = new GoogleSheetExport(_googleDriveHelper, _googleSheetValues, _configuration);
|
||||
export.Export(layer);
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
@@ -216,7 +215,7 @@ namespace WebAPI.Controllers
|
||||
Title = "No Layers to import.",
|
||||
Type = LogEntryType.info,
|
||||
LogType = LogType.import,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
return Ok();
|
||||
}
|
||||
@@ -231,7 +230,7 @@ namespace WebAPI.Controllers
|
||||
if (type == "FK2")
|
||||
{
|
||||
var importer = new MorskaFk2Importer(_db, _googleSheetValues, this);
|
||||
importer.import(importWorker);
|
||||
importer.Import(importWorker);
|
||||
|
||||
_logsController.AddEntry(new LogEntry
|
||||
{
|
||||
@@ -262,7 +261,7 @@ namespace WebAPI.Controllers
|
||||
endDateParsed.Date >= DateTime.UtcNow.Date)
|
||||
{
|
||||
var importer = new MorskaImporter(_db, _googleSheetValues, this);
|
||||
importer.import(importWorker);
|
||||
importer.Import(importWorker);
|
||||
Thread.Sleep(5000); // be aware of GSheet API quota
|
||||
|
||||
_logsController.AddEntry(new LogEntry
|
||||
@@ -276,8 +275,8 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
else if (IsImportedLayerUpToDate(importWorker) == false)
|
||||
{
|
||||
MorskaImporter importer = new MorskaImporter(_db, _googleSheetValues, this);
|
||||
importer.import(importWorker);
|
||||
var importer = new MorskaImporter(_db, _googleSheetValues, this);
|
||||
importer.Import(importWorker);
|
||||
Thread.Sleep(5000); // be aware of GSheet API quota
|
||||
|
||||
_logsController.AddEntry(new LogEntry
|
||||
@@ -357,7 +356,7 @@ namespace WebAPI.Controllers
|
||||
"T4-R2"
|
||||
};
|
||||
|
||||
foreach (string type in processTypes)
|
||||
foreach (var type in processTypes)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -366,10 +365,10 @@ namespace WebAPI.Controllers
|
||||
Title = $"Processing: {type}",
|
||||
Type = LogEntryType.info,
|
||||
LogType = LogType.process,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
List<Layer> processWorkerLayers = _db.Layers
|
||||
var processWorkerLayers = _db.Layers
|
||||
.Include(x => x.Records)
|
||||
.Where(x =>
|
||||
x.Records!.Any(y => y.Code == "Type" && y.Desc1 == "ProcessWorker") &&
|
||||
@@ -386,11 +385,11 @@ namespace WebAPI.Controllers
|
||||
Title = "No Layers to process.",
|
||||
Type = LogEntryType.info,
|
||||
LogType = LogType.process,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
}
|
||||
|
||||
foreach (Layer processWorker in processWorkerLayers)
|
||||
foreach (var processWorker in processWorkerLayers)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -445,7 +444,7 @@ namespace WebAPI.Controllers
|
||||
throw new Exception("ProcessType record not found");
|
||||
case "T3-SourceYearSummary":
|
||||
{
|
||||
T3SourceYearSummaryProcessor processor =
|
||||
var processor =
|
||||
new T3SourceYearSummaryProcessor(_db, _googleSheetValues, this);
|
||||
processor.process(processWorker);
|
||||
|
||||
@@ -461,7 +460,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
case "T3-MultiSourceYearSummary":
|
||||
{
|
||||
T3MultiSourceYearSummaryProcessor processor =
|
||||
var processor =
|
||||
new T3MultiSourceYearSummaryProcessor(_db, _googleSheetValues, this, _logsController);
|
||||
processor.process(processWorker);
|
||||
|
||||
@@ -477,7 +476,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
case "T3-MultiSourceCopySelectedCodesYearSummary":
|
||||
{
|
||||
T3MultiSourceCopySelectedCodesYearSummaryProcessor processor =
|
||||
var processor =
|
||||
new T3MultiSourceCopySelectedCodesYearSummaryProcessor(_db, _googleSheetValues, this);
|
||||
processor.process(processWorker);
|
||||
|
||||
@@ -493,7 +492,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
case "T1-R1":
|
||||
{
|
||||
T1R1Processor processor = new T1R1Processor(_db, _googleSheetValues, this, _logsController);
|
||||
var processor = new T1R1Processor(_db, _googleSheetValues, this, _logsController);
|
||||
processor.process(processWorker);
|
||||
|
||||
_logsController.AddEntry(new LogEntry
|
||||
@@ -509,7 +508,7 @@ namespace WebAPI.Controllers
|
||||
case "T4-R2":
|
||||
{
|
||||
var processor = new T4R2Processor(_db, _googleSheetValues, this, _logsController);
|
||||
processor.process(processWorker);
|
||||
processor.Process(processWorker);
|
||||
|
||||
_logsController.AddEntry(new LogEntry
|
||||
{
|
||||
@@ -532,29 +531,29 @@ namespace WebAPI.Controllers
|
||||
switch (processType!)
|
||||
{
|
||||
case "T3-SingleSource":
|
||||
var t3SingleSource = new T3SingleSourceProcessor(_db, _googleSheetValues, this);
|
||||
{
|
||||
T3SingleSourceProcessor processor = new T3SingleSourceProcessor(_db, _googleSheetValues, this);
|
||||
processor.process(processWorker);
|
||||
t3SingleSource.process(processWorker);
|
||||
break;
|
||||
}
|
||||
case "T4-SingleSource":
|
||||
{
|
||||
T4SingleSourceProcessor processor = new T4SingleSourceProcessor(_db, _googleSheetValues, this);
|
||||
processor.process(processWorker);
|
||||
var t4SingleSource = new T4SingleSourceProcessor(_db, _googleSheetValues, this);
|
||||
t4SingleSource.process(processWorker);
|
||||
break;
|
||||
}
|
||||
case "T3-MultiSourceSummary":
|
||||
{
|
||||
T3MultiSourceSummaryProcessor processor =
|
||||
var t3MultiSourceSummary =
|
||||
new T3MultiSourceSummaryProcessor(_db, _googleSheetValues, this, _logsController);
|
||||
processor.process(processWorker);
|
||||
t3MultiSourceSummary.process(processWorker);
|
||||
break;
|
||||
}
|
||||
case "T3-MultiSourceCopySelectedCodes":
|
||||
{
|
||||
T3MultiSourceCopySelectedCodesProcessor processor =
|
||||
var t3MultiSourceCopySelectedCode =
|
||||
new T3MultiSourceCopySelectedCodesProcessor(_db, _googleSheetValues, this);
|
||||
processor.process(processWorker);
|
||||
t3MultiSourceCopySelectedCode.process(processWorker);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -571,13 +570,13 @@ namespace WebAPI.Controllers
|
||||
|
||||
internal void SaveRecords(Guid id, ICollection<Record> records, Guid currentUserId)
|
||||
{
|
||||
List<Record> toDelete = _db.Records.Where(x => x.LayerId == id).ToList();
|
||||
var toDelete = _db.Records.Where(x => x.LayerId == id).ToList();
|
||||
if (toDelete.Count > 0)
|
||||
{
|
||||
_db.Records.RemoveRange(toDelete);
|
||||
}
|
||||
|
||||
foreach (Record record in records)
|
||||
foreach (var record in records)
|
||||
{
|
||||
record.CreatedById = currentUserId;
|
||||
record.CreatedAt = DateTime.UtcNow;
|
||||
@@ -588,7 +587,7 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteToConsole(params string[] messages)
|
||||
private static void WriteToConsole(params string[] messages)
|
||||
{
|
||||
foreach (var message in messages)
|
||||
{
|
||||
@@ -648,9 +647,9 @@ namespace WebAPI.Controllers
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((!double.TryParse(data[1][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"),
|
||||
if (!double.TryParse(data[1][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"),
|
||||
out var value) ||
|
||||
double.Abs((double)(record.Value1-value)!) > 0.01)) continue;
|
||||
double.Abs((double)(record.Value1-value)!) > 0.01) continue;
|
||||
WriteToConsole(
|
||||
$"Code: {data[0][i]}. DiunaBI: {record.Value1:N2}. GoogleSheet: {data[1][i]}");
|
||||
isUpToDate = false;
|
||||
@@ -667,5 +666,4 @@ namespace WebAPI.Controllers
|
||||
}
|
||||
return isUpToDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,60 +2,47 @@ using System.Globalization;
|
||||
using Google.Apis.Sheets.v4;
|
||||
using Google.Apis.Sheets.v4.Data;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
namespace WebAPI.Controllers;
|
||||
|
||||
public class LogsController : Controller
|
||||
{
|
||||
public class LogsController : Controller
|
||||
{
|
||||
private SpreadsheetsResource.ValuesResource? googleSheetValues;
|
||||
private GoogleDriveHelper googleDriveHelper;
|
||||
private readonly IConfiguration configuration;
|
||||
private readonly SpreadsheetsResource.ValuesResource? _googleSheetValues;
|
||||
private readonly IConfiguration _configuration;
|
||||
public LogsController(
|
||||
GoogleSheetsHelper _googleSheetsHelper,
|
||||
GoogleDriveHelper _googleDriveHelper,
|
||||
IConfiguration _configuration)
|
||||
GoogleSheetsHelper googleSheetsHelper,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
if (_googleSheetsHelper.Service is not null) {
|
||||
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
|
||||
if (googleSheetsHelper.Service is not null) {
|
||||
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
|
||||
}
|
||||
googleDriveHelper = _googleDriveHelper;
|
||||
configuration = _configuration;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public void AddEntry(LogEntry entry)
|
||||
{
|
||||
if (googleSheetValues is null) {
|
||||
if (_googleSheetValues is null) {
|
||||
throw new Exception("Google Sheets API not initialized");
|
||||
}
|
||||
String type;
|
||||
switch (entry.LogType) {
|
||||
case LogType.import:
|
||||
type = "Import";
|
||||
break;
|
||||
case LogType.backup:
|
||||
type = "Backup";
|
||||
break;
|
||||
case LogType.process:
|
||||
type = "Process";
|
||||
break;
|
||||
case LogType.powerBI:
|
||||
type = "PowerBIAccess";
|
||||
break;
|
||||
default:
|
||||
type = "Other"; // should never happen
|
||||
break;
|
||||
}
|
||||
var response = googleSheetValues.Get(configuration["appLogsFile"], $"{type}!A:A").Execute();
|
||||
|
||||
var type = entry.LogType switch
|
||||
{
|
||||
LogType.import => "Import",
|
||||
LogType.backup => "Backup",
|
||||
LogType.process => "Process",
|
||||
LogType.powerBI => "PowerBIAccess",
|
||||
_ => "Other"
|
||||
};
|
||||
var response = _googleSheetValues.Get(_configuration["appLogsFile"], $"{type}!A:A").Execute();
|
||||
var data = response.Values;
|
||||
int row = 1;
|
||||
var row = 1;
|
||||
if (data != null) {
|
||||
row = data.Count + 1;
|
||||
}
|
||||
var range = $"{type}!A{row}:D{row}";
|
||||
|
||||
List<object> logRow = new List<object>
|
||||
var logRow = new List<object>
|
||||
{
|
||||
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
|
||||
entry.Type.ToString(),
|
||||
@@ -63,11 +50,10 @@ namespace WebAPI.Controllers
|
||||
entry.Message!
|
||||
};
|
||||
|
||||
ValueRange valueRange = new ValueRange() { Values = new IList<object>[] { logRow }};
|
||||
var valueRange = new ValueRange { Values = new IList<object>[] { logRow }};
|
||||
|
||||
var updateRequest = googleSheetValues.Update(valueRange, configuration["appLogsFile"], range);
|
||||
var updateRequest = _googleSheetValues.Update(valueRange, _configuration["appLogsFile"], range);
|
||||
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
|
||||
updateRequest.Execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
namespace WebAPI.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class PingController : Controller
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class PingController : Controller
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
public PingController(
|
||||
IConfiguration configuration)
|
||||
@@ -22,5 +22,4 @@ namespace WebAPI.Controllers
|
||||
{
|
||||
return Ok(_configuration["PONG"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,47 @@
|
||||
using System.Globalization;
|
||||
using Google.Apis.Drive.v3.Data;
|
||||
using Google.Apis.Sheets.v4;
|
||||
using Google.Apis.Sheets.v4.Data;
|
||||
using WebAPI.Models;
|
||||
using static Google.Apis.Drive.v3.FilesResource;
|
||||
|
||||
namespace WebAPI.Exports
|
||||
namespace WebAPI.Exports;
|
||||
|
||||
public class GoogleSheetExport
|
||||
{
|
||||
public class googleSheetExport
|
||||
private readonly GoogleDriveHelper _googleDriveHelper;
|
||||
private readonly SpreadsheetsResource.ValuesResource _googleSheetValues;
|
||||
private readonly IConfiguration _configuration;
|
||||
public GoogleSheetExport(
|
||||
GoogleDriveHelper googleDriveHelper,
|
||||
SpreadsheetsResource.ValuesResource googleSheetValues,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
private GoogleDriveHelper googleDriveHelper;
|
||||
private SpreadsheetsResource.ValuesResource googleSheetValues;
|
||||
private readonly IConfiguration configuration;
|
||||
public googleSheetExport(
|
||||
GoogleDriveHelper _googleDriveHelper,
|
||||
SpreadsheetsResource.ValuesResource _googleSheetValues,
|
||||
IConfiguration _configuration)
|
||||
{
|
||||
googleDriveHelper = _googleDriveHelper;
|
||||
googleSheetValues = _googleSheetValues;
|
||||
configuration = _configuration;
|
||||
_googleDriveHelper = googleDriveHelper;
|
||||
_googleSheetValues = googleSheetValues;
|
||||
_configuration = configuration;
|
||||
}
|
||||
public void export(Layer layer)
|
||||
public void Export(Layer layer)
|
||||
{
|
||||
if (googleDriveHelper.Service is null)
|
||||
if (_googleDriveHelper.Service is null)
|
||||
{
|
||||
throw new Exception("Google Drive API not initialized");
|
||||
}
|
||||
try
|
||||
{
|
||||
|
||||
List<IList<object>> data = new List<IList<object>>() { new List<object>() { layer.Name! } };
|
||||
var data = new List<IList<object>> { new List<object> { layer.Name! } };
|
||||
|
||||
switch (layer.Type)
|
||||
{
|
||||
case LayerType.import:
|
||||
{
|
||||
data.Add(new List<object> { "Code", "Value1" });
|
||||
foreach (Record record in layer.Records!)
|
||||
{
|
||||
data.Add(new List<object> { record.Code!, record.Value1! });
|
||||
}
|
||||
data.AddRange(layer.Records!.Select(record => new List<object> { record.Code!, record.Value1! }));
|
||||
break;
|
||||
}
|
||||
case LayerType.administration:
|
||||
{
|
||||
data.Add(new List<object> { "Code", "Desc1"});
|
||||
foreach (Record record in layer.Records!)
|
||||
{
|
||||
data.Add(new List<object> { record.Code!, record.Desc1!});
|
||||
}
|
||||
data.AddRange(layer.Records!.Select(record => new List<object> { record.Code!, record.Desc1! }));
|
||||
break;
|
||||
}
|
||||
case LayerType.processed:
|
||||
@@ -61,32 +53,63 @@ namespace WebAPI.Exports
|
||||
"Value23", "Value24", "Value25", "Value26", "Value27", "Value28",
|
||||
"Value29", "Value30", "Value31", "Value32"});
|
||||
|
||||
foreach (Record record in layer.Records!)
|
||||
data.AddRange(layer.Records!.Select(record => new List<object>
|
||||
{
|
||||
data.Add(new List<object> { record.Code!, record.Value1!, record.Value2!, record.Value3!, record.Value4!,
|
||||
record.Value5!, record.Value6!, record.Value7!, record.Value8!, record.Value9!, record.Value10!,
|
||||
record.Value11!, record.Value12!, record.Value13!, record.Value14!, record.Value15!, record.Value16!,
|
||||
record.Value17!, record.Value18!, record.Value19!, record.Value20!, record.Value21!, record.Value22!,
|
||||
record.Value23!, record.Value24!, record.Value25!, record.Value26!, record.Value27!, record.Value28!,
|
||||
record.Value29!, record.Value30!, record.Value31!, record.Value32!});
|
||||
}
|
||||
record.Code!,
|
||||
record.Value1!,
|
||||
record.Value2!,
|
||||
record.Value3!,
|
||||
record.Value4!,
|
||||
record.Value5!,
|
||||
record.Value6!,
|
||||
record.Value7!,
|
||||
record.Value8!,
|
||||
record.Value9!,
|
||||
record.Value10!,
|
||||
record.Value11!,
|
||||
record.Value12!,
|
||||
record.Value13!,
|
||||
record.Value14!,
|
||||
record.Value15!,
|
||||
record.Value16!,
|
||||
record.Value17!,
|
||||
record.Value18!,
|
||||
record.Value19!,
|
||||
record.Value20!,
|
||||
record.Value21!,
|
||||
record.Value22!,
|
||||
record.Value23!,
|
||||
record.Value24!,
|
||||
record.Value25!,
|
||||
record.Value26!,
|
||||
record.Value27!,
|
||||
record.Value28!,
|
||||
record.Value29!,
|
||||
record.Value30!,
|
||||
record.Value31!,
|
||||
record.Value32!
|
||||
}));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Exception("Wrong LayerType");
|
||||
}
|
||||
|
||||
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
|
||||
body.Name = $"{DateTime.Now.ToString(new CultureInfo("pl-PL"))}";
|
||||
body.MimeType = "application/vnd.google-apps.spreadsheet";
|
||||
body.Parents = new List<string?> { configuration["exportDirectory"] };
|
||||
CreateRequest request = googleDriveHelper.Service.Files.Create(body);
|
||||
var body = new Google.Apis.Drive.v3.Data.File
|
||||
{
|
||||
Name = $"{DateTime.Now.ToString(new CultureInfo("pl-PL"))}",
|
||||
MimeType = "application/vnd.google-apps.spreadsheet",
|
||||
Parents = new List<string?> { _configuration["exportDirectory"] }
|
||||
};
|
||||
var request = _googleDriveHelper.Service.Files.Create(body);
|
||||
var file = request.Execute();
|
||||
|
||||
string sheetId = file.Id;
|
||||
var sheetId = file.Id;
|
||||
var range = $"Sheet1!A1:AG${data.Count}";
|
||||
|
||||
ValueRange valueRange = new ValueRange() { Values = data};
|
||||
var valueRange = new ValueRange { Values = data};
|
||||
|
||||
var updateRequest = googleSheetValues.Update(valueRange, sheetId, range);
|
||||
var updateRequest = _googleSheetValues.Update(valueRange, sheetId, range);
|
||||
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
|
||||
updateRequest.Execute();
|
||||
|
||||
@@ -95,5 +118,4 @@ namespace WebAPI.Exports
|
||||
Console.WriteLine(e.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace WebAPI;
|
||||
|
||||
public class GoogleDriveHelper
|
||||
{
|
||||
public DriveService? Service { get; set; }
|
||||
public DriveService? Service { get; private set; }
|
||||
private const string ApplicationName = "Diuna";
|
||||
private static readonly string[] Scopes = { DriveService.Scope.Drive };
|
||||
public GoogleDriveHelper()
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WebAPI.Models
|
||||
namespace WebAPI.Models;
|
||||
|
||||
public class Record
|
||||
{
|
||||
public class Record
|
||||
{
|
||||
#region Properties
|
||||
[Key]
|
||||
public Guid Id { get; set; }
|
||||
[Required]
|
||||
[StringLength(50)]
|
||||
public string? Code { get; set; }
|
||||
public double? Value1 { get; set; }
|
||||
public double? Value2 { get; set; }
|
||||
@@ -42,23 +43,28 @@ namespace WebAPI.Models
|
||||
public double? Value31 { get; set; }
|
||||
public double? Value32 { get; set; }
|
||||
//Description fields
|
||||
[StringLength(50)]
|
||||
public string? Desc1 { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Desc2 { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Desc3 { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Desc4 { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Desc5 { get; set; }
|
||||
[StringLength(50)]
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime ModifiedAt { get; set; }
|
||||
public bool IsDeleted { get; set; }
|
||||
public bool IsDeleted { get; init; }
|
||||
#endregion
|
||||
#region Relations
|
||||
[Required]
|
||||
public Guid CreatedById { get; set; }
|
||||
public User? CreatedBy { get; set; }
|
||||
public User? CreatedBy { get; init; }
|
||||
[Required]
|
||||
public Guid ModifiedById { get; set; }
|
||||
public User? ModifiedBy { get; set; }
|
||||
public User? ModifiedBy { get; init; }
|
||||
public Guid LayerId { get; set; }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WebAPI.Models
|
||||
namespace WebAPI.Models;
|
||||
|
||||
public class User
|
||||
{
|
||||
public class User
|
||||
{
|
||||
#region Properties
|
||||
[Key]
|
||||
public Guid Id { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public Guid Id { get; init; }
|
||||
[StringLength(50)]
|
||||
public string? UserName { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public string? Email { get; init; }
|
||||
[StringLength(50)]
|
||||
public string? UserName { get; init; }
|
||||
public DateTime CreatedAt { get; init; }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,88 +1,87 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Globalization;
|
||||
using Google.Apis.Sheets.v4;
|
||||
using WebAPI;
|
||||
using WebAPI.Controllers;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace DiunaBIWebAPI.dataImporters
|
||||
namespace DiunaBIWebAPI.dataImporters;
|
||||
|
||||
public class MorskaFk2Importer
|
||||
{
|
||||
public class MorskaFk2Importer
|
||||
{
|
||||
private readonly AppDbContext db;
|
||||
private readonly SpreadsheetsResource.ValuesResource googleSheetValues;
|
||||
private readonly LayersController controller;
|
||||
private readonly AppDbContext _db;
|
||||
private readonly SpreadsheetsResource.ValuesResource _googleSheetValues;
|
||||
private readonly LayersController _controller;
|
||||
|
||||
public MorskaFk2Importer(
|
||||
AppDbContext _db,
|
||||
SpreadsheetsResource.ValuesResource _googleSheetValues,
|
||||
LayersController _controller)
|
||||
AppDbContext db,
|
||||
SpreadsheetsResource.ValuesResource googleSheetValues,
|
||||
LayersController controller)
|
||||
{
|
||||
db = _db;
|
||||
googleSheetValues = _googleSheetValues;
|
||||
controller = _controller;
|
||||
_db = db;
|
||||
_googleSheetValues = googleSheetValues;
|
||||
_controller = controller;
|
||||
}
|
||||
|
||||
public void import(Layer importWorker)
|
||||
public void Import(Layer importWorker)
|
||||
{
|
||||
string? sheetId = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
|
||||
var sheetId = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetId")?.Desc1;
|
||||
if (sheetId == null)
|
||||
{
|
||||
throw new Exception($"SheetId not found, {importWorker.Name}");
|
||||
}
|
||||
string? sheetTabName = importWorker.Records!.Where(x => x.Code == "SheetTabName").FirstOrDefault()?.Desc1;
|
||||
var sheetTabName = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetTabName")?.Desc1;
|
||||
if (sheetTabName == null)
|
||||
{
|
||||
throw new Exception($"SheetTabName not found, {importWorker.Name}");
|
||||
}
|
||||
string? importYearCell = importWorker.Records!.Where(x => x.Code == "ImportYear").FirstOrDefault()?.Desc1;
|
||||
var importYearCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportYear")?.Desc1;
|
||||
if (importYearCell == null)
|
||||
{
|
||||
throw new Exception($"ImportYear not found, {importWorker.Name}");
|
||||
}
|
||||
string? importMonthCell = importWorker.Records!.Where(x => x.Code == "ImportMonth").FirstOrDefault()?.Desc1;
|
||||
var importMonthCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportMonth")?.Desc1;
|
||||
if (importMonthCell == null)
|
||||
{
|
||||
throw new Exception($"ImportMonth not found, {importWorker.Name}");
|
||||
}
|
||||
string? importNameCell = importWorker.Records!.Where(x => x.Code == "ImportName").FirstOrDefault()?.Desc1;
|
||||
var importNameCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportName")?.Desc1;
|
||||
if (importNameCell == null)
|
||||
{
|
||||
throw new Exception($"ImportName not found, {importWorker.Name}");
|
||||
}
|
||||
string? checkSumCell = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
|
||||
var checkSumCell = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetId")?.Desc1;
|
||||
if (checkSumCell == null)
|
||||
{
|
||||
throw new Exception($"SheetId not found, {importWorker.Name}");
|
||||
}
|
||||
string? dataRange = importWorker.Records!.Where(x => x.Code == "DataRange").FirstOrDefault()?.Desc1;
|
||||
var dataRange = importWorker.Records!.FirstOrDefault(x => x.Code == "DataRange")?.Desc1;
|
||||
if (dataRange == null)
|
||||
{
|
||||
throw new Exception($"DataRange not found, {importWorker.Name}");
|
||||
}
|
||||
|
||||
var nameResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{importNameCell}:{importNameCell}").Execute();
|
||||
string? name = nameResponse.Values?[0][0].ToString();
|
||||
var nameResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importNameCell}:{importNameCell}").Execute();
|
||||
var 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();
|
||||
var yearResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importYearCell}:{importYearCell}").Execute();
|
||||
var 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();
|
||||
var monthResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importMonthCell}:{importMonthCell}").Execute();
|
||||
var month = monthResponse.Values[0][0].ToString();
|
||||
if (month == null)
|
||||
{
|
||||
throw new Exception($"ImportMonth cell is empty, {importWorker.Name}");
|
||||
}
|
||||
Layer layer = new Layer
|
||||
var layer = new Layer
|
||||
{
|
||||
Source = "GoogleSheet",
|
||||
Number = db.Layers.Count() + 1,
|
||||
Number = _db.Layers.Count() + 1,
|
||||
ParentId = importWorker.Id,
|
||||
Type = LayerType.import,
|
||||
CreatedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"),
|
||||
@@ -92,29 +91,25 @@ namespace DiunaBIWebAPI.dataImporters
|
||||
};
|
||||
layer.Name = $"L{layer.Number}-I-{name}2-{year}/{month}-{DateTime.Now.ToString("yyyyMMddHHmm", CultureInfo.InvariantCulture)}";
|
||||
|
||||
List<Record> newRecords = new List<Record>();
|
||||
var newRecords = new List<Record>();
|
||||
|
||||
var dataRangeResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{dataRange}").Execute();
|
||||
var dataRangeResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{dataRange}").Execute();
|
||||
var data = dataRangeResponse.Values;
|
||||
for (int i = 0; i < data.Count; i++)
|
||||
for (var i = 0; i < data.Count; i++)
|
||||
{
|
||||
if (data[i].Count > 8 && (string)data[i][2] != String.Empty)
|
||||
{
|
||||
string[] dateArr = data[i][0].ToString()!.Split(".");
|
||||
if (data[i].Count <= 8 || (string)data[i][2] == string.Empty) continue;
|
||||
var dateArr = data[i][0].ToString()!.Split(".");
|
||||
if (dateArr.Length != 3)
|
||||
{
|
||||
throw new Exception($"Invalid date in row {i}");
|
||||
}
|
||||
|
||||
string number = data[i][1].ToString()!;
|
||||
var number = data[i][1].ToString()!;
|
||||
if (number.Length == 1) number = $"0{number}";
|
||||
string code = dateArr[2] + dateArr[1] + dateArr[0] + number;
|
||||
double value;
|
||||
if (
|
||||
data[i][8].ToString()?.Length > 0 &&
|
||||
double.TryParse(data[i][8].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out value))
|
||||
{
|
||||
Record record = new Record
|
||||
var code = dateArr[2] + dateArr[1] + dateArr[0] + number;
|
||||
if (!(data[i][8].ToString()?.Length > 0) ||
|
||||
!double.TryParse(data[i][8].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out var value)) continue;
|
||||
var record = new Record
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Code = code,
|
||||
@@ -124,13 +119,9 @@ namespace DiunaBIWebAPI.dataImporters
|
||||
ModifiedAt = DateTime.UtcNow
|
||||
};
|
||||
newRecords.Add(record);
|
||||
};
|
||||
}
|
||||
}
|
||||
db.Layers.Add(layer);
|
||||
controller.SaveRecords(layer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
db.SaveChanges();
|
||||
}
|
||||
_db.Layers.Add(layer);
|
||||
_controller.SaveRecords(layer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
_db.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,88 +1,87 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Globalization;
|
||||
using Google.Apis.Sheets.v4;
|
||||
using WebAPI;
|
||||
using WebAPI.Controllers;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace DiunaBIWebAPI.dataImporters
|
||||
namespace DiunaBIWebAPI.dataImporters;
|
||||
|
||||
public class MorskaImporter
|
||||
{
|
||||
public class MorskaImporter
|
||||
{
|
||||
private readonly AppDbContext db;
|
||||
private readonly SpreadsheetsResource.ValuesResource googleSheetValues;
|
||||
private readonly LayersController controller;
|
||||
private readonly AppDbContext _db;
|
||||
private readonly SpreadsheetsResource.ValuesResource _googleSheetValues;
|
||||
private readonly LayersController _controller;
|
||||
|
||||
public MorskaImporter(
|
||||
AppDbContext _db,
|
||||
SpreadsheetsResource.ValuesResource _googleSheetValues,
|
||||
LayersController _controller)
|
||||
AppDbContext db,
|
||||
SpreadsheetsResource.ValuesResource googleSheetValues,
|
||||
LayersController controller)
|
||||
{
|
||||
db = _db;
|
||||
googleSheetValues = _googleSheetValues;
|
||||
controller = _controller;
|
||||
_db = db;
|
||||
_googleSheetValues = googleSheetValues;
|
||||
_controller = controller;
|
||||
}
|
||||
|
||||
public void import(Layer importWorker)
|
||||
public void Import(Layer importWorker)
|
||||
{
|
||||
string? sheetId = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
|
||||
var sheetId = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetId")?.Desc1;
|
||||
if (sheetId == null)
|
||||
{
|
||||
throw new Exception($"SheetId not found, {importWorker.Name}");
|
||||
}
|
||||
string? sheetTabName = importWorker.Records!.Where(x => x.Code == "SheetTabName").FirstOrDefault()?.Desc1;
|
||||
var sheetTabName = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetTabName")?.Desc1;
|
||||
if (sheetTabName == null)
|
||||
{
|
||||
throw new Exception($"SheetTabName not found, {importWorker.Name}");
|
||||
}
|
||||
string? importYearCell = importWorker.Records!.Where(x => x.Code == "ImportYear").FirstOrDefault()?.Desc1;
|
||||
var importYearCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportYear")?.Desc1;
|
||||
if (importYearCell == null)
|
||||
{
|
||||
throw new Exception($"ImportYear not found, {importWorker.Name}");
|
||||
}
|
||||
string? importMonthCell = importWorker.Records!.Where(x => x.Code == "ImportMonth").FirstOrDefault()?.Desc1;
|
||||
var importMonthCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportMonth")?.Desc1;
|
||||
if (importMonthCell == null)
|
||||
{
|
||||
throw new Exception($"ImportMonth not found, {importWorker.Name}");
|
||||
}
|
||||
string? importNameCell = importWorker.Records!.Where(x => x.Code == "ImportName").FirstOrDefault()?.Desc1;
|
||||
var importNameCell = importWorker.Records!.FirstOrDefault(x => x.Code == "ImportName")?.Desc1;
|
||||
if (importNameCell == null)
|
||||
{
|
||||
throw new Exception($"ImportName not found, {importWorker.Name}");
|
||||
}
|
||||
string? checkSumCell = importWorker.Records!.Where(x => x.Code == "SheetId").FirstOrDefault()?.Desc1;
|
||||
var checkSumCell = importWorker.Records!.FirstOrDefault(x => x.Code == "SheetId")?.Desc1;
|
||||
if (checkSumCell == null)
|
||||
{
|
||||
throw new Exception($"SheetId not found, {importWorker.Name}");
|
||||
}
|
||||
string? dataRange = importWorker.Records!.Where(x => x.Code == "DataRange").FirstOrDefault()?.Desc1;
|
||||
var dataRange = importWorker.Records!.FirstOrDefault(x => x.Code == "DataRange")?.Desc1;
|
||||
if (dataRange == null)
|
||||
{
|
||||
throw new Exception($"DataRange not found, {importWorker.Name}");
|
||||
}
|
||||
|
||||
var nameResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{importNameCell}:{importNameCell}").Execute();
|
||||
string? name = nameResponse.Values?[0][0].ToString();
|
||||
var nameResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importNameCell}:{importNameCell}").Execute();
|
||||
var 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();
|
||||
var yearResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importYearCell}:{importYearCell}").Execute();
|
||||
var 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();
|
||||
var monthResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{importMonthCell}:{importMonthCell}").Execute();
|
||||
var month = monthResponse.Values[0][0].ToString();
|
||||
if (month == null)
|
||||
{
|
||||
throw new Exception($"ImportMonth cell is empty, {importWorker.Name}");
|
||||
}
|
||||
Layer layer = new Layer
|
||||
var layer = new Layer
|
||||
{
|
||||
Source = "GoogleSheet",
|
||||
Number = db.Layers.Count() + 1,
|
||||
Number = _db.Layers.Count() + 1,
|
||||
ParentId = importWorker.Id,
|
||||
Type = LayerType.import,
|
||||
CreatedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"),
|
||||
@@ -90,20 +89,17 @@ namespace DiunaBIWebAPI.dataImporters
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
ModifiedAt = DateTime.UtcNow
|
||||
};
|
||||
layer.Name = $"L{layer.Number}-I-{name}-{year}/{month}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
|
||||
layer.Name = $"L{layer.Number}-I-{name}-{year}/{month}-{DateTime.Now:yyyyMMddHHmm}";
|
||||
|
||||
List<Record> newRecords = new List<Record>();
|
||||
var newRecords = new List<Record>();
|
||||
|
||||
var dataRangeResponse = googleSheetValues.Get(sheetId, $"{sheetTabName}!{dataRange}").Execute();
|
||||
var dataRangeResponse = _googleSheetValues.Get(sheetId, $"{sheetTabName}!{dataRange}").Execute();
|
||||
var data = dataRangeResponse.Values;
|
||||
for (int i = 0; i < data[1].Count; i++)
|
||||
for (var i = 0; i < data[1].Count; i++)
|
||||
{
|
||||
double value;
|
||||
if (
|
||||
data[0][i].ToString()?.Length > 0 &&
|
||||
double.TryParse(data[1][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out value))
|
||||
{
|
||||
Record record = new Record
|
||||
if (!(data[0][i].ToString()?.Length > 0) ||
|
||||
!double.TryParse(data[1][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out var value)) continue;
|
||||
var record = new Record
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Code = data[0][i].ToString(),
|
||||
@@ -112,12 +108,9 @@ namespace DiunaBIWebAPI.dataImporters
|
||||
ModifiedAt = DateTime.UtcNow
|
||||
};
|
||||
newRecords.Add(record);
|
||||
};
|
||||
}
|
||||
db.Layers.Add(layer);
|
||||
controller.SaveRecords(layer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
db.SaveChanges();
|
||||
}
|
||||
_db.Layers.Add(layer);
|
||||
_controller.SaveRecords(layer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
_db.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
using CsvHelper;
|
||||
using CsvHelper.Configuration;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
||||
using System.Formats.Asn1;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.dataParsers
|
||||
{
|
||||
public class csvParser
|
||||
{
|
||||
public List<Record> parse(IFormFile file)
|
||||
{
|
||||
var info = CultureInfo.CurrentCulture;
|
||||
|
||||
List<Record> records = new List<Record>();
|
||||
|
||||
var stream = new StreamReader(file.OpenReadStream());
|
||||
string content = stream.ReadToEnd();
|
||||
|
||||
List<string> lines = content.Split("\n").ToList();
|
||||
List<List<string>> data = new List<List<string>>();
|
||||
foreach (string line in lines)
|
||||
{
|
||||
data.Add(line.Split(";").ToList());
|
||||
}
|
||||
|
||||
for (int i = 1; i < data[0].Count; i++)
|
||||
{
|
||||
for (int j = 1; j < data.Count; j++) {
|
||||
if (data[j][0].Length > 0)
|
||||
{
|
||||
double value = double.Parse(data[j][i], CultureInfo.GetCultureInfo("pl-PL"));
|
||||
if (value > 0)
|
||||
{
|
||||
Record record = new Record();
|
||||
record.Id = Guid.NewGuid();
|
||||
record.Code = data[0][i];
|
||||
record.Desc1 = data[j][0];
|
||||
record.Value1 = value;
|
||||
record.CreatedAt = DateTime.UtcNow;
|
||||
record.ModifiedAt= DateTime.UtcNow;
|
||||
records.Add(record);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
using Google.Apis.Sheets.v4;
|
||||
using System.Globalization;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.dataParsers
|
||||
{
|
||||
public class morskaK5Parser
|
||||
{
|
||||
private SpreadsheetsResource.ValuesResource googleSheetValues;
|
||||
private AppDbContext db;
|
||||
|
||||
public morskaK5Parser(
|
||||
SpreadsheetsResource.ValuesResource _googleSheetValues,
|
||||
AppDbContext _db)
|
||||
{
|
||||
googleSheetValues = _googleSheetValues;
|
||||
db = _db;
|
||||
}
|
||||
|
||||
public Layer parse()
|
||||
{
|
||||
Layer layer = new Layer();
|
||||
layer.Source = "GoogleSheet";
|
||||
|
||||
string sheetId = "1ZzndU8HjYqz5VKCcrVHBOFW8fqpYfwquclznX9q39Yk";
|
||||
|
||||
var range = "Sierpien_2023!B3:AR5";
|
||||
|
||||
var request = googleSheetValues.Get(sheetId, range);
|
||||
var response = request.Execute();
|
||||
var data = response.Values;
|
||||
|
||||
layer.Source = "GoogleSheet";
|
||||
layer.Number = db.Layers.Count() + 1;
|
||||
layer.Name = $"L{layer.Number}-I-{data[0][1]}-{data[0][2]}/{data[0][3]}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
|
||||
layer.Type = LayerType.import;
|
||||
|
||||
List<Record> records = new List<Record>();
|
||||
|
||||
for (int i = 1; i < data[1].Count; i++)
|
||||
{
|
||||
double value;
|
||||
|
||||
if (
|
||||
data[1][i].ToString()?.Length > 0 &&
|
||||
double.TryParse(data[2][i].ToString(), CultureInfo.GetCultureInfo("pl-PL"), out value))
|
||||
{
|
||||
Record record = new Record();
|
||||
record.Id = Guid.NewGuid();
|
||||
record.Code = data[1][i].ToString();
|
||||
record.Value1 = value;
|
||||
record.CreatedAt = DateTime.UtcNow;
|
||||
record.ModifiedAt = DateTime.UtcNow;
|
||||
records.Add(record);
|
||||
};
|
||||
|
||||
}
|
||||
layer.Records = records;
|
||||
return layer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using WebAPI.Models;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace DiunaBIWebAPI.dataProcessors
|
||||
namespace DiunaBIWebAPI.dataProcessors;
|
||||
|
||||
public static class ProcessHelper
|
||||
{
|
||||
public static class ProcessHelper
|
||||
{
|
||||
public static void setValue(Record record, int number, double? value)
|
||||
public static void SetValue(Record record, int number, double? value)
|
||||
{
|
||||
value = (double)Math.Round((decimal)(value ?? 0), 2);
|
||||
switch (number)
|
||||
@@ -110,100 +109,67 @@ namespace DiunaBIWebAPI.dataProcessors
|
||||
}
|
||||
public static double? getValue(Record record, int number)
|
||||
{
|
||||
switch (number)
|
||||
return number switch
|
||||
{
|
||||
1 => record.Value1,
|
||||
2 => record.Value2,
|
||||
3 => record.Value3,
|
||||
4 => record.Value4,
|
||||
5 => record.Value5,
|
||||
6 => record.Value6,
|
||||
7 => record.Value7,
|
||||
8 => record.Value8,
|
||||
9 => record.Value9,
|
||||
10 => record.Value10,
|
||||
11 => record.Value11,
|
||||
12 => record.Value12,
|
||||
13 => record.Value13,
|
||||
14 => record.Value14,
|
||||
15 => record.Value15,
|
||||
16 => record.Value16,
|
||||
17 => record.Value17,
|
||||
18 => record.Value18,
|
||||
19 => record.Value19,
|
||||
20 => record.Value20,
|
||||
21 => record.Value21,
|
||||
22 => record.Value22,
|
||||
23 => record.Value23,
|
||||
24 => record.Value24,
|
||||
25 => record.Value25,
|
||||
26 => record.Value26,
|
||||
27 => record.Value27,
|
||||
28 => record.Value28,
|
||||
29 => record.Value29,
|
||||
30 => record.Value30,
|
||||
31 => record.Value31,
|
||||
32 => record.Value32,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
public static List<int> ParseCodes(string codes)
|
||||
{
|
||||
var codesList = new List<int>();
|
||||
foreach (var code in codes.Split(';'))
|
||||
{
|
||||
var range = code.Split('-');
|
||||
switch (range.Length)
|
||||
{
|
||||
case 1:
|
||||
return record.Value1;
|
||||
case 2:
|
||||
return record.Value2;
|
||||
case 3:
|
||||
return record.Value3;
|
||||
case 4:
|
||||
return record.Value4;
|
||||
case 5:
|
||||
return record.Value5;
|
||||
case 6:
|
||||
return record.Value6;
|
||||
case 7:
|
||||
return record.Value7;
|
||||
case 8:
|
||||
return record.Value8;
|
||||
case 9:
|
||||
return record.Value9;
|
||||
case 10:
|
||||
return record.Value10;
|
||||
case 11:
|
||||
return record.Value11;
|
||||
case 12:
|
||||
return record.Value12;
|
||||
case 13:
|
||||
return record.Value13;
|
||||
case 14:
|
||||
return record.Value14;
|
||||
case 15:
|
||||
return record.Value15;
|
||||
case 16:
|
||||
return record.Value16;
|
||||
case 17:
|
||||
return record.Value17;
|
||||
case 18:
|
||||
return record.Value18;
|
||||
case 19:
|
||||
return record.Value19;
|
||||
case 20:
|
||||
return record.Value20;
|
||||
case 21:
|
||||
return record.Value21;
|
||||
case 22:
|
||||
return record.Value22;
|
||||
case 23:
|
||||
return record.Value23;
|
||||
case 24:
|
||||
return record.Value24;
|
||||
case 25:
|
||||
return record.Value25;
|
||||
case 26:
|
||||
return record.Value26;
|
||||
case 27:
|
||||
return record.Value27;
|
||||
case 28:
|
||||
return record.Value28;
|
||||
case 29:
|
||||
return record.Value29;
|
||||
case 30:
|
||||
return record.Value30;
|
||||
case 31:
|
||||
return record.Value31;
|
||||
case 32:
|
||||
return record.Value32;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static List<int> parseCodes(string codes)
|
||||
{
|
||||
List<int> codesList = new List<int>();
|
||||
foreach (string code in codes.Split(';'))
|
||||
{
|
||||
string[] range = code.Split('-');
|
||||
if (range.Length == 1)
|
||||
{
|
||||
codesList.Add(int.Parse(range[0]));
|
||||
}
|
||||
else if (range.Length == 2)
|
||||
break;
|
||||
case 2:
|
||||
{
|
||||
for (int i = int.Parse(range[0]); i <= int.Parse(range[1]); i++)
|
||||
{
|
||||
codesList.Add(i);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
default:
|
||||
throw new Exception($"Invalid code range: {code}");
|
||||
}
|
||||
}
|
||||
return codesList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace WebAPI.dataProcessors
|
||||
{
|
||||
throw new Exception("Codes record not found");
|
||||
}
|
||||
List<int> codesList = ProcessHelper.parseCodes(codes);
|
||||
List<int> codesList = ProcessHelper.ParseCodes(codes);
|
||||
|
||||
Layer? processedLayer = db.Layers
|
||||
.Where(x => x.ParentId == processWorker!.Id
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace WebAPI.dataProcessors
|
||||
throw new Exception("Codes record not found");
|
||||
}
|
||||
// create array of integers from string codes where: '501-503;505-505;510-512' -> [501,502,503,505,510,511,512]
|
||||
List<int> codesList = ProcessHelper.parseCodes(codes);
|
||||
List<int> codesList = ProcessHelper.ParseCodes(codes);
|
||||
|
||||
Layer? processedLayer = db.Layers
|
||||
.Where(x => x.ParentId == processWorker!.Id
|
||||
@@ -103,7 +103,7 @@ namespace WebAPI.dataProcessors
|
||||
};
|
||||
for (var i = 1; i < 33; i++)
|
||||
{
|
||||
ProcessHelper.setValue(newRecord, i, ProcessHelper.getValue(x, i));
|
||||
ProcessHelper.SetValue(newRecord, i, ProcessHelper.getValue(x, i));
|
||||
}
|
||||
return newRecord;
|
||||
})
|
||||
|
||||
@@ -93,7 +93,7 @@ namespace WebAPI.dataProcessors
|
||||
};
|
||||
for (var i = 1; i < 33; i++)
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, i,
|
||||
ProcessHelper.SetValue(processedRecord, i,
|
||||
codeRecords.Sum(x => ProcessHelper.getValue(x, i)));
|
||||
}
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ namespace WebAPI.dataProcessors
|
||||
};
|
||||
for (var i = 1; i<33; i++)
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, i,
|
||||
ProcessHelper.SetValue(processedRecord, i,
|
||||
codeRecords.Sum(x => ProcessHelper.getValue(x, i)));
|
||||
}
|
||||
newRecords.Add(processedRecord);
|
||||
|
||||
@@ -128,10 +128,10 @@ namespace WebAPI.dataProcessors
|
||||
Record validationRecord = new Record();
|
||||
for (var i = 1; i < 33; i++)
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, i,
|
||||
ProcessHelper.SetValue(processedRecord, i,
|
||||
codeRecords.Sum(x => ProcessHelper.getValue(x, i)));
|
||||
|
||||
ProcessHelper.setValue(validationRecord, i,
|
||||
ProcessHelper.SetValue(validationRecord, i,
|
||||
codeRecordsValidation.Sum(x => ProcessHelper.getValue(x, i)));
|
||||
|
||||
if (
|
||||
|
||||
@@ -108,7 +108,7 @@ namespace WebAPI.dataProcessors
|
||||
.Where(x => x.CreatedAt.Date <= new DateTime(year, month, 1))
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.FirstOrDefault()?.Value1 ?? 0;
|
||||
ProcessHelper.setValue(processedRecord, 1, firstVal);
|
||||
ProcessHelper.SetValue(processedRecord, 1, firstVal);
|
||||
previousValue = firstVal;
|
||||
//days 2-29/30
|
||||
for (int i=2; i<lastDayInMonth; i++)
|
||||
@@ -120,11 +120,11 @@ namespace WebAPI.dataProcessors
|
||||
if (dayVal == null)
|
||||
{
|
||||
//TODO: missing day value? Should I log it?
|
||||
ProcessHelper.setValue(processedRecord, i, 0);
|
||||
ProcessHelper.SetValue(processedRecord, i, 0);
|
||||
} else
|
||||
{
|
||||
double processedVal = (dayVal ?? 0) - previousValue;
|
||||
ProcessHelper.setValue(processedRecord, i, processedVal);
|
||||
ProcessHelper.SetValue(processedRecord, i, processedVal);
|
||||
previousValue = dayVal ?? 0;
|
||||
}
|
||||
}
|
||||
@@ -136,17 +136,17 @@ namespace WebAPI.dataProcessors
|
||||
|
||||
if (lastVal == null)
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, lastDayInMonth, 0);
|
||||
ProcessHelper.SetValue(processedRecord, lastDayInMonth, 0);
|
||||
} else
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, lastDayInMonth, (lastVal ?? 0) - previousValue);
|
||||
ProcessHelper.SetValue(processedRecord, lastDayInMonth, (lastVal ?? 0) - previousValue);
|
||||
}
|
||||
|
||||
// copy last value
|
||||
double? valueToCopy = codeRecords
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.FirstOrDefault()?.Value1;
|
||||
ProcessHelper.setValue(processedRecord, 32, valueToCopy);
|
||||
ProcessHelper.SetValue(processedRecord, 32, valueToCopy);
|
||||
|
||||
newRecords.Add(processedRecord);
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ namespace WebAPI.dataProcessors
|
||||
};
|
||||
for (var i = 1; i < 33; i++)
|
||||
{
|
||||
ProcessHelper.setValue(processedRecord, i,
|
||||
ProcessHelper.SetValue(processedRecord, i,
|
||||
codeRecords.Sum(x => ProcessHelper.getValue(x, i)));
|
||||
}
|
||||
newRecords.Add(processedRecord);
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
using System.Globalization;
|
||||
using DiunaBIWebAPI.dataProcessors;
|
||||
using DiunaBIWebAPI.dataProcessors;
|
||||
using Google.Apis.Sheets.v4;
|
||||
using Google.Apis.Sheets.v4.Data;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WebAPI.Controllers;
|
||||
using WebAPI.Models;
|
||||
@@ -12,46 +9,44 @@ namespace WebAPI.dataProcessors
|
||||
{
|
||||
public class T4R2Processor
|
||||
{
|
||||
private readonly AppDbContext db;
|
||||
private readonly SpreadsheetsResource.ValuesResource googleSheetValues;
|
||||
private readonly LayersController controller;
|
||||
private readonly LogsController logsController;
|
||||
private readonly AppDbContext _db;
|
||||
private readonly LayersController _controller;
|
||||
private readonly LogsController _logsController;
|
||||
|
||||
public T4R2Processor(
|
||||
AppDbContext _db,
|
||||
SpreadsheetsResource.ValuesResource _googleSheetValues,
|
||||
LayersController _controller,
|
||||
LogsController _logsController)
|
||||
AppDbContext db,
|
||||
SpreadsheetsResource.ValuesResource googleSheetValues,
|
||||
LayersController controller,
|
||||
LogsController logsController)
|
||||
{
|
||||
db = _db;
|
||||
googleSheetValues = _googleSheetValues;
|
||||
controller = _controller;
|
||||
logsController = _logsController;
|
||||
_db = db;
|
||||
_controller = controller;
|
||||
_logsController = logsController;
|
||||
}
|
||||
|
||||
public void process(Layer processWorker)
|
||||
public void Process(Layer processWorker)
|
||||
{
|
||||
int year = int.Parse(processWorker!.Records?.SingleOrDefault(x => x.Code == "Year")?.Desc1!);
|
||||
List<Record>? sources = processWorker.Records?.Where(x => x.Code == "Source").ToList();
|
||||
if (sources!.Count() == 0)
|
||||
var year = int.Parse(processWorker.Records?.SingleOrDefault(x => x.Code == "Year")?.Desc1!);
|
||||
var sources = processWorker.Records?.Where(x => x.Code == "Source").ToList();
|
||||
if (!sources!.Any())
|
||||
{
|
||||
throw new Exception("Source record not found");
|
||||
}
|
||||
|
||||
string? layerName = processWorker.Records?.SingleOrDefault(x => x.Code == "LayerName")?.Desc1;
|
||||
var layerName = processWorker.Records?.SingleOrDefault(x => x.Code == "LayerName")?.Desc1;
|
||||
if (layerName == null)
|
||||
{
|
||||
throw new Exception("LayerName record not found");
|
||||
}
|
||||
|
||||
|
||||
Layer? processedLayer = db.Layers
|
||||
.Where(x => x.ParentId == processWorker!.Id
|
||||
var processedLayer = _db.Layers
|
||||
.Where(x => x.ParentId == processWorker.Id
|
||||
&& !x.IsDeleted)
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.FirstOrDefault();
|
||||
|
||||
bool isNew = false;
|
||||
var isNew = false;
|
||||
if (processedLayer == null)
|
||||
{
|
||||
isNew = true;
|
||||
@@ -60,8 +55,8 @@ namespace WebAPI.dataProcessors
|
||||
Id = Guid.NewGuid(),
|
||||
Source = "",
|
||||
Type = LayerType.processed,
|
||||
ParentId = processWorker!.Id,
|
||||
Number = db.Layers.Count() + 1,
|
||||
ParentId = processWorker.Id,
|
||||
Number = _db.Layers.Count() + 1
|
||||
};
|
||||
processedLayer.Name = $"L{processedLayer.Number}-{layerName}";
|
||||
processedLayer.CreatedById = Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D");
|
||||
@@ -75,42 +70,35 @@ namespace WebAPI.dataProcessors
|
||||
processedLayer.ModifiedAt = DateTime.UtcNow;
|
||||
|
||||
|
||||
List<Record> newRecords = new List<Record>();
|
||||
var newRecords = new List<Record>();
|
||||
|
||||
foreach (Record source in sources!)
|
||||
foreach (var source in sources!)
|
||||
{
|
||||
string? rawSourceCodes = processWorker.Records?.SingleOrDefault(x => x.Code == $"Codes-{source.Desc1}")
|
||||
var rawSourceCodes = processWorker.Records?.SingleOrDefault(x => x.Code == $"Codes-{source.Desc1}")
|
||||
?.Desc1;
|
||||
List<int> sourceCodes = new List<int>();
|
||||
var sourceCodes = new List<int>();
|
||||
if (rawSourceCodes != null)
|
||||
{
|
||||
sourceCodes = ProcessHelper.parseCodes(rawSourceCodes);
|
||||
sourceCodes = ProcessHelper.ParseCodes(rawSourceCodes);
|
||||
}
|
||||
|
||||
for (int month = 1; month <= DateTime.UtcNow.Month; month++)
|
||||
for (var month = 1; month <= DateTime.UtcNow.Month; month++)
|
||||
{
|
||||
Layer? dataSource = db.Layers.Where(x =>
|
||||
var monthCopy = month;
|
||||
var dataSource = _db.Layers.Where(x =>
|
||||
x.Type == LayerType.processed &&
|
||||
!x.IsDeleted &&
|
||||
x.Name != null && x.Name.Contains($"{year}/{month}-{source.Desc1}-T")
|
||||
x.Name != null && x.Name.Contains($"{year}/{monthCopy}-{source.Desc1}-T")
|
||||
)
|
||||
.Include(x => x.Records)
|
||||
.FirstOrDefault();
|
||||
if (dataSource != null)
|
||||
{
|
||||
List<Record> news = dataSource.Records!
|
||||
.Where(x =>
|
||||
{
|
||||
if (sourceCodes.Count > 0)
|
||||
{
|
||||
return sourceCodes.Contains(int.Parse(x.Code!));
|
||||
}
|
||||
|
||||
return true; // get all
|
||||
})
|
||||
.Where(x => sourceCodes.Count <= 0 || sourceCodes.Contains(int.Parse(x.Code!)))
|
||||
.Select(x =>
|
||||
{
|
||||
Record newRecord = new Record
|
||||
var newRecord = new Record
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Code = x.Code + month.ToString("D2"),
|
||||
@@ -126,9 +114,9 @@ namespace WebAPI.dataProcessors
|
||||
}
|
||||
else
|
||||
{
|
||||
logsController.AddEntry(new LogEntry
|
||||
_logsController.AddEntry(new LogEntry
|
||||
{
|
||||
Title = $"{processWorker!.Name}, {processWorker.Id}",
|
||||
Title = $"{processWorker.Name}, {processWorker.Id}",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.process,
|
||||
Message = $"Data source {year}/{month}-{source.Desc1}-T3 not found",
|
||||
@@ -138,7 +126,7 @@ namespace WebAPI.dataProcessors
|
||||
}
|
||||
|
||||
// year summery
|
||||
Layer? dataSourceSum = db.Layers.Where(x =>
|
||||
var dataSourceSum = _db.Layers.Where(x =>
|
||||
x.Type == LayerType.processed &&
|
||||
!x.IsDeleted &&
|
||||
x.Name != null && x.Name.Contains($"{year}/13-{source.Desc1}-T")
|
||||
@@ -147,7 +135,7 @@ namespace WebAPI.dataProcessors
|
||||
.FirstOrDefault();
|
||||
if (dataSourceSum != null)
|
||||
{
|
||||
List<Record> news = dataSourceSum.Records!
|
||||
var news = dataSourceSum.Records!
|
||||
.Where(x =>
|
||||
{
|
||||
if (sourceCodes.Count > 0)
|
||||
@@ -174,9 +162,9 @@ namespace WebAPI.dataProcessors
|
||||
}
|
||||
else
|
||||
{
|
||||
logsController.AddEntry(new LogEntry
|
||||
_logsController.AddEntry(new LogEntry
|
||||
{
|
||||
Title = $"{processWorker!.Name}, {processWorker.Id}",
|
||||
Title = $"{processWorker.Name}, {processWorker.Id}",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.process,
|
||||
Message = $"Data source {year}/13-{source.Desc1}-T3 not found",
|
||||
@@ -185,74 +173,17 @@ namespace WebAPI.dataProcessors
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// year summary
|
||||
Layer? dataSourceSum = db.Layers.Where(x =>
|
||||
x.Type == LayerType.processed &&
|
||||
!x.IsDeleted &&
|
||||
x.Name != null && x.Name.Contains($"{year}/13-{source.Desc1}-T3")
|
||||
)
|
||||
.Include(x => x.Records)
|
||||
.FirstOrDefault();
|
||||
if (dataSourceSum != null)
|
||||
{
|
||||
dataSources.Add(dataSourceSum);
|
||||
}
|
||||
else
|
||||
{
|
||||
logsController.AddEntry(new LogEntry
|
||||
{
|
||||
Title = $"{processWorker!.Name}, {processWorker.Id}",
|
||||
Type = LogEntryType.warning,
|
||||
LogType = LogType.process,
|
||||
Message = $"Data source {year}/13-{source.Desc1}-T3 not found",
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
if (dataSources.Count == 0)
|
||||
{
|
||||
throw new Exception($"DataSources are empty");
|
||||
}
|
||||
|
||||
List<Record> newRecords = dataSources
|
||||
.SelectMany(x => x.Records!)
|
||||
.Where(x => codesList.Contains(int.Parse(x.Code!)))
|
||||
.Select(x =>
|
||||
{
|
||||
Layer? layer = dataSources.SingleOrDefault(y => y.Id == x.LayerId);
|
||||
string postFix = layer!.Name!.Split("/")[1].Split("-")[0];
|
||||
if (postFix.Length == 1)
|
||||
{
|
||||
postFix = "0" + postFix;
|
||||
}
|
||||
|
||||
Record newRecord = new Record
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Code = x.Code + postFix,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
ModifiedAt = DateTime.UtcNow,
|
||||
Value1 = x.Value32
|
||||
};
|
||||
|
||||
return newRecord;
|
||||
})
|
||||
.ToList();
|
||||
*/
|
||||
if (isNew)
|
||||
{
|
||||
db.Layers.Add(processedLayer);
|
||||
_db.Layers.Add(processedLayer);
|
||||
}
|
||||
else
|
||||
{
|
||||
db.Layers.Update(processedLayer);
|
||||
_db.Layers.Update(processedLayer);
|
||||
}
|
||||
|
||||
controller.SaveRecords(processedLayer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
db.SaveChanges();
|
||||
_controller.SaveRecords(processedLayer.Id, newRecords, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
|
||||
_db.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user