BISK2023-17-endpoint-to-sync-data-from-clients-to-biskilog-cloud #1

Merged
barhen merged 4 commits from BISK2023-17-endpoint-to-sync-data-from-clients-to-biskilog-cloud into dev 1 year ago
  1. 20
      Biskilog_Cloud.sln
  2. 13
      ClientManager/ClientManager.csproj
  3. 10
      ClientManager/Program.cs
  4. 11
      ClientManager/Properties/launchSettings.json
  5. 21
      ClientManager/Worker.cs
  6. 8
      ClientManager/appsettings.Development.json
  7. 8
      ClientManager/appsettings.json
  8. 1175
      ServerManager/BiskPosContext.cs
  9. 32
      ServerManager/Controllers/WeatherForecastController.cs
  10. 48
      ServerManager/Program.cs
  11. 34
      ServerManager/Properties/launchSettings.json
  12. 41
      ServerManager/ServerManager.csproj
  13. 287
      ServerManager/ServiceRepo/CompanyService.cs
  14. 390
      ServerManager/ServiceRepo/ProductsService.cs
  15. 282
      ServerManager/ServiceRepo/SalesService.cs
  16. 346
      ServerManager/SyncMethods/CompanySync.cs
  17. 327
      ServerManager/SyncMethods/ProductSync.cs
  18. 341
      ServerManager/SyncMethods/SalesSync.cs
  19. 12
      ServerManager/WeatherForecast.cs
  20. 46
      ServerManager/Worker.cs
  21. 2
      ServerManager/appsettings.Development.json
  22. 15
      ServerManager/appsettings.json
  23. 22
      Shared/Biskilog_Cloud.Shared.csproj
  24. 11
      Shared/ClientContractModels/Authtype.cs
  25. 21
      Shared/ClientContractModels/Clientbusiness.cs
  26. 15
      Shared/ClientContractModels/Clientinfo.cs
  27. 21
      Shared/ClientContractModels/Contract.cs
  28. 16
      Shared/ClientContractModels/Databasemap.cs
  29. 16
      Shared/ClientContractModels/Siteaccesspermission.cs
  30. 27
      Shared/ClientContractModels/Userauth.cs
  31. 16
      Shared/CustomModels/CancelledSales.cs
  32. 15
      Shared/CustomModels/CustomerAccounts.cs
  33. 29
      Shared/CustomModels/MostPurchaseItem.cs
  34. 18
      Shared/CustomModels/ProductItem.cs
  35. 23
      Shared/CustomModels/ProductPriceChange.cs
  36. 26
      Shared/CustomModels/ProductUnits.cs
  37. 22
      Shared/CustomModels/SaleItem.cs
  38. 14
      Shared/CustomModels/SyncTimestamp.cs
  39. 16
      Shared/CustomModels/TradeSummary.cs
  40. 21
      Shared/CustomModels/WeeklySaleItem.cs
  41. 17
      Shared/Enums/AuthEnums.cs
  42. 14
      Shared/Enums/ConnectionEnums.cs
  43. 86
      Shared/Interfaces/IAnalytics.cs
  44. 19
      Shared/Interfaces/IAuthService.cs
  45. 17
      Shared/Interfaces/ICalculator.cs
  46. 26
      Shared/Interfaces/ICompanyInfo.cs
  47. 24
      Shared/Interfaces/IConnectionService.cs
  48. 12
      Shared/Interfaces/ICustomer.cs
  49. 15
      Shared/Interfaces/IMainInterface.cs
  50. 38
      Shared/Interfaces/IProducts.cs
  51. 35
      Shared/Interfaces/ISalesInterface.cs
  52. 16
      Shared/Interfaces/ISearchService.cs
  53. 22
      Shared/Interfaces/ITokenService.cs
  54. 12
      Shared/Interfaces/IUser.cs
  55. 23
      Shared/Models/CreditPurchase.cs
  56. 27
      Shared/Models/CustomerAccount.cs
  57. 23
      Shared/Models/ProductAltUnit.cs
  58. 17
      Shared/Models/RestockLevel.cs
  59. 21
      Shared/Models/SystemUserRole.cs
  60. 24
      Shared/Models/TbStock.cs
  61. 21
      Shared/Models/TblBranch.cs
  62. 15
      Shared/Models/TblBrand.cs
  63. 19
      Shared/Models/TblCancelledTransaction.cs
  64. 39
      Shared/Models/TblCart.cs
  65. 15
      Shared/Models/TblCategory.cs
  66. 23
      Shared/Models/TblCompanyDetail.cs
  67. 37
      Shared/Models/TblCustomer.cs
  68. 17
      Shared/Models/TblCustomerPurchase.cs
  69. 22
      Shared/Models/TblDeliveryDetail.cs
  70. 27
      Shared/Models/TblDeliveryHead.cs
  71. 26
      Shared/Models/TblDeliveryRecipient.cs
  72. 21
      Shared/Models/TblDiscountLog.cs
  73. 35
      Shared/Models/TblDriver.cs
  74. 41
      Shared/Models/TblHeldTransaction.cs
  75. 17
      Shared/Models/TblInventory.cs
  76. 19
      Shared/Models/TblInventoryEntry.cs
  77. 31
      Shared/Models/TblInvoice.cs
  78. 21
      Shared/Models/TblPriceChange.cs
  79. 33
      Shared/Models/TblProduct.cs
  80. 21
      Shared/Models/TblTruck.cs
  81. 21
      Shared/Models/TblTruckAssignment.cs
  82. 19
      Shared/Models/TblTruckDriverMapping.cs
  83. 19
      Shared/Models/TblTruckInventory.cs
  84. 35
      Shared/Models/TblUser.cs
  85. 15
      Shared/Models/TblUserActivity.cs
  86. 19
      Shared/Models/UnitOfMeasure.cs
  87. 239
      Shared/ServiceRepo/TokenService.cs
  88. 4
      Shared/SharedClass.cs

20
Biskilog_Cloud.sln

@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.5.33530.505 VisualStudioVersion = 17.5.33530.505
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientManager", "ClientManager\ClientManager.csproj", "{AD0879FE-FBA8-4CD1-B95A-93E0277FD40F}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServerManager", "ServerManager\ServerManager.csproj", "{48786C44-14A8-4510-9DC2-167C431DDE95}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerManager", "ServerManager\ServerManager.csproj", "{7A6AAC33-5ED1-4CAD-AA67-E107245354B3}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Biskilog_Cloud.Shared", "Shared\Biskilog_Cloud.Shared.csproj", "{1D368EE7-D1D3-4D50-83ED-57B0EB9CC6F4}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -13,14 +13,14 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{AD0879FE-FBA8-4CD1-B95A-93E0277FD40F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {48786C44-14A8-4510-9DC2-167C431DDE95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AD0879FE-FBA8-4CD1-B95A-93E0277FD40F}.Debug|Any CPU.Build.0 = Debug|Any CPU {48786C44-14A8-4510-9DC2-167C431DDE95}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AD0879FE-FBA8-4CD1-B95A-93E0277FD40F}.Release|Any CPU.ActiveCfg = Release|Any CPU {48786C44-14A8-4510-9DC2-167C431DDE95}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AD0879FE-FBA8-4CD1-B95A-93E0277FD40F}.Release|Any CPU.Build.0 = Release|Any CPU {48786C44-14A8-4510-9DC2-167C431DDE95}.Release|Any CPU.Build.0 = Release|Any CPU
{7A6AAC33-5ED1-4CAD-AA67-E107245354B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1D368EE7-D1D3-4D50-83ED-57B0EB9CC6F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A6AAC33-5ED1-4CAD-AA67-E107245354B3}.Debug|Any CPU.Build.0 = Debug|Any CPU {1D368EE7-D1D3-4D50-83ED-57B0EB9CC6F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A6AAC33-5ED1-4CAD-AA67-E107245354B3}.Release|Any CPU.ActiveCfg = Release|Any CPU {1D368EE7-D1D3-4D50-83ED-57B0EB9CC6F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A6AAC33-5ED1-4CAD-AA67-E107245354B3}.Release|Any CPU.Build.0 = Release|Any CPU {1D368EE7-D1D3-4D50-83ED-57B0EB9CC6F4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

13
ClientManager/ClientManager.csproj

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-ClientManager-173f3572-8fd4-498f-addd-d620cda23800</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
</ItemGroup>
</Project>

10
ClientManager/Program.cs

@ -1,10 +0,0 @@
using ClientManager;
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
host.Run();

11
ClientManager/Properties/launchSettings.json

@ -1,11 +0,0 @@
{
"profiles": {
"ClientManager": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

21
ClientManager/Worker.cs

@ -1,21 +0,0 @@
namespace ClientManager
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}

8
ClientManager/appsettings.Development.json

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

8
ClientManager/appsettings.json

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

1175
ServerManager/BiskPosContext.cs

File diff suppressed because it is too large

32
ServerManager/Controllers/WeatherForecastController.cs

@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;
namespace ServerManager.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}

48
ServerManager/Program.cs

@ -1,10 +1,44 @@
using Biskilog_Cloud.Shared.Interfaces;
using Microsoft.EntityFrameworkCore;
using ServerManager; using ServerManager;
using ServerManager.ServiceRepo;
using ServerManager.SyncMethods;
IHost host = Host.CreateDefaultBuilder(args) var builder = WebApplication.CreateBuilder(args);
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
host.Run(); // Add services to the container.
builder.Services.AddSignalR();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddEntityFrameworkMySql().AddDbContext<BiskPosContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("Connection"));
});
builder.Services.AddScoped<SalesSync>();
builder.Services.AddScoped<CompanySync>();
builder.Services.AddScoped<ProductSync>();
builder.Services.AddHostedService<Worker>();
builder.Services.AddScoped<ISalesInterface, SalesService>();
builder.Services.AddScoped<IUser, CompanyService>();
builder.Services.AddScoped<ICustomer, CompanyService>();
builder.Services.AddScoped<ICompanyInfo, CompanyService>();
builder.Services.AddScoped<IProduct, ProductsService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

34
ServerManager/Properties/launchSettings.json

@ -1,10 +1,40 @@
{ {
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:21664",
"sslPort": 44321
}
},
"profiles": { "profiles": {
"ServerManager": { "http": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5110",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7022;http://localhost:5110",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": { "environmentVariables": {
"DOTNET_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
} }
} }

41
ServerManager/ServerManager.csproj

@ -1,13 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk.Worker"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-ServerManager-52a85e73-fd4f-461a-8b7b-99494934c716</UserSecretsId> </PropertyGroup>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> <PackageReference Include="Dapper" Version="2.0.151" />
</ItemGroup> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
<PackageReference Include="BCrypt.Net" Version="0.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.5" />
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="3.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Biskilog_Cloud.Shared.csproj" />
</ItemGroup>
</Project> </Project>

287
ServerManager/ServiceRepo/CompanyService.cs

@ -0,0 +1,287 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using Dapper;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using Microsoft.EntityFrameworkCore;
using System;
using System.Data;
using System.Data.SqlClient;
namespace ServerManager.ServiceRepo
{
public class CompanyService : ICompanyInfo, ICustomer, IUser
{
private readonly BiskPosContext m_context;
public CompanyService(BiskPosContext a_context)
{
m_context = a_context;
}
#region Unimplemented
public IEnumerable<TblUser> FetchUsers()
{
throw new NotImplementedException();
}
public Task<IEnumerable<TblUser>> GetUsers()
{
throw new NotImplementedException();
}
public IEnumerable<CustomerAccounts> FetchCustomers()
{
throw new NotImplementedException();
}
public Task<IEnumerable<CustomerAccounts>> GetCustomers()
{
throw new NotImplementedException();
}
public Task<IEnumerable<TblBranch>> GetBranches()
{
throw new NotImplementedException();
}
public string GetBranchName(string a_branchId)
{
throw new NotImplementedException();
}
public Task<TblCompanyDetail> GetCompanyInfoAsync()
{
throw new NotImplementedException();
}
public string GetCompanyName()
{
throw new NotImplementedException();
}
public IEnumerable<TblBranch> FetchBranches()
{
throw new NotImplementedException();
}
#endregion
public async Task<IEnumerable<TblBranch>> FetchBranch(DateTime a_dateTime, string a_branch)
{
string connection = m_context.Database.GetConnectionString();
using (IDbConnection dbConnection = new SqlConnection(connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblbranch",
a_branchId = a_branch,
lastModified = a_dateTime
};
List<TblBranch> result = (await dbConnection.QueryAsync<TblBranch>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblCompanyDetail>> FetchCompanyInfoAsync(DateTime a_dateTime, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcompanydetails",
a_branchId = a_branch,
lastModified = a_dateTime
};
List<TblCompanyDetail> result = (await dbConnection.QueryAsync<TblCompanyDetail>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblTruckDriverMapping>> FetchDriverMappingAsync(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbltruck_drivermapping",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblTruckDriverMapping> result = (await dbConnection.QueryAsync<TblTruckDriverMapping>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblDriver>> FetchDriversAsync(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbldrivers",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblDriver> result = (await dbConnection.QueryAsync<TblDriver>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<SystemUserRole>> FetchSystemRoles(DateTime a_dateTime, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "systemuserroles",
a_branchId = a_branch,
lastModified = a_dateTime
};
List<SystemUserRole> result = (await dbConnection.QueryAsync<SystemUserRole>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblTruck>> FetchTruckAsync(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbltruck",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblTruck> result = (await dbConnection.QueryAsync<TblTruck>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblTruckInventory>> FetchTruckInventoryAsync(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbltruckinventory",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblTruckInventory> result = (await dbConnection.QueryAsync<TblTruckInventory>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblCustomer>> FetchCustomers(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcustomers",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblCustomer> result = (await dbConnection.QueryAsync<TblCustomer>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblTruckAssignment>> FetchTruckAssignmentAsync(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbltruckassignments",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblTruckAssignment> result = (await dbConnection.QueryAsync<TblTruckAssignment>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblUser>> FetchUsers(DateTime a_syncDate, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_context.Database.GetConnectionString()))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblusers",
a_branchId = a_branch,
lastModified = a_syncDate
};
List<TblUser> result = (await dbConnection.QueryAsync<TblUser>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
}
}

390
ServerManager/ServiceRepo/ProductsService.cs

@ -0,0 +1,390 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using Dapper;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Data.SqlClient;
namespace ServerManager.ServiceRepo
{
public class ProductsService : IProduct
{
private readonly BiskPosContext m_context;
private string m_connection;
public ProductsService(BiskPosContext a_context, IConfiguration configuration)
{
m_context = a_context;
m_connection = configuration.GetConnectionString("connection")!.ToString();
}
public event EventHandler ProductsChanged;
public event EventHandler UnitsChanged;
public event EventHandler BrandsChanged;
public event EventHandler CategoriesChanged;
public async Task<IEnumerable<TblBrand>> FetchBrandsAsync(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblBrand",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblBrand> result = (await dbConnection.QueryAsync<TblBrand>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblBrand>();
}
}
public async Task<IEnumerable<TblCategory>> FetchCategoriesAsync(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcategory",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblCategory> result = (await dbConnection.QueryAsync<TblCategory>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblCategory>();
}
}
public async Task<IEnumerable<TblInventory>> FetchInventory(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblInventory",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblInventory> result = (await dbConnection.QueryAsync<TblInventory>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblInventory>();
}
}
public async Task<IEnumerable<TblInventoryEntry>> FetchInventoryEntries(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblInventoryentries",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblInventoryEntry> result = (await dbConnection.QueryAsync<TblInventoryEntry>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblInventoryEntry>();
}
}
public async Task<IEnumerable<TblPriceChange>> FetchPriceChanges(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblpricechanges",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblPriceChange> result = (await dbConnection.QueryAsync<TblPriceChange>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblPriceChange>();
}
}
public async Task<IEnumerable<ProductAltUnit>> FetchProductAltUnit(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "productaltunit",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<ProductAltUnit> result = (await dbConnection.QueryAsync<ProductAltUnit>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<ProductAltUnit>();
}
}
public async Task<IEnumerable<TblProduct>> FetchProducts(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
branchID = a_branch,
lastModified = a_lastSync
};
List<TblProduct> result = (await dbConnection.QueryAsync<TblProduct>(
"FetchProductTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TblProduct>();
}
}
public async Task<IEnumerable<RestockLevel>> FetchRestockAsync(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "Restocklevels",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<RestockLevel> result = (await dbConnection.QueryAsync<RestockLevel>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<RestockLevel>();
}
}
public async Task<IEnumerable<TbStock>> FetchStockAsync(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "Tbstock",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TbStock> result = (await dbConnection.QueryAsync<TbStock>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<TbStock>();
}
}
public async Task<IEnumerable<UnitOfMeasure>> FetchUnitOfMeasureAsync(DateTime a_lastSync, string a_branch)
{
try
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "unitofmeasure",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<UnitOfMeasure> result = (await dbConnection.QueryAsync<UnitOfMeasure>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return new List<UnitOfMeasure>();
}
}
public Task FetchBrands()
{
throw new NotImplementedException();
}
public Task FetchLowStockProducts()
{
throw new NotImplementedException();
}
public Task FetchCategories()
{
throw new NotImplementedException();
}
public Task FetchProducts()
{
throw new NotImplementedException();
}
public Task FetchUnits()
{
throw new NotImplementedException();
}
public IEnumerable<TblBrand> GetBrands(string a_brandKey = "")
{
throw new NotImplementedException();
}
public IEnumerable<TblCategory> GetCategories(string a_categoryKey = "")
{
throw new NotImplementedException();
}
public IEnumerable<ProductItem> GetLowstockItems()
{
throw new NotImplementedException();
}
public ProductItem GetProductById(string a_id)
{
throw new NotImplementedException();
}
public ProductItem GetProductByName(string name)
{
throw new NotImplementedException();
}
public IEnumerable<ProductItem> GetProducts(string a_productKey = "")
{
throw new NotImplementedException();
}
public string GetUnitName(string a_unitCode)
{
throw new NotImplementedException();
}
public IEnumerable<UnitOfMeasure> GetUnitofmeasures()
{
throw new NotImplementedException();
}
public void RefreshList()
{
throw new NotImplementedException();
}
}
}

282
ServerManager/ServiceRepo/SalesService.cs

@ -0,0 +1,282 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using Dapper;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Data.SqlClient;
namespace ServerManager.ServiceRepo
{
public class SalesService : ISalesInterface
{
private readonly BiskPosContext m_context;
private readonly string m_connection;
public SalesService(BiskPosContext a_context, IConfiguration configuration)
{
m_context = a_context;
m_connection = configuration.GetConnectionString("connection")!.ToString();
}
public event EventHandler TransactionsChanged;
public event EventHandler FetchComplete;
public event EventHandler FetchStart;
public async Task<IEnumerable<TblCancelledTransaction>> FetchCancelledTransaction(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcancelledtransaction",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblCancelledTransaction> result = (await dbConnection.QueryAsync<TblCancelledTransaction>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblCart>> FetchCartTbl(DateTime a_lastSync,string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcart",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblCart> result = (await dbConnection.QueryAsync<TblCart>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<CreditPurchase>> FetchCreditPurchase(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "CreditPurchases",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<CreditPurchase> result = (await dbConnection.QueryAsync<CreditPurchase>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<CustomerAccount>> FetchCustomerAccount(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "customeraccounts",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<CustomerAccount> result = (await dbConnection.QueryAsync<CustomerAccount>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblCustomerPurchase>> FetchCustomerPurchase(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tblcustomerpurchases",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblCustomerPurchase> result = (await dbConnection.QueryAsync<TblCustomerPurchase>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblDeliveryDetail>> FetchDeliveryDetails(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "tbldeliverydetails",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblDeliveryDetail> result = (await dbConnection.QueryAsync<TblDeliveryDetail>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblDeliveryHead>> FetchDeliveryHead(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblDeliveryHeads",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblDeliveryHead> result = (await dbConnection.QueryAsync<TblDeliveryHead>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblDeliveryRecipient>> FetchDeliveryRecipients(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblDeliveryRecipients",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblDeliveryRecipient> result = (await dbConnection.QueryAsync<TblDeliveryRecipient>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblDiscountLog>> FetchDiscountLogs(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblDiscountLogs",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblDiscountLog> result = (await dbConnection.QueryAsync<TblDiscountLog>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public async Task<IEnumerable<TblInvoice>> FetchInvoice(DateTime a_lastSync, string a_branch)
{
using (IDbConnection dbConnection = new SqlConnection(m_connection))
{
dbConnection.Open();
// Using Dapper to call a stored procedure with parameters
var parameters = new
{
a_tableName = "TblInvoices",
a_branchId = a_branch,
lastModified = a_lastSync
};
List<TblInvoice> result = (await dbConnection.QueryAsync<TblInvoice>(
"FetchTableRows",
parameters,
commandType: CommandType.StoredProcedure)).AsList();
return result;
}
}
public Task FetchReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public Task FetchRecentTransaction(int a_limit)
{
throw new NotImplementedException();
}
public Task FetchTransaction(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public Task<IEnumerable<TblCart>> GetReceiptDetail(string a_receiptId)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetRecentTransaction()
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetTransactions(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
}
}

346
ServerManager/SyncMethods/CompanySync.cs

@ -0,0 +1,346 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ServerManager.SyncMethods
{
public class CompanySync
{
private readonly ICompanyInfo m_companyService;
private readonly IUser m_userService;
private readonly ICustomer m_customerService;
private HttpClient m_httpClient;
public CompanySync(ICompanyInfo companyService, IUser userService, ICustomer customerService)
{
m_companyService = companyService;
m_userService = userService;
m_customerService = customerService;
m_httpClient = new HttpClient();
}
/// <summary>
/// Returns a collection of tasks to perform a sync in the ICompanyInterface
/// </summary>
/// <returns></returns>
public IEnumerable<Task> GetCompanySyncTask(HttpClient httpClient)
{
m_httpClient = httpClient;
return new Task[] {
SyncCompanyTable(),
SyncBranchTable(),
SyncCustomer(),
SyncDrivers(),
SyncTruckAssignments(),
SyncTruckDriverMappingSync(),
SyncTruckInventorySync(),
SyncUsersSync(),
SyncTruckSync(),
SyncSystemUserRoles()
};
}
private async Task SyncCompanyTable()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tblcompanydetails");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCompanyDetail> modifiedCart = await m_companyService.FetchCompanyInfoAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "tblcompanydetails",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCompanyDetail> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tblcompanydetails", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncBranchTable()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tblbranch");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblBranch> modifiedCart = await m_companyService.FetchBranch(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "tblbranch",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblBranch> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tblbranch", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncCustomer()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tblCustomers");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCustomer> modifiedCart = await m_customerService.FetchCustomers(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "tblCustomers",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCustomer> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tblCustomers", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncDrivers()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tbldrivers");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblDriver> modifiedCart = await m_companyService.FetchDriversAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbldrivers", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblDriver> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tbldriver", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncSystemUserRoles()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/systemuserroles");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<SystemUserRole> modifiedCart = await m_companyService.FetchSystemRoles(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "systemuserroles", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<SystemUserRole> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/SystemRoles", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncTruckAssignments()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tbltruckassignments");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblTruckAssignment> modifiedCart = await m_companyService.FetchTruckAssignmentAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbltruckassignments", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblTruckAssignment> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tblTruckAssignment", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncTruckDriverMappingSync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tbltruck_drivermapping");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblTruckDriverMapping> modifiedCart = await m_companyService.FetchDriverMappingAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbltruck_drivermapping", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblTruckDriverMapping> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tbldrivermappings", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncTruckInventorySync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tbltruckinventory");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblTruckInventory> modifiedCart = await m_companyService.FetchTruckInventoryAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbltruckinventory", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblTruckInventory> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tbltruckinventory", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncTruckSync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tbltrucks");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblTruck> modifiedCart = await m_companyService.FetchTruckAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbltrucks", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblTruck> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tbltrucks", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
private async Task SyncUsersSync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncCompanyInfo/lastsyncdate/tblusers");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblUser> modifiedCart = await m_userService.FetchUsers(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblusers", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblUser> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/publish/tblusers", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncCompanyInfo/setsyncdate", syncTimestamp);
}
}
}

327
ServerManager/SyncMethods/ProductSync.cs

@ -0,0 +1,327 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using System.Net.Http.Headers;
namespace ServerManager.SyncMethods
{
public class ProductSync
{
private readonly IProduct m_productService;
private HttpClient m_httpClient;
public ProductSync(IProduct a_produtService)
{
m_productService = a_produtService;
m_httpClient = new HttpClient();
}
/// <summary>
/// Returns a collection of tasks to perform a sync in the SalesInterface
/// </summary>
/// <returns></returns>
public IEnumerable<Task> GetProductSyncTask(HttpClient httpClient)
{
m_httpClient = httpClient;
return new Task[] {
SyncProductsAsync(),
SyncInventoryAsync(),
SyncInventoryEntriesAsync(),
SyncRestockAsync(),
SyncPriceChangesAsync(),
SyncProductAltUnitAsync(),
SyncStockAsync(),
SyncBrandsAsync(),
SyncCategoriesAsync(),
SyncUnitOfMeasureAsync(),
};
}
private async Task SyncProductsAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblproduct");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblProduct> modifiedCart = await m_productService.FetchProducts(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblproduct", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblProduct> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblproducts", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncInventoryAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblInventory");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblInventory> modifiedCart = await m_productService.FetchInventory(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblInventory", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblInventory> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblInventory", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncInventoryEntriesAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblInventoryentries");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblInventoryEntry> modifiedCart = await m_productService.FetchInventoryEntries(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblInventoryentries", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblInventoryEntry> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblInventoryentry", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncRestockAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/restocklevels");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<RestockLevel> modifiedCart = await m_productService.FetchRestockAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "restocklevels", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<RestockLevel> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblRestock", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncPriceChangesAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblpricechanges");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblPriceChange> modifiedCart = await m_productService.FetchPriceChanges(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblpricechanges", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblPriceChange> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tlpricechanges", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncProductAltUnitAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/productaltunit");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<RestockLevel> modifiedCart = await m_productService.FetchRestockAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "productaltunit", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<RestockLevel> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblProductAltUnit", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncStockAsync()
{var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tbstock");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TbStock> modifiedCart = await m_productService.FetchStockAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbstock", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TbStock> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblStock", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncBrandsAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblbrands");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblBrand> modifiedCart = await m_productService.FetchBrandsAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblbrands", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblBrand> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblbrands", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncCategoriesAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblcategory");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCategory> modifiedCart = await m_productService.FetchCategoriesAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblcategory", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCategory> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblCategories", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
private async Task SyncUnitOfMeasureAsync()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/unitofmeasure");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<UnitOfMeasure> modifiedCart = await m_productService.FetchUnitOfMeasureAsync(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "unitofmeasure", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<UnitOfMeasure> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblunitofmeasure", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
}
}
}

341
ServerManager/SyncMethods/SalesSync.cs

@ -0,0 +1,341 @@
using System.Net.Http.Headers;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using Biskilog_Cloud.Shared.CustomModels;
namespace ServerManager.SyncMethods
{
public class SalesSync
{
private readonly ISalesInterface m_salesService;
private HttpClient m_httpClient;
public SalesSync(ISalesInterface a_salesService)
{
m_salesService = a_salesService;
m_httpClient = new HttpClient();
}
/// <summary>
/// Returns a collection of tasks to perform a sync in the SalesInterface
/// </summary>
/// <returns></returns>
public IEnumerable<Task> GetSalesSyncTask(HttpClient httpClient)
{
m_httpClient = httpClient;
return new Task[] {
SyncCartTable(),
SyncInvoice(),
SyncDiscountLogs(),
SyncCancelledTransactionTable(),
SyncDeliveryRecipient(),
SyncCreditPurchase(),
SyncCustomerAccounts(),
SyncCustomerPurchases(),
SyncDeliveryDetails(),
SynctblDeliveryhead(),
};
}
private async Task SyncCartTable()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblcart");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCart> modifiedCart = await m_salesService.FetchCartTbl(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "TblCart",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCart> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblCart", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncCancelledTransactionTable()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblcancelledtransactions");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCancelledTransaction> modifiedCart = await m_salesService.FetchCancelledTransaction(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "tblcancelledtransactions",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCancelledTransaction> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblcancelledtransaction", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncCreditPurchase()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/CreditPurchases");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<CreditPurchase> modifiedCart = await m_salesService.FetchCreditPurchase(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp
{
TableName = "CreditPurchases",
Timestamp = DateTime.Now.AddSeconds(-10),
};
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<CreditPurchase> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblCreditpurchase", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncCustomerAccounts()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/customeraccounts");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<CustomerAccount> modifiedCart = await m_salesService.FetchCustomerAccount(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "customeraccounts", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<CustomerAccount> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblCustomerAccount", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncCustomerPurchases()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblcustomerpurchases");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblCustomerPurchase> modifiedCart = await m_salesService.FetchCustomerPurchase(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblcustomerpurchases", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblCustomerPurchase> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/CustomerPurchase", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncDiscountLogs()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tbldiscountlogs");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblDiscountLog> modifiedCart = await m_salesService.FetchDiscountLogs(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbldiscountlogs", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblDiscountLog> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/DiscountLogs", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncDeliveryDetails()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblDeliverydetails");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblDeliveryDetail> modifiedCart = await m_salesService.FetchDeliveryDetails(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbldeliverydetails", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblDeliveryDetail> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblDeliverydetails", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SynctblDeliveryhead()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblDeliveryhead");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblDeliveryHead> modifiedCart = await m_salesService.FetchDeliveryHead(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbldeliveryhead", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblDeliveryHead> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblDeliveryhead", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncDeliveryRecipient()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblDeliveryrecipients");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblDeliveryRecipient> modifiedCart = await m_salesService.FetchDeliveryRecipients(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbldeliveryrecipients", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblDeliveryRecipient> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblDeliveryrecipient", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
private async Task SyncInvoice()
{
var responseMessage = await m_httpClient.GetAsync("/api/SyncSales/lastsyncdate/tblinvoice");
if (!responseMessage.IsSuccessStatusCode)
{
return;
}
DateTime date = await responseMessage.Content.ReadFromJsonAsync<DateTime>();
IEnumerable<TblInvoice> modifiedCart = await m_salesService.FetchInvoice(date, "BRID0");
SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblinvoice", Timestamp = DateTime.Now.AddSeconds(-10) };
int batchSize = 200;
int totalItems = modifiedCart.Count();
int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
for (int batchIndex = 0; batchIndex < batches; batchIndex++)
{
List<TblInvoice> batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
var response = await m_httpClient.PostAsJsonAsync("/api/SyncSales/publish/tblinvoice", batch);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Sent batch {batchIndex + 1}, Count: {batch.Count}");
}
}
//Set last sync date
await m_httpClient.PostAsJsonAsync("/api/SyncSales/setsyncdate", syncTimestamp);
}
}
}

12
ServerManager/WeatherForecast.cs

@ -0,0 +1,12 @@
namespace ServerManager;
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}

46
ServerManager/Worker.cs

@ -1,21 +1,57 @@
using ServerManager.SyncMethods;
using System.Net.Http.Headers;
namespace ServerManager namespace ServerManager
{ {
public class Worker : BackgroundService public class Worker : BackgroundService
{ {
private readonly ILogger<Worker> _logger; private readonly ILogger<Worker> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IConfiguration m_configuration;
private HttpClient m_httpClient;
public Worker(ILogger<Worker> logger) public Worker(ILogger<Worker> logger, IServiceProvider serviceProvider, IConfiguration configuration)
{ {
_logger = logger; _logger = logger;
_serviceProvider = serviceProvider;
m_configuration = configuration;
} }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
while (!stoppingToken.IsCancellationRequested) try
{
string baseurl = m_configuration.GetValue("BaseUrl", "")!;
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(baseurl);
string token = m_configuration.GetValue("Token", "")!;
var authHeader = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Authorization = authHeader;
using var scope = _serviceProvider.CreateScope();
var salesSync = scope.ServiceProvider.GetRequiredService<SalesSync>();
var productSync = scope.ServiceProvider.GetRequiredService<ProductSync>();
var companySync = scope.ServiceProvider.GetRequiredService<CompanySync>();
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time} ", DateTimeOffset.Now);
List<Task> runTask = new List<Task>();
runTask.AddRange(salesSync.GetSalesSyncTask(httpClient));
runTask.AddRange(productSync.GetProductSyncTask(httpClient));
runTask.AddRange(companySync.GetCompanySyncTask(httpClient));
// Wait for all tasks to complete
await Task.WhenAll(runTask);
await Task.Delay(1000, stoppingToken);
}
}
catch (Exception ex)
{ {
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); Console.WriteLine(ex.ToString());
await Task.Delay(1000, stoppingToken);
} }
} }
} }
} }

2
ServerManager/appsettings.Development.json

@ -2,7 +2,7 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.AspNetCore": "Warning"
} }
} }
} }

15
ServerManager/appsettings.json

@ -2,7 +2,18 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.AspNetCore": "Warning"
} }
},
"ConnectionStrings": {
"Connection": "Server=BarhenVM\\SqlExpress;Database=BISK_POS;Integrated Security=True;TrustServerCertificate=true"
},
"Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyMWM3MWE0Ni0xZmY2LTRkMGMtYmYzMS1iMTExMzJlMGM5ODQiLCJpYXQiOiIxNC8wOC8yMDIzIDY6MjI6MzIgcG0iLCJDb250cmFjdFN0YXJ0IjoiMTgvMDUvMjAyMyA4OjQ3OjI3IHBtIiwiQ29udHJhY3RFbmQiOiIxOC8wNS8yMDI0IDg6NDc6MjkgcG0iLCJVc2VySWQiOiIxIiwiVXNlcm5hbWUiOiJ0ZXN0IiwiRGJJZCI6IjEiLCJDb21wYXJpc29uTW9kZSI6IkZhbHNlIiwiQnJhbmNoSWQiOiJCUklEMCIsIkJyYW5jaEFjY2VzcyI6IkJSSUQwIiwiQ2xpZW50SWQiOiIxIiwiZXhwIjoxNjkzMjQ2OTUyLCJpc3MiOiJBVVRIIFNFUlZFUiIsImF1ZCI6IkJJU0tJTE9HIn0.W3kxw5kEj13TDSs96doR20IW96k3aO8uR5SKGiSaSX4",
"BaseUrl": "https://localhost:7247/",
"AllowedHosts": "*",
"JWT": {
"Key": "@@BISKILOGACCOUNTING2023DEV??//##$",
"Issuer": "AUTH SERVER",
"Audience": "BISKILOG"
} }
} }

22
Shared/Biskilog_Cloud.Shared.csproj

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="Blazored.LocalStorage" Version="4.3.0" />
<PackageReference Include="Blazored.SessionStorage" Version="2.3.0" />
<PackageReference Include="EntityFramework" Version="6.4.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.30.1" />
</ItemGroup>
<ItemGroup>
<SupportedPlatform Include="browser" />
</ItemGroup>
</Project>

11
Shared/ClientContractModels/Authtype.cs

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Authtype
{
public int Id { get; set; }
public string? Type { get; set; }
}

21
Shared/ClientContractModels/Clientbusiness.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Clientbusiness
{
/// <summary>
/// there could be multiple branches of the same business
/// </summary>
public int BusinessId { get; set; }
public int ClientId { get; set; }
public string BusinessName { get; set; } = null!;
public string BiskilogVersion { get; set; } = null!;
public DateTime DateJoined { get; set; }
public string BusinessExternalId { get; set; } = string.Empty!;
}

15
Shared/ClientContractModels/Clientinfo.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Clientinfo
{
public int ClientId { get; set; }
public string? Fullname { get; set; }
public string? PhoneNumber { get; set; }
public string? Email { get; set; }
}

21
Shared/ClientContractModels/Contract.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Contract
{
public int ContractId { get; set; }
public int ClientId { get; set; }
public int? BusinessId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public decimal? Bill { get; set; }
public string Comments { get; set; } = null!;
}

16
Shared/ClientContractModels/Databasemap.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Databasemap
{
public int DbNo { get; set; }
public string DbName { get; set; } = null!;
public int ClientId { get; set; }
public string Domain { get; set; }
public DateTime LastSyncDate { get; set; }
}

16
Shared/ClientContractModels/Siteaccesspermission.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Siteaccesspermission
{
public int UserId { get; set; }
/// <summary>
/// businessIds could also been seen as branchID
/// </summary>
public int BusinessId { get; set; }
public int ClientId { get; set; }
}

27
Shared/ClientContractModels/Userauth.cs

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.ClientContractModels;
public partial class Userauth
{
public int UserId { get; set; }
public int ClientId { get; set; }
public string? Username { get; set; }
public string? Email { get; set; }
public string? Passsword { get; set; }
public string? PhoneNumber { get; set; }
public int AuthType { get; set; }
public ulong Isactive { get; set; }
public ulong? Isowner { get; set; }
public DateTime? LastLogin { get; set; }
}

16
Shared/CustomModels/CancelledSales.cs

@ -0,0 +1,16 @@
using Biskilog_Cloud.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class CancelledSales
{
public TblCancelledTransaction? CancelledTransaction { get; set; }
public string Customer { get; set; } = "WALK-IN Purchase";
public decimal? Value { get; set; }
}
}

15
Shared/CustomModels/CustomerAccounts.cs

@ -0,0 +1,15 @@
using Biskilog_Cloud.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class CustomerAccounts
{
public TblCustomer Customer { get; set; }
public decimal Debt { get; set; } = 0;
}
}

29
Shared/CustomModels/MostPurchaseItem.cs

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class MostPurchasedItem
{
/// <summary>
/// Specifies the id of the product
/// </summary>
public string ProductId { get; set; } = string.Empty;
/// <summary>
/// Specifies the name of the product
/// </summary>
public string ProductName { get; set; } = string.Empty;
/// <summary>
/// The total revenue generated from the sale
/// </summary>
public decimal? Revenue { get; set; }
/// <summary>
/// This is the number of times the item has been sold
/// </summary>
public int? NbrTimesSold { get; set; }
}
}

18
Shared/CustomModels/ProductItem.cs

@ -0,0 +1,18 @@
using Biskilog_Cloud.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class ProductItem
{
public TblProduct? Product { get; set; }
public TblInventory? Stock { get; set; }
public RestockLevel? Restocklevel { get; set; }
public List<ProductUnits> Units { get; set; } = new List<ProductUnits>();
public string BaseUnit { get; set; } = string.Empty;
}
}

23
Shared/CustomModels/ProductPriceChange.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class ProductPriceChange
{
public string? Pcode { get; set; }
public string? ProductName { get; set; }
public decimal? PreviousPrice { get; set; }
public decimal? CurrentPrice { get; set; }
public DateTime? ChangeDate { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}
}

26
Shared/CustomModels/ProductUnits.cs

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class ProductUnits
{
public string? Pcode { get; set; }
public string? UnitCode { get; set; }
public string? UnitName { get; set; }
public string? UnitBarcode { get; set; }
public decimal? PriceUnit { get; set; }
public int? QuantityUnit { get; set; }
public string DistinctiveCode { get; set; } = null!;
public string BranchId { get; set; } = null!;
}
}

22
Shared/CustomModels/SaleItem.cs

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class SaleItem
{
public string? Transno { get; set; }
public DateTime? Date { get; set; }
public string? Cashier { get; set; }
public string? Status { get; set; }
public decimal? Total { get; set; }
public string BranchId { get; set; } = null!;
public string Customer { get; set; } = "Walk-In Purchase"!;
}
}

14
Shared/CustomModels/SyncTimestamp.cs

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class SyncTimestamp
{
public string TableName { get; set; }
public DateTime Timestamp { get; set; }
}
}

16
Shared/CustomModels/TradeSummary.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class TradeSummary
{
public DateTime CurrentTradeDate { get; set; } = DateTime.Now;
public DateTime LastTradeDate { get; set; } = DateTime.Now.AddDays(-1);
public double CurrentTradeSales { get; set; } = 0;
public double LastTradeSales { get; set; } = 0;
}
}

21
Shared/CustomModels/WeeklySaleItem.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.CustomModels
{
public class WeeklySaleItem
{
public DateTime Date { get; set; }
public decimal? Total { get; set; }
public string BranchId { get; set; } = null!;
}
public class WeeklyCategorySummary
{
public decimal? Total { get; set; }
public string Category { get; set; } = string.Empty!;
}
}

17
Shared/Enums/AuthEnums.cs

@ -0,0 +1,17 @@
namespace Biskilog_Cloud.Shared.Enums
{
public enum AuthEnums
{
Registered,
AleadyLoggedin,
WrongPassword,
NotFound,
Found,
Expired,
Invalid,
Valid,
Successful,
Error
}
}

14
Shared/Enums/ConnectionEnums.cs

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Enums
{
public enum ConnectionEnums
{
ConnectionEstablished,
ConnectionNotEstablished,
}
}

86
Shared/Interfaces/IAnalytics.cs

@ -0,0 +1,86 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Models;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IAnalytics
{
/// <summary>
/// Fetches a collection of sales transaction made from the specified start date to the end date
/// </summary>
/// <param name="a_start">Specified Start Date</param>
/// <param name="a_end">Specified end Date</param>
/// <returns></returns>
IEnumerable<TblCart> GetSalesTransaction(DateTime a_start, DateTime a_end);
/// <summary>
/// Fetches a collection of sales transaction made within a one week period
/// </summary>
/// <returns></returns>
IEnumerable<WeeklySaleItem> GetWeeklySalesTransaction();
/// <summary>
/// Fetches a collection of in-debt customers
/// <returns></returns>
IEnumerable<CustomerAccounts> GetInDebtCustomers();
/// <summary>
/// Fetches a collection of Product Items which are currently out of stock
/// </summary>
/// <returns></returns>
IEnumerable<ProductItem> GetOutOfStockItems();
/// <summary>
/// Fetches a collection of the most purchased Product Items within a specified date range
/// </summary>
/// <param name="a_start"></param>
/// <param name="a_end"></param>
/// <returns></returns>
IEnumerable<MostPurchasedItem> GetMostPurchasedItem(DateTime a_start, DateTime a_end);
/// <summary>
/// Fetches a collection of cancelled transaction within a specified date range
/// </summary>
/// <param name="a_start"></param>
/// <param name="a_end"></param>
/// <returns></returns>
IEnumerable<CancelledSales> GetCancelledSales(DateTime a_start, DateTime a_end);
/// <summary>
/// Fetches a collection of transaction made by employees within a specified date range
/// </summary>
/// <param name="a_start"></param>
/// <param name="a_end"></param>
/// <returns>A dictionary of transactions made by employees with employee name as key</returns>
Dictionary<string, List<SaleItem>> GetEmployeeSales(DateTime a_start, DateTime a_end);
/// <summary>
/// Fetches a collection of product price changes with a specified date range
/// </summary>
/// <param name="a_start"></param>
/// <param name="a_end"></param>
/// <returns></returns>
IEnumerable<ProductPriceChange> GetPriceChanges(DateTime a_start, DateTime a_end);
/// <summary>
/// Fetch the trade summary which is made of the total sales made currently and previous trade
/// </summary>
/// <returns></returns>
TradeSummary GetTradeSummary();
/// <summary>
/// Fetches the most recent sales transactions
/// </summary>
/// <param name="a_limit">The number of rows to return </param>
/// <returns></returns>
IEnumerable<SaleItem> GetRecentSales(int a_limit);
/// <summary>
/// Fetches a collection of product price changes recently made
/// </summary>
/// <param name="a_limit">the number of rows to return</param>
/// <returns></returns>
IEnumerable<ProductPriceChange> GetRecentPriceChanges(int a_limit);
/// <summary>
/// Fetches a collection of price change history per product
/// </summary>
/// <param name="a_limit">the number of products to fetch history</param>
/// <returns></returns>
IEnumerable<ProductPriceChange> GetProductPriceChangeHistory(int a_limit);
/// <summary>
/// Fetches a collection of sales transaction grouped by category made within a one week period
/// </summary>
/// <returns></returns>
IEnumerable<WeeklyCategorySummary> GetWeeklySalesCategoryTransaction(int a_limit);
}
}

19
Shared/Interfaces/IAuthService.cs

@ -0,0 +1,19 @@
using Biskilog_Cloud.Shared.ClientContractModels;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IAuthService
{
/// <summary>
/// Authenticates user or client
/// </summary>
/// <param name="a_username"></param>
/// <param name="a_password"></param>
/// <returns>A tokenized string with relevant information on the authenticated user</returns>
Task<string> AuthenticateClient(string a_username, string a_password);
Contract? GetContract(int a_clientId, List<int> a_businessId);
Databasemap GetClientDB(int a_clientId);
List<Siteaccesspermission> GetSiteaccesspermission(int a_clientId, int a_userId);
List<Clientbusiness> GetClientbusiness(int a_clientId, int userId);
}
}

17
Shared/Interfaces/ICalculator.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ICalculator
{
double CalculatePercentage();
string FormatMoneyWithCurrency(double a_amount);
string FormatMoneyWithCurrencyKilo(double a_amount);
NumberFormatInfo GetCurrencyCode();
}
}

26
Shared/Interfaces/ICompanyInfo.cs

@ -0,0 +1,26 @@
using Biskilog_Cloud.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ICompanyInfo
{
IEnumerable<TblBranch> FetchBranches();
Task<TblCompanyDetail> GetCompanyInfoAsync();
Task<IEnumerable<TblBranch>> GetBranches();
string GetCompanyName();
string GetBranchName(string a_branchId);
Task<IEnumerable<TblBranch>> FetchBranch(DateTime a_dateTime, string a_branch);
Task<IEnumerable<SystemUserRole>> FetchSystemRoles(DateTime a_dateTime, string a_branch);
Task<IEnumerable<TblCompanyDetail>> FetchCompanyInfoAsync(DateTime a_dateTime, string a_branch);
Task<IEnumerable<TblDriver>> FetchDriversAsync(DateTime a_syncDate, string a_branchId);
Task<IEnumerable<TblTruckDriverMapping>> FetchDriverMappingAsync(DateTime a_syncDate, string a_branchId);
Task<IEnumerable<TblTruck>> FetchTruckAsync(DateTime a_syncDate, string a_branchId);
Task<IEnumerable<TblTruckInventory>> FetchTruckInventoryAsync(DateTime a_syncDate, string a_branchId);
Task<IEnumerable<TblTruckAssignment>> FetchTruckAssignmentAsync(DateTime a_syncDate, string a_branchId);
}
}

24
Shared/Interfaces/IConnectionService.cs

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IConnectionService
{
/// <summary>
/// Prepares and returns the connection string for a client using the specified database id
/// </summary>
/// <param name="a_databaseId">Specified database id to use</param>
/// <returns></returns>
string GetClientConnectionString(int a_databaseId);
/// <summary>
/// Prepare the DB context from the specified connection string
/// </summary>
/// <param name="a_connectionString"></param>
/// <returns>A configured BiskAcdbContext</returns>
object PrepareDBContext(string a_connectionString);
}
}

12
Shared/Interfaces/ICustomer.cs

@ -0,0 +1,12 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Models;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ICustomer
{
IEnumerable<CustomerAccounts> FetchCustomers();
Task<IEnumerable<CustomerAccounts>> GetCustomers();
Task<IEnumerable<TblCustomer>> FetchCustomers(DateTime a_lastSync, string a_branchId);
}
}

15
Shared/Interfaces/IMainInterface.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IMainInterface
{
void ShowReceipt(string a_receipt);
DateOnly CurrentTradeDate();
DateOnly PreviousTradeDate();
}
}

38
Shared/Interfaces/IProducts.cs

@ -0,0 +1,38 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Models;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IProduct
{
IEnumerable<UnitOfMeasure> GetUnitofmeasures();
IEnumerable<ProductItem> GetProducts(string a_productKey = "");
IEnumerable<TblBrand> GetBrands(string a_brandKey = "");
IEnumerable<TblCategory> GetCategories(string a_categoryKey = "");
IEnumerable<ProductItem> GetLowstockItems();
Task FetchProducts();
Task FetchLowStockProducts();
Task FetchUnits();
Task FetchBrands();
Task FetchCategories();
void RefreshList();
ProductItem GetProductById(string a_id);
ProductItem GetProductByName(string name);
string GetUnitName(string a_unitCode);
event EventHandler ProductsChanged;
event EventHandler UnitsChanged;
event EventHandler BrandsChanged;
event EventHandler CategoriesChanged;
Task<IEnumerable<TblProduct>> FetchProducts(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblInventory>> FetchInventory(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblInventoryEntry>> FetchInventoryEntries(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblPriceChange>> FetchPriceChanges(DateTime a_lastSync, string a_branch);
Task<IEnumerable<ProductAltUnit>> FetchProductAltUnit(DateTime a_lastSync, string a_branch);
Task<IEnumerable<RestockLevel>> FetchRestockAsync(DateTime a_lastSync, string a_branch);
Task<IEnumerable<UnitOfMeasure>> FetchUnitOfMeasureAsync(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TbStock>> FetchStockAsync(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblBrand>> FetchBrandsAsync(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblCategory>> FetchCategoriesAsync(DateTime a_lastSync, string a_branch);
}
}

35
Shared/Interfaces/ISalesInterface.cs

@ -0,0 +1,35 @@
using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ISalesInterface
{
Task FetchRecentTransaction(int a_limit);
Task FetchTransaction(DateTime a_start, DateTime a_end);
IEnumerable<SaleItem> GetTransactions(DateTime a_start, DateTime a_end);
IEnumerable<SaleItem> GetRecentTransaction();
Task FetchReceipt(string a_receiptId);
IEnumerable<SaleItem> GetReceipt(string a_receiptId);
Task<IEnumerable<TblCart>> GetReceiptDetail(string a_receiptId);
event EventHandler TransactionsChanged;
event EventHandler FetchComplete;
event EventHandler FetchStart;
Task<IEnumerable<TblCart>> FetchCartTbl(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblCancelledTransaction>> FetchCancelledTransaction(DateTime a_lastSync, string a_branch);
Task<IEnumerable<CreditPurchase>> FetchCreditPurchase(DateTime a_lastSync, string a_branch);
Task<IEnumerable<CustomerAccount>> FetchCustomerAccount(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblCustomerPurchase>> FetchCustomerPurchase(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblDiscountLog>> FetchDiscountLogs(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblDeliveryDetail>> FetchDeliveryDetails(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblDeliveryHead>> FetchDeliveryHead(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblDeliveryRecipient>> FetchDeliveryRecipients(DateTime a_lastSync, string a_branch);
Task<IEnumerable<TblInvoice>> FetchInvoice(DateTime a_lastSync, string a_branch);
}
}

16
Shared/Interfaces/ISearchService.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ISearchService
{
public event Action<string> SearchValueChanged;
public event Action ClearTextBox;
void PerformSearch(string a_searchKey);
void Clear();
}
}

22
Shared/Interfaces/ITokenService.cs

@ -0,0 +1,22 @@
using Biskilog_Cloud.Shared.ClientContractModels;
using Biskilog_Cloud.Shared.Enums;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface ITokenService
{
AuthEnums ValidateToken(string a_token);
string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison);
int? GetDatabaseIdFromToken(string a_token);
int? GetUserIdFromToken(string a_token);
string? GetUserNameFromToken(string a_token);
string? GetBaseBranch(string a_token);
bool? GetComparison(string a_token);
IEnumerable<string> BranchIds(string a_token);
string? GetAllBranch(string a_token);
Task SetToken(string a_token, bool a_remember);
Task<string> GetToken();
Task ClearToken();
Task<bool> IsTokenSet();
}
}

12
Shared/Interfaces/IUser.cs

@ -0,0 +1,12 @@

using Biskilog_Cloud.Shared.Models;
namespace Biskilog_Cloud.Shared.Interfaces
{
public interface IUser
{
IEnumerable<TblUser> FetchUsers();
Task<IEnumerable<TblUser>> GetUsers();
Task<IEnumerable<TblUser>> FetchUsers(DateTime a_syncDate, string a_branchId);
}
}

23
Shared/Models/CreditPurchase.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class CreditPurchase
{
public string ReceiptId { get; set; } = null!;
public DateTime? Date { get; set; }
public decimal? Paid { get; set; }
public decimal? TotalBill { get; set; }
public string? CustomerId { get; set; }
public string? Status { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

27
Shared/Models/CustomerAccount.cs

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class CustomerAccount
{
public string? CustomerId { get; set; }
public string? TransactionId { get; set; }
public DateTime? Date { get; set; }
public decimal? Debit { get; set; }
public decimal? Credit { get; set; }
public decimal? Balance { get; set; }
public string? Comments { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

23
Shared/Models/ProductAltUnit.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class ProductAltUnit
{
public string? Pcode { get; set; }
public string? UnitCode { get; set; }
public string? UnitBarcode { get; set; }
public decimal? PriceUnit { get; set; }
public int? QuantityUnit { get; set; }
public string DistinctiveCode { get; set; } = null!;
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

17
Shared/Models/RestockLevel.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class RestockLevel
{
public string ProductId { get; set; } = null!;
public int? WarnLevel { get; set; }
public string? Unit { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

21
Shared/Models/SystemUserRole.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class SystemUserRole
{
public string? Roles { get; set; }
public bool? Owner { get; set; }
public bool? Manager { get; set; }
public bool? Assist { get; set; }
public bool? Cashier { get; set; }
public int Id { get; set; }
public DateTime LastModified { get; set; }
}

24
Shared/Models/TbStock.cs

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TbStock
{
public string? Refno { get; set; }
public string? Pcode { get; set; }
public int? Qty { get; set; }
public DateTime? Sdate { get; set; }
public string? Stockinby { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}
;

21
Shared/Models/TblBranch.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblBranch
{
public string? BranchName { get; set; }
public string BranchId { get; set; } = null!;
public string? Address { get; set; }
public string? City { get; set; }
public string? StateOrProvince { get; set; }
public string? BranchTelephone { get; set; }
public DateTime LastModified { get; set; }
}

15
Shared/Models/TblBrand.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblBrand
{
public string Id { get; set; } = null!;
public string? Brand { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

19
Shared/Models/TblCancelledTransaction.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCancelledTransaction
{
public string? Transno { get; set; }
public DateTime? DateCancelled { get; set; }
public string? CancelledBy { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

39
Shared/Models/TblCart.cs

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCart
{
public string? Transno { get; set; }
public string? Id { get; set; }
public int? Quantity { get; set; }
public DateTime? Date { get; set; }
public decimal? Price { get; set; }
public string? Cashier { get; set; }
public string? Status { get; set; }
public decimal? Total { get; set; }
public string? BranchId { get; set; }
public string? Unit { get; set; }
public decimal? Costprice { get; set; }
public decimal? Tendered { get; set; }
public decimal? Balance { get; set; }
public decimal? ValueAddTax { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

15
Shared/Models/TblCategory.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCategory
{
public string Id { get; set; } = null!;
public string? Category { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

23
Shared/Models/TblCompanyDetail.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCompanyDetail
{
public string? CompanyName { get; set; }
public string? Address { get; set; }
public string? Website { get; set; }
public string? Email { get; set; }
public string Tin { get; set; } = null!;
public string? MainTelephone { get; set; }
public string? Vatno { get; set; }
public DateTime LastModified { get; set; }
}

37
Shared/Models/TblCustomer.cs

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCustomer
{
public string CustomerId { get; set; } = null!;
public string? Firstname { get; set; }
public string? Surname { get; set; }
public string? Address { get; set; }
public string? Telephone { get; set; }
public DateTime? DateAdded { get; set; }
public string? BranchId { get; set; }
public string? Status { get; set; }
public string? Tin { get; set; }
public DateTime? DateExit { get; set; } = new DateTime(2000, 01, 01);
public string? Email { get; set; }
public string? FinancialStatus { get; set; }
public string? NameKey1 { get; set; }
public string? NameKey2 { get; set; }
public DateTime LastModified { get; set; }
}

17
Shared/Models/TblCustomerPurchase.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblCustomerPurchase
{
public string? CustomerId { get; set; }
public string? TransactionId { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

22
Shared/Models/TblDeliveryDetail.cs

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblDeliveryDetail
{
public string? DeliveryId { get; set; }
public string? Pcode { get; set; }
public int? Quantity { get; set; }
public string? Unit { get; set; }
public decimal? Cost { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
public string? BranchId { get; set; }
}

27
Shared/Models/TblDeliveryHead.cs

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblDeliveryHead
{
public string DeliveryId { get; set; } = null!;
public string? GeneratedBy { get; set; }
public DateTime? DateInitiated { get; set; }
public DateTime? DateCompleted { get; set; }
public string? Destination { get; set; }
public string? CustomerId { get; set; }
public decimal? TotalCost { get; set; }
public string? Status { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

26
Shared/Models/TblDeliveryRecipient.cs

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblDeliveryRecipient
{
public string DeliveryId { get; set; } = null!;
public string? Fullname { get; set; }
public string? Address { get; set; }
public string? Telephone { get; set; }
public string? Email { get; set; }
public string? CustomerId { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public DateTime LastModified { get; set; }
public string? BranchId { get; set; }
}

21
Shared/Models/TblDiscountLog.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblDiscountLog
{
public string? ReceiptId { get; set; }
public string? Cashier { get; set; }
public DateTime? Date { get; set; }
public decimal? Discount { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

35
Shared/Models/TblDriver.cs

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblDriver
{
public string DriverId { get; set; } = null!;
public string? Firstname { get; set; }
public string? Surname { get; set; }
public string? Middlename { get; set; }
public DateTime? DateOfBirth { get; set; }
public string? Address1 { get; set; }
public string? Address2 { get; set; }
public string? Telephone { get; set; }
public string? Email { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? BranchId { get; set; }
public string? Status { get; set; }
public DateTime LastModified { get; set; }
}

41
Shared/Models/TblHeldTransaction.cs

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblHeldTransaction
{
public string? ProductId { get; set; }
public int? Quantity { get; set; }
public DateTime? Date { get; set; }
public decimal? Price { get; set; }
public string? Cashier { get; set; }
public string? Status { get; set; }
public decimal? Total { get; set; }
public string? BranchId { get; set; }
public string? Unit { get; set; }
public decimal? Costprice { get; set; }
public decimal? Discount { get; set; }
public string? InvoiceId { get; set; }
public string? CustomerId { get; set; }
public string CountId { get; set; } = null!;
public string TransactionId { get; set; } = null!;
public string? Distinctive { get; set; }
public DateTime LastModified { get; set; }
}

17
Shared/Models/TblInventory.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblInventory
{
public string? Pcode { get; set; }
public int? Quantity { get; set; } = 0;
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

19
Shared/Models/TblInventoryEntry.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblInventoryEntry
{
public string? Pcode { get; set; }
public int? Quantity { get; set; } = 0;
public DateTime? Date { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

31
Shared/Models/TblInvoice.cs

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblInvoice
{
public string? InvoiceId { get; set; }
public string? Pcode { get; set; }
public int? Quantity { get; set; } = 0;
public decimal? Unitprice { get; set; } = 0;
public string? Unit { get; set; }
public decimal? Totalprice { get; set; } = 0;
public DateTime? DateGenerated { get; set; }
public string? Status { get; set; }
public string? GeneratedBy { get; set; }
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

21
Shared/Models/TblPriceChange.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblPriceChange
{
public string? Pcode { get; set; }
public decimal? PreviousPrice { get; set; } = 0;
public decimal? CurrentPrice { get; set; } = 0;
public DateTime? ChangeDate { get; set; } = new DateTime(2000,01,01);
public string? BranchId { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

33
Shared/Models/TblProduct.cs

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblProduct
{
public string? Pcode { get; set; }
public string? Barcode { get; set; }
public string? Pdesc { get; set; }
public string? Bid { get; set; }
public string? Cid { get; set; }
public decimal? Price { get; set; } = 0;
public decimal? Costprice { get; set; } = 0;
public string? BaseUnit { get; set; }
public string? ProductName { get; set; }
public string? BranchId { get; set; }
public string? Status { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

21
Shared/Models/TblTruck.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblTruck
{
public string TruckId { get; set; } = null!;
public string? LicensePlate { get; set; }
public string? Brand { get; set; }
public string? Driver { get; set; }
public decimal? Weight { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

21
Shared/Models/TblTruckAssignment.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblTruckAssignment
{
public string? OrderId { get; set; }
public decimal? Cost { get; set; }
public string? TruckId { get; set; }
public string? Status { get; set; }
public DateTime? DateAssigned { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

19
Shared/Models/TblTruckDriverMapping.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblTruckDriverMapping
{
public string? TruckId { get; set; }
public string? DriverId { get; set; }
public DateTime? DateEntry { get; set; }
public string? Operation { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

19
Shared/Models/TblTruckInventory.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblTruckInventory
{
public string? TruckId { get; set; }
public string? Pcode { get; set; }
public int? Quantity { get; set; }
public string? Unit { get; set; }
public string CountId { get; set; } = null!;
public DateTime LastModified { get; set; }
}

35
Shared/Models/TblUser.cs

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblUser
{
public string Username { get; set; } = null!;
public string? Password { get; set; } = string.Empty;
public string? Firstname { get; set; } = string.Empty;
public string? Surname { get; set; } = string.Empty;
public string? StreetAddress1 { get; set; } = string.Empty;
public string? StreetAddress2 { get; set; } = string.Empty;
public string? City { get; set; } = string.Empty;
public string? StateOrProvince { get; set; } = string.Empty;
public string? Telephone { get; set; } = string.Empty;
public string? Email { get; set; } = string.Empty;
public string? AccessLevel { get; set; } = string.Empty;
public DateTime? LastLogin { get; set; } = new DateTime(2000, 01, 01);
public string? BranchId { get; set; } = string.Empty;
public DateTime LastModified { get; set; }
}

15
Shared/Models/TblUserActivity.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class TblUserActivity
{
public string Username { get; set; } = null!;
public DateTime? LastActive { get; set; }
public string? Workstation { get; set; }
public DateTime LastModified { get; set; }
}

19
Shared/Models/UnitOfMeasure.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Cloud.Shared.Models;
public partial class UnitOfMeasure
{
public string UnitCode { get; set; } = null!;
public string? Unitname { get; set; }
public string? Unitshort { get; set; }
public string? Status { get; set; }
public string? BranchId { get; set; }
public DateTime LastModified { get; set; }
}

239
Shared/ServiceRepo/TokenService.cs

@ -0,0 +1,239 @@
using Biskilog_Cloud.Shared.ClientContractModels;
using Biskilog_Cloud.Shared.Enums;
using Biskilog_Cloud.Shared.Interfaces;
using Blazored.LocalStorage;
using Blazored.SessionStorage;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Biskilog_Cloud.ServiceRepo
{
public class TokenService : ITokenService
{
private IConfiguration m_configuration { get; }
private readonly ISessionStorageService m_sessionStorage;
private readonly ILocalStorageService m_localStorage;
public TokenService(IConfiguration a_configuration, ISessionStorageService a_sessionStorage = null, ILocalStorageService a_localStorage = null)
{
m_configuration = a_configuration;
m_sessionStorage = a_sessionStorage;
m_localStorage = a_localStorage;
}
/// <summary>
/// Validates a user access token
/// </summary>
/// <returns>AuthEnums.Valid if token is a valid and unexpired token</returns>
public AuthEnums ValidateToken(string a_token)
{
try
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
if (jwtToken.ValidFrom <= DateTime.Now && jwtToken.ValidTo > DateTime.Now)
return AuthEnums.Valid;
return AuthEnums.Expired;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return AuthEnums.Invalid;
}
}
/// <summary>
/// Generates an access token based on the user
/// </summary>
/// <returns>A tokenized string</returns>
public string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison)
{
try
{
//create claims details based on the user information
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
new Claim("ContractStart",a_clientContract.StartDate !.Value.ToString()),
new Claim("ContractEnd",a_clientContract.EndDate!.Value.ToString()),
new Claim("UserId", a_user.UserId.ToString()),
new Claim("Username", a_user.Username.ToString()),
new Claim("DbId",a_database.DbNo.ToString()),
new Claim("ComparisonMode",a_comparison.ToString()),
new Claim("BranchId",a_business[0].ToString()),
new Claim("BranchAccess",string.Join(", ", a_business.ToArray())),
new Claim("ClientId", a_user.ClientId.ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(m_configuration["Jwt:Key"]!));
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(m_configuration["Jwt:Issuer"], m_configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(14), signingCredentials: signIn);
return $"{new JwtSecurityTokenHandler().WriteToken(token)}";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return AuthEnums.Error.ToString();
}
}
/// <summary>
///Deserializes the token string if valid to return the specified user role id in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>RoleId</returns>
public int? GetDatabaseIdFromToken(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return int.Parse(jwtToken.Claims.First(claim => claim.Type == "DbId").Value);
}
return null;
}
/// <summary>
///Deserializes the token string if valid to return the specified user id in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>UserId</returns>
public int? GetUserIdFromToken(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return int.Parse(jwtToken.Claims.First(claim => claim.Type == "UserId").Value);
}
return null;
}
/// <summary>
///Deserializes the token string if valid to return the specified username in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetUserNameFromToken(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "Username").Value;
}
return null;
}
/// <summary>
///Deserializes the token string if valid to return the specified branchId in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetBaseBranch(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "BranchId").Value;
}
return null;
}
public bool? GetComparison(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return bool.Parse(jwtToken.Claims.First(claim => claim.Type == "ComparisonMode").Value);
}
return null;
}
/// <summary>
///Deserializes the token string if valid to return the specified list of branches a user has access to in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetAllBranch(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "BranchAccess").Value;
}
return null;
}
/// <summary>
/// Return a specified list of branches a user has access if comparison mode is set otherwise returns only the
/// active branch on the list
/// </summary>
/// <param name="a_token"></param>
/// <returns></returns>
public IEnumerable<string> BranchIds(string a_token)
{
List<string> branchIds = new List<string>();
if (ValidateToken(a_token) == AuthEnums.Valid)
{
bool comparison = GetComparison(a_token)!.Value;
if (comparison)
{
string? branches = GetAllBranch(a_token);
if (branches != null)
{
string[] branchArray = branches!.Split();
branchIds.AddRange(branchArray);
}
}
else
{
string? baseBranch = GetBaseBranch(a_token);
branchIds.Add(baseBranch!);
}
}
return branchIds.AsEnumerable();
}
public async Task SetToken(string a_token, bool a_remember)
{
if (a_remember)
{
await m_localStorage.SetItemAsStringAsync("token", $"Bearer {a_token}");
}
else
{
await m_sessionStorage.SetItemAsStringAsync("token", $"Bearer {a_token}");
}
}
public async Task<string> GetToken()
{
string token = await m_localStorage.GetItemAsStringAsync("token");
if (String.IsNullOrEmpty(token))
{
token = await m_sessionStorage.GetItemAsStringAsync("token");
}
return token;
}
public async Task ClearToken()
{
await m_localStorage.ClearAsync();
await m_sessionStorage.ClearAsync();
}
public async Task<bool> IsTokenSet()
{
return await m_localStorage.ContainKeyAsync("token") || await m_sessionStorage.ContainKeyAsync("token");
}
}
}

4
Shared/SharedClass.cs

@ -0,0 +1,4 @@
/* Shared classes can be referenced by both the Client and Server */
public class Shared
{
}
Loading…
Cancel
Save