Browse Source

inital commit

master
barhen-pfw 1 year ago
parent
commit
41bbb2e179
  1. 25
      Cloud_Manager.sln
  2. 1388
      Cloud_Manager/BiskAcdbContext.cs
  3. 280
      Cloud_Manager/BiskilogContext.cs
  4. 18
      Cloud_Manager/CloudHubs/SalesHub.cs
  5. 16
      Cloud_Manager/Cloud_Manager.csproj
  6. 151
      Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs
  7. 144
      Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs
  8. 145
      Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs
  9. 33
      Cloud_Manager/Controllers/WeatherForecastController.cs
  10. 11
      Cloud_Manager/Models/ClientContractModels/Authtype.cs
  11. 21
      Cloud_Manager/Models/ClientContractModels/Clientbusiness.cs
  12. 15
      Cloud_Manager/Models/ClientContractModels/Clientinfo.cs
  13. 21
      Cloud_Manager/Models/ClientContractModels/Contract.cs
  14. 16
      Cloud_Manager/Models/ClientContractModels/Databasemap.cs
  15. 16
      Cloud_Manager/Models/ClientContractModels/Siteaccesspermission.cs
  16. 27
      Cloud_Manager/Models/ClientContractModels/Userauth.cs
  17. 16
      Cloud_Manager/Models/CustomModels/CancelledSales.cs
  18. 15
      Cloud_Manager/Models/CustomModels/CustomerAccounts.cs
  19. 29
      Cloud_Manager/Models/CustomModels/MostPurchaseItem.cs
  20. 18
      Cloud_Manager/Models/CustomModels/ProductItem.cs
  21. 23
      Cloud_Manager/Models/CustomModels/ProductPriceChange.cs
  22. 26
      Cloud_Manager/Models/CustomModels/ProductUnits.cs
  23. 22
      Cloud_Manager/Models/CustomModels/SaleItem.cs
  24. 14
      Cloud_Manager/Models/CustomModels/SyncTimestamp.cs
  25. 16
      Cloud_Manager/Models/CustomModels/TradeSummary.cs
  26. 21
      Cloud_Manager/Models/CustomModels/WeeklySaleItem.cs
  27. 17
      Cloud_Manager/Models/Enums/AuthEnums.cs
  28. 14
      Cloud_Manager/Models/Enums/ConnectionEnums.cs
  29. 86
      Cloud_Manager/Models/Interfaces/IAnalytics.cs
  30. 20
      Cloud_Manager/Models/Interfaces/IAuthService.cs
  31. 28
      Cloud_Manager/Models/Interfaces/ICompanyInfo.cs
  32. 24
      Cloud_Manager/Models/Interfaces/IConnectionService.cs
  33. 12
      Cloud_Manager/Models/Interfaces/ICustomer.cs
  34. 15
      Cloud_Manager/Models/Interfaces/IMainInterface.cs
  35. 44
      Cloud_Manager/Models/Interfaces/IProducts.cs
  36. 10
      Cloud_Manager/Models/Interfaces/ISalesHub.cs
  37. 36
      Cloud_Manager/Models/Interfaces/ISalesInterface.cs
  38. 18
      Cloud_Manager/Models/Interfaces/ITokenService.cs
  39. 16
      Cloud_Manager/Models/Interfaces/IUser.cs
  40. 21
      Cloud_Manager/Models/POSModels/Creditpurchase.cs
  41. 25
      Cloud_Manager/Models/POSModels/Customeraccount.cs
  42. 21
      Cloud_Manager/Models/POSModels/Productaltunit.cs
  43. 15
      Cloud_Manager/Models/POSModels/Restocklevel.cs
  44. 19
      Cloud_Manager/Models/POSModels/Systemuserrole.cs
  45. 19
      Cloud_Manager/Models/POSModels/Tblbranch.cs
  46. 13
      Cloud_Manager/Models/POSModels/Tblbrand.cs
  47. 17
      Cloud_Manager/Models/POSModels/Tblcancelledtransaction.cs
  48. 35
      Cloud_Manager/Models/POSModels/Tblcart.cs
  49. 13
      Cloud_Manager/Models/POSModels/Tblcategory.cs
  50. 21
      Cloud_Manager/Models/POSModels/Tblcompanydetail.cs
  51. 35
      Cloud_Manager/Models/POSModels/Tblcustomer.cs
  52. 15
      Cloud_Manager/Models/POSModels/Tblcustomerpurchase.cs
  53. 21
      Cloud_Manager/Models/POSModels/Tbldeliverydetail.cs
  54. 25
      Cloud_Manager/Models/POSModels/Tbldeliveryhead.cs
  55. 25
      Cloud_Manager/Models/POSModels/Tbldeliveryrecipient.cs
  56. 19
      Cloud_Manager/Models/POSModels/Tbldiscountlog.cs
  57. 33
      Cloud_Manager/Models/POSModels/Tbldriver.cs
  58. 15
      Cloud_Manager/Models/POSModels/Tblinventory.cs
  59. 17
      Cloud_Manager/Models/POSModels/Tblinventoryentry.cs
  60. 29
      Cloud_Manager/Models/POSModels/Tblinvoice.cs
  61. 19
      Cloud_Manager/Models/POSModels/Tblpricechange.cs
  62. 31
      Cloud_Manager/Models/POSModels/Tblproduct.cs
  63. 13
      Cloud_Manager/Models/POSModels/Tblsyncinfo.cs
  64. 19
      Cloud_Manager/Models/POSModels/Tbltruck.cs
  65. 19
      Cloud_Manager/Models/POSModels/TbltruckDrivermapping.cs
  66. 21
      Cloud_Manager/Models/POSModels/Tbltruckassignment.cs
  67. 19
      Cloud_Manager/Models/POSModels/Tbltruckinventory.cs
  68. 33
      Cloud_Manager/Models/POSModels/Tbluser.cs
  69. 23
      Cloud_Manager/Models/POSModels/Tbstock.cs
  70. 17
      Cloud_Manager/Models/POSModels/Unitofmeasure.cs
  71. 199
      Cloud_Manager/Models/ServiceRepo/TokenService.cs
  72. 103
      Cloud_Manager/Program.cs
  73. 41
      Cloud_Manager/Properties/launchSettings.json
  74. 146
      Cloud_Manager/Services/AuthenticationService.cs
  75. 227
      Cloud_Manager/Services/CompanyService.cs
  76. 50
      Cloud_Manager/Services/ConnectionService.cs
  77. 89
      Cloud_Manager/Services/CustomerService.cs
  78. 411
      Cloud_Manager/Services/ProductRepo.cs
  79. 381
      Cloud_Manager/Services/SalesService.cs
  80. 59
      Cloud_Manager/Services/UserService.cs
  81. 13
      Cloud_Manager/WeatherForecast.cs
  82. 8
      Cloud_Manager/appsettings.Development.json
  83. 18
      Cloud_Manager/appsettings.json

25
Cloud_Manager.sln

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33530.505
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cloud_Manager", "Cloud_Manager\Cloud_Manager.csproj", "{D2BD9F08-9AD5-4ECB-B60F-C507F6DB0B22}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D2BD9F08-9AD5-4ECB-B60F-C507F6DB0B22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D2BD9F08-9AD5-4ECB-B60F-C507F6DB0B22}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2BD9F08-9AD5-4ECB-B60F-C507F6DB0B22}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2BD9F08-9AD5-4ECB-B60F-C507F6DB0B22}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B00F402F-EC33-41CE-9AEE-FB56B36DEEE3}
EndGlobalSection
EndGlobal

1388
Cloud_Manager/BiskAcdbContext.cs

File diff suppressed because it is too large

280
Cloud_Manager/BiskilogContext.cs

@ -0,0 +1,280 @@
using System;
using System.Collections.Generic;
using Cloud_Manager.Models.ClientContractModels;
using Microsoft.EntityFrameworkCore;
namespace Cloud_Manager;
/// <summary>
/// This is the main EF DbContext for the Biskilog Accounting
/// </summary>
public partial class BiskilogContext : DbContext
{
public BiskilogContext()
{
}
public BiskilogContext(DbContextOptions<BiskilogContext> options)
: base(options)
{
}
public virtual DbSet<Authtype> Authtypes { get; set; }
public virtual DbSet<Clientbusiness> Clientbusinesses { get; set; }
public virtual DbSet<Clientinfo> Clientinfos { get; set; }
public virtual DbSet<Contract> Contracts { get; set; }
public virtual DbSet<Databasemap> Databasemaps { get; set; }
public virtual DbSet<Siteaccesspermission> Siteaccesspermissions { get; set; }
public virtual DbSet<Userauth> Userauths { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
modelBuilder.Entity<Authtype>(entity =>
{
entity.HasKey(e => e.Id).HasName("PRIMARY");
entity
.ToTable("authtypes")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.Property(e => e.Id)
.HasColumnType("int(11)")
.HasColumnName("id");
entity.Property(e => e.Type)
.HasMaxLength(50)
.HasColumnName("type")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
});
modelBuilder.Entity<Clientbusiness>(entity =>
{
entity.HasKey(e => new { e.BusinessId, e.ClientId })
.HasName("PRIMARY")
.HasAnnotation("MySql:IndexPrefixLength", new[] { 0, 0 });
entity
.ToTable("clientbusiness")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.Property(e => e.BusinessId)
.HasComment("there could be multiple branches of the same business")
.HasColumnType("int(11)")
.HasColumnName("businessId");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientID");
entity.Property(e => e.BiskilogVersion)
.HasMaxLength(50)
.HasDefaultValueSql("''")
.HasColumnName("biskilog_version")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.BusinessName)
.HasMaxLength(50)
.HasDefaultValueSql("''")
.HasColumnName("business_name")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.DateJoined)
.HasDefaultValueSql("current_timestamp()")
.HasColumnType("datetime")
.HasColumnName("date_joined");
entity.Property(e => e.BusinessExternalId)
.HasMaxLength(50)
.HasDefaultValueSql("''")
.HasColumnName("businessExternalId")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
});
modelBuilder.Entity<Clientinfo>(entity =>
{
entity.HasKey(e => e.ClientId).HasName("PRIMARY");
entity
.ToTable("clientinfo")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientID");
entity.Property(e => e.Email)
.HasMaxLength(200)
.HasColumnName("email")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.Fullname)
.HasMaxLength(200)
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.PhoneNumber)
.HasMaxLength(200)
.HasColumnName("phoneNumber")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
});
modelBuilder.Entity<Contract>(entity =>
{
entity.HasKey(e => e.ContractId).HasName("PRIMARY");
entity
.ToTable("contracts")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.HasIndex(e => new { e.ClientId, e.BusinessId }, "clientId_businessId").IsUnique();
entity.Property(e => e.ContractId)
.HasColumnType("int(11)")
.HasColumnName("contractId");
entity.Property(e => e.Bill)
.HasPrecision(18, 2)
.HasColumnName("bill");
entity.Property(e => e.BusinessId)
.HasColumnType("int(11)")
.HasColumnName("businessId");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientId");
entity.Property(e => e.Comments)
.HasColumnType("text")
.HasColumnName("comments")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.EndDate)
.HasColumnType("datetime")
.HasColumnName("end_date");
entity.Property(e => e.StartDate)
.HasColumnType("datetime")
.HasColumnName("start_date");
});
modelBuilder.Entity<Databasemap>(entity =>
{
entity.HasKey(e => e.DbNo).HasName("PRIMARY");
entity
.ToTable("databasemap")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.HasIndex(e => e.ClientId, "businessId").IsUnique();
entity.Property(e => e.DbNo)
.HasColumnType("int(11)")
.HasColumnName("db_no");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientID");
entity.Property(e => e.DbName)
.HasMaxLength(50)
.HasDefaultValueSql("''")
.HasColumnName("db_name")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.Domain)
.HasMaxLength(50)
.HasDefaultValueSql("''")
.HasColumnName("domain")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.LastSyncDate)
.HasColumnType("datetime")
.HasColumnName("last_sync_date");
});
modelBuilder.Entity<Siteaccesspermission>(entity =>
{
entity.HasKey(e => new { e.UserId, e.BusinessId, e.ClientId })
.HasName("PRIMARY")
.HasAnnotation("MySql:IndexPrefixLength", new[] { 0, 0, 0 });
entity
.ToTable("siteaccesspermission")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.Property(e => e.UserId)
.HasColumnType("int(11)")
.HasColumnName("userID");
entity.Property(e => e.BusinessId)
.HasComment("businessIds could also been seen as branchID")
.HasColumnType("int(11)")
.HasColumnName("businessId");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientId");
});
modelBuilder.Entity<Userauth>(entity =>
{
entity.HasKey(e => e.UserId).HasName("PRIMARY");
entity
.ToTable("userauth")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.HasIndex(e => e.AuthType, "authType");
entity.HasIndex(e => new { e.ClientId, e.Username, e.Email }, "clientId_username_email").IsUnique();
entity.Property(e => e.UserId)
.HasColumnType("int(11)")
.HasColumnName("userId");
entity.Property(e => e.AuthType)
.HasColumnType("int(11)")
.HasColumnName("authType");
entity.Property(e => e.ClientId)
.HasColumnType("int(11)")
.HasColumnName("clientId");
entity.Property(e => e.Email)
.HasMaxLength(200)
.HasColumnName("email")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.Isactive)
.HasColumnType("bit(1)")
.HasColumnName("isactive");
entity.Property(e => e.Isowner)
.HasColumnType("bit(1)")
.HasColumnName("isowner");
entity.Property(e => e.LastLogin)
.HasColumnType("datetime")
.HasColumnName("last_login");
entity.Property(e => e.Passsword)
.HasMaxLength(200)
.HasColumnName("passsword")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.PhoneNumber)
.HasMaxLength(50)
.HasColumnName("phoneNumber")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
entity.Property(e => e.Username)
.HasMaxLength(30)
.HasColumnName("username")
.UseCollation("utf8mb4_general_ci")
.HasCharSet("utf8mb4");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

18
Cloud_Manager/CloudHubs/SalesHub.cs

@ -0,0 +1,18 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Interfaces;
using Microsoft.AspNetCore.SignalR;
namespace Cloud_Manager.CloudHubs
{
public class SalesHub : Hub<ISalesHub>
{
public async Task JoinCompanyGroup(string a_companyId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, a_companyId);
}
public async Task AddTransaction(string a_companyId, SaleItem a_sale)
{
await Clients.OthersInGroup(a_companyId).TransactionMade(a_sale);
}
}
}

16
Cloud_Manager/Cloud_Manager.csproj

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.3" />
</ItemGroup>
</Project>

151
Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs

@ -0,0 +1,151 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Runtime.InteropServices;
namespace Cloud_Manager.Controllers.SyncControllers
{
[Route("api/[controller]")]
[ApiController]
public class SyncCompanyInfoController : ControllerBase
{
private readonly ISalesInterface m_salesService;
private readonly ICustomer m_customer;
private readonly IUser m_users;
private readonly ICompanyInfo m_companyInfo;
public SyncCompanyInfoController(ISalesInterface a_salesService, ICustomer customer, IUser users, ICompanyInfo a_companyInfo)
{
m_salesService = a_salesService;
m_customer = customer;
m_users = users;
m_companyInfo = a_companyInfo;
}
// GET: api/<SyncCompanyInfoController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName)
{
return m_salesService.GetLastSyncDate(a_tableName);
}
// Post: api/<SyncCompanyInfoController>
[Authorize]
[HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp)
{
m_salesService.SetLastSyncDate(a_timestamp.TableName, a_timestamp.Timestamp);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of SystemUserRoles rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/SystemRoles")]
public async Task SyncSyatemRolesAsync(List<Systemuserrole> a_item)
{
await m_companyInfo.SyncSystemRoles(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblDriver rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDriver")]
public async Task SyncDriversAsync(List<Tbldriver> a_item)
{
await m_companyInfo.SyncDriverDetails(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of CompanyDetails rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcompanydetails")]
public async Task SyncCompanyAsync(List<Tblcompanydetail> a_item)
{
await m_companyInfo.SyncCompanyDetails(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblUsers rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblusers")]
public async Task SyncUsersAsync(List<Tbluser> a_item)
{
await m_users.SyncUserAsync(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of Trucks rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbltrucks")]
public async Task SyncTrucksAsync(List<Tbltruck> a_item)
{
await m_companyInfo.SyncTrucks(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblBranch rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblbranch")]
public async Task SyncBranchAsync(List<Tblbranch> a_item)
{
await m_companyInfo.SyncBranches(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblCustomers rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcustomers")]
public async Task SyncCustomersAsync(List<Tblcustomer> a_item)
{
await m_customer.SyncCustomers(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblTruck Inventory rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbltruckinventory")]
public async Task SyncTruckInventoryAsync(List<Tbltruckinventory> a_item)
{
await m_companyInfo.SyncTruckInventory(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblTruckAssignment rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblTruckAssignment")]
public async Task SyncTruckAssignmentSync(List<Tbltruckassignment> a_item)
{
await m_companyInfo.SyncTruckAssignments(a_item);
}
// POST api/<SyncCompanyInfoController>
/// <summary>
/// Endpoint to publish a collection of TblDriverMapping rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbldrivermappings")]
public async Task SyncTruckDriverMappingSync(List<TbltruckDrivermapping> a_item)
{
await m_companyInfo.SyncTruckMappings(a_item);
}
}
}

144
Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs

@ -0,0 +1,144 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Cloud_Manager.Controllers.SyncControllers
{
[Route("api/[controller]")]
[ApiController]
public class SyncProductsController : ControllerBase
{
private readonly IProduct m_productService;
public SyncProductsController(IProduct a_productService)
{
m_productService = a_productService;
}
// GET: api/<SyncProductsController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName)
{
return m_productService.GetLastSyncDate(a_tableName);
}
// Post: api/<SyncProductsController>
[Authorize]
[HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp)
{
m_productService.SetLastSyncDate(a_timestamp.TableName, a_timestamp.Timestamp);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TblProduct rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblProducts")]
public async Task SyncProductsAsync(List<Tblproduct> a_item)
{
await m_productService.SyncProducts(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TblInventory rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblInventory")]
public async Task SyncInventoryAsync(List<Tblinventory> a_item)
{
await m_productService.SyncInventory(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of Restock rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblRestock")]
public async Task SyncRestockAsync(List<Restocklevel> a_item)
{
await m_productService.SyncRestockAsync(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TblInventoryEntries rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblInventoryentry")]
public async Task SyncInventoryEntriesAsync(List<Tblinventoryentry> a_item)
{
await m_productService.SyncInventoryEntries(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of PriceChanges rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tlpricechanges")]
public async Task SyncPriceChangesAsync(List<Tblpricechange> a_item)
{
await m_productService.SyncPriceChanges(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of ProductAltUnit rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblProductAltUnit")]
public async Task SyncProductAltUnitAsync(List<Productaltunit> a_item)
{
await m_productService.SyncProductAltUnit(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TbStock rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblStock")]
public async Task SyncStockAsync(List<Tbstock> a_item)
{
await m_productService.SyncStockAsync(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TblBrands rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblbrands")]
public async Task SyncBrandsAsync(List<Tblbrand> a_item)
{
await m_productService.SyncBrandsAsync(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of TblCategory rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCategories")]
public async Task SyncCategoriesAsync(List<Tblcategory> a_item)
{
await m_productService.SyncCategoriesAsync(a_item);
}
// POST api/<SyncProductsController>
/// <summary>
/// Endpoint to publish a collection of UnitOfMeasure rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblunitofmeasure")]
public async Task SyncUnitMeasureAsync(List<Unitofmeasure> a_item)
{
await m_productService.SyncUnitOfMeasureAsync(a_item);
}
}
}

145
Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs

@ -0,0 +1,145 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Cloud_Manager.Controllers.SyncControllers
{
[Route("api/[controller]")]
[ApiController]
public class SyncSalesController : ControllerBase
{
private readonly ISalesInterface m_salesService;
public SyncSalesController(ISalesInterface a_salesService)
{
m_salesService = a_salesService;
}
// GET: api/<SyncSalesController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName)
{
return m_salesService.GetLastSyncDate(a_tableName);
}
// Post: api/<SyncSalesController>
[Authorize]
[HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp)
{
m_salesService.SetLastSyncDate(a_timestamp.TableName, a_timestamp.Timestamp);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of TblCart rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCart")]
public async Task SyncSalesAsync(List<Tblcart> a_item)
{
await m_salesService.SyncCart(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of TblCancelledTransation rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcancelledtransaction")]
public async Task SyncCancelledTransactionAsync(List<Tblcancelledtransaction> a_item)
{
await m_salesService.SyncCancelledTransaction(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of TblInvoice rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblinvoice")]
public async Task SyncInvoiceAsync(List<Tblinvoice> a_item)
{
await m_salesService.SyncInvoice(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of CreditPurchase rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCreditpurchase")]
public async Task SyncCreditPurchaseAsync(List<Creditpurchase> a_item)
{
await m_salesService.SyncCreditPurchase(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Customer Account rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCustomerAccount")]
public async Task SyncCustomerAccountAsync(List<Customeraccount> a_item)
{
await m_salesService.SyncCustomerAccount(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Customer Purchase rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/CustomerPurchase")]
public async Task SyncCustomerPurchaseAsync(List<Tblcustomerpurchase> a_item)
{
await m_salesService.SyncCustomerPurchase(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Discount logs rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/DiscountLogs")]
public async Task SyncDiscountLogsAsync(List<Tbldiscountlog> a_item)
{
await m_salesService.SyncDiscountLogs(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Delivery Head rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliveryhead")]
public async Task SyncDeliveryHeadAsync(List<Tbldeliveryhead> a_item)
{
await m_salesService.SyncDeliveryHead(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Delivery Details rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliverydetails")]
public async Task SyncDeliveryDetailsAsync(List<Tbldeliverydetail> a_item)
{
await m_salesService.SyncDeliveryDetails(a_item);
}
// POST api/<SyncSalesController>
/// <summary>
/// Endpoint to publish a collection of Delivery Recipient rows to the cloud
/// </summary>
/// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliveryrecipient")]
public async Task SyncDeliveryRecipientAsync(List<Tbldeliveryrecipient> a_item)
{
await m_salesService.SyncDeliveryRecipients(a_item);
}
}
}

33
Cloud_Manager/Controllers/WeatherForecastController.cs

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
namespace Cloud_Manager.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();
}
}
}

11
Cloud_Manager/Models/ClientContractModels/Authtype.cs

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

21
Cloud_Manager/Models/ClientContractModels/Clientbusiness.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/ClientContractModels/Clientinfo.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/ClientContractModels/Contract.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/ClientContractModels/Databasemap.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/ClientContractModels/Siteaccesspermission.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/ClientContractModels/Userauth.cs

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/CancelledSales.cs

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

15
Cloud_Manager/Models/CustomModels/CustomerAccounts.cs

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

29
Cloud_Manager/Models/CustomModels/MostPurchaseItem.cs

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/ProductItem.cs

@ -0,0 +1,18 @@
using Cloud_Manager.Models.POSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/ProductPriceChange.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/ProductUnits.cs

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/SaleItem.cs

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/SyncTimestamp.cs

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

16
Cloud_Manager/Models/CustomModels/TradeSummary.cs

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/CustomModels/WeeklySaleItem.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/Enums/AuthEnums.cs

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

14
Cloud_Manager/Models/Enums/ConnectionEnums.cs

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

86
Cloud_Manager/Models/Interfaces/IAnalytics.cs

@ -0,0 +1,86 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.POSModels;
namespace Cloud_Manager.Models.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);
}
}

20
Cloud_Manager/Models/Interfaces/IAuthService.cs

@ -0,0 +1,20 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.ClientContractModels;
namespace Cloud_Manager.Models.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);
}
}

28
Cloud_Manager/Models/Interfaces/ICompanyInfo.cs

@ -0,0 +1,28 @@
using Cloud_Manager.Models.POSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.Interfaces
{
public interface ICompanyInfo
{
IEnumerable<Tblbranch> FetchBranches();
Task<Tblcompanydetail> GetCompanyInfoAsync();
Task<IEnumerable<Tblbranch>> GetBranches();
string GetCompanyName();
string GetBranchName(string a_branchId);
Task SyncBranches(List<Tblbranch> a_branches);
Task SyncCompanyDetails(List<Tblcompanydetail> a_details);
Task SyncDriverDetails(List<Tbldriver> a_details);
Task SyncSystemRoles(List<Systemuserrole> a_roles);
Task SyncTrucks(List<Tbltruck> a_trucks);
Task SyncTruckAssignments(List<Tbltruckassignment> a_assignments);
Task SyncTruckMappings(List<TbltruckDrivermapping> a_mapping);
Task SyncTruckInventory(List<Tbltruckinventory> a_inventories);
DateTime GetLastSyncDate(string a_tablename);
void SetLastSyncDate(string a_tableName, DateTime a_timestamp);
}
}

24
Cloud_Manager/Models/Interfaces/IConnectionService.cs

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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
Cloud_Manager/Models/Interfaces/ICustomer.cs

@ -0,0 +1,12 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.POSModels;
namespace Cloud_Manager.Models.Interfaces
{
public interface ICustomer
{
IEnumerable<CustomerAccounts> FetchCustomers();
Task<IEnumerable<CustomerAccounts>> GetCustomers();
Task SyncCustomers(List<Tblcustomer> a_details);
}
}

15
Cloud_Manager/Models/Interfaces/IMainInterface.cs

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

44
Cloud_Manager/Models/Interfaces/IProducts.cs

@ -0,0 +1,44 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.POSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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 SyncProducts(List<Tblproduct> a_item);
Task SyncInventory(List<Tblinventory> a_item);
Task SyncInventoryEntries(List<Tblinventoryentry> a_item);
Task SyncPriceChanges(List<Tblpricechange> a_items);
Task SyncProductAltUnit(List<Productaltunit> a_items);
Task SyncRestockAsync(List<Restocklevel> a_items);
Task SyncUnitOfMeasureAsync(List<Unitofmeasure> a_items);
Task SyncStockAsync(List<Tbstock> a_items);
Task SyncBrandsAsync(List<Tblbrand> a_items);
Task SyncCategoriesAsync(List<Tblcategory> a_items);
DateTime GetLastSyncDate(string a_tablename);
void SetLastSyncDate(string a_tableName, DateTime a_timestamp);
}
}

10
Cloud_Manager/Models/Interfaces/ISalesHub.cs

@ -0,0 +1,10 @@
using Cloud_Manager.Models.CustomModels;
namespace Cloud_Manager.Models.Interfaces
{
public interface ISalesHub
{
Task TransactionMade(SaleItem a_transaction);
Task JoinCompanyGroup();
}
}

36
Cloud_Manager/Models/Interfaces/ISalesInterface.cs

@ -0,0 +1,36 @@
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.POSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.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);
Task SyncCart(List<Tblcart> a_item);
Task SyncCancelledTransaction(List<Tblcancelledtransaction> a_item);
Task SyncCreditPurchase(List<Creditpurchase> a_item);
Task SyncCustomerAccount(List<Customeraccount> a_customerAccounts);
Task SyncCustomerPurchase(List<Tblcustomerpurchase> a_customerPurchase);
Task SyncDiscountLogs(List<Tbldiscountlog> a_discountLog);
Task SyncDeliveryDetails(List<Tbldeliverydetail> a_details);
Task SyncDeliveryHead(List<Tbldeliveryhead> a_heads);
Task SyncDeliveryRecipients(List<Tbldeliveryrecipient> a_recipients);
Task SyncInvoice(List<Tblinvoice> a_invoice);
DateTime GetLastSyncDate(string a_tablename);
void SetLastSyncDate(string a_tableName, DateTime a_timestamp);
event EventHandler TransactionsChanged;
event EventHandler FetchComplete;
event EventHandler FetchStart;
}
}

18
Cloud_Manager/Models/Interfaces/ITokenService.cs

@ -0,0 +1,18 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
namespace Cloud_Manager.Models.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);
}
}

16
Cloud_Manager/Models/Interfaces/IUser.cs

@ -0,0 +1,16 @@
using Cloud_Manager.Models.POSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cloud_Manager.Models.Interfaces
{
public interface IUser
{
IEnumerable<Tbluser> FetchUsers();
Task<IEnumerable<Tbluser>> GetUsers();
Task SyncUserAsync(List<Tbluser> a_users);
}
}

21
Cloud_Manager/Models/POSModels/Creditpurchase.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Creditpurchase
{
public string ReceiptId { get; set; } = null!;
public string BranchId { get; set; } = null!;
public DateTime Date { get; set; }
public decimal TotalBill { get; set; }
public decimal Paid { get; set; }
public string CustomerId { get; set; } = null!;
public string Status { get; set; } = null!;
}

25
Cloud_Manager/Models/POSModels/Customeraccount.cs

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Customeraccount
{
public string CustomerId { get; set; } = null!;
public string TransactionId { get; set; } = null!;
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; } = null!;
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

21
Cloud_Manager/Models/POSModels/Productaltunit.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; } = null!;
}

15
Cloud_Manager/Models/POSModels/Restocklevel.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Restocklevel
{
public string ProductId { get; set; } = null!;
public string BranchId { get; set; } = null!;
public int? WarnLevel { get; set; }
public string? Unit { get; set; }
}

19
Cloud_Manager/Models/POSModels/Systemuserrole.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; }
}

19
Cloud_Manager/Models/POSModels/Tblbranch.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; }
}

13
Cloud_Manager/Models/POSModels/Tblbrand.cs

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblbrand
{
public string Id { get; set; } = null!;
public string BranchId { get; set; } = null!;
public string? Brand { get; set; }
}

17
Cloud_Manager/Models/POSModels/Tblcancelledtransaction.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblcancelledtransaction
{
public string? Transno { get; set; }
public DateTime? DateCancelled { get; set; }
public string? CancelledBy { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

35
Cloud_Manager/Models/POSModels/Tblcart.cs

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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? Unit { get; set; }
public decimal? Tendered { get; set; }
public decimal? Balance { get; set; }
public decimal? ValueAddTax { get; set; }
public decimal? Discount { get; set; } = 0;
public decimal? Costprice { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

13
Cloud_Manager/Models/POSModels/Tblcategory.cs

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblcategory
{
public string Id { get; set; } = null!;
public string BranchId { get; set; } = null!;
public string? Category { get; set; }
}

21
Cloud_Manager/Models/POSModels/Tblcompanydetail.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; }
}

35
Cloud_Manager/Models/POSModels/Tblcustomer.cs

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblcustomer
{
public string CustomerId { get; set; } = null!;
public string BranchId { 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? Status { get; set; }
public string? Tin { get; set; }
public DateTime? DateExit { get; set; }
public string? Email { get; set; }
public string? FinancialStatus { get; set; }
public string? NameKey1 { get; set; }
public string? NameKey2 { get; set; }
}

15
Cloud_Manager/Models/POSModels/Tblcustomerpurchase.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblcustomerpurchase
{
public string? CustomerId { get; set; }
public string? TransactionId { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

21
Cloud_Manager/Models/POSModels/Tbldeliverydetail.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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 string BranchId { get; set; } = null!;
}

25
Cloud_Manager/Models/POSModels/Tbldeliveryhead.cs

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tbldeliveryhead
{
public string DeliveryId { get; set; } = null!;
public string BranchId { 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; }
}

25
Cloud_Manager/Models/POSModels/Tbldeliveryrecipient.cs

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tbldeliveryrecipient
{
public string DeliveryId { get; set; } = null!;
public string BranchId { 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 DateOnly? FromDate { get; set; }
public DateOnly? ToDate { get; set; }
}

19
Cloud_Manager/Models/POSModels/Tbldiscountlog.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; } = null!;
public string CountId { get; set; } = null!;
}

33
Cloud_Manager/Models/POSModels/Tbldriver.cs

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tbldriver
{
public string DriverId { get; set; } = null!;
public string BranchId { get; set; } = null!;
public string? Firstname { get; set; }
public string? Surname { get; set; }
public string? Middlename { get; set; }
public DateOnly? 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? Status { get; set; }
}

15
Cloud_Manager/Models/POSModels/Tblinventory.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblinventory
{
public string? Pcode { get; set; }
public int? Quantity { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

17
Cloud_Manager/Models/POSModels/Tblinventoryentry.cs

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

29
Cloud_Manager/Models/POSModels/Tblinvoice.cs

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblinvoice
{
public string? InvoiceId { get; set; }
public string? Pcode { get; set; }
public int? Quantity { get; set; }
public decimal? Unitprice { get; set; }
public string? Unit { get; set; }
public decimal? Totalprice { get; set; }
public DateOnly? DateGenerated { get; set; }
public string? Status { get; set; }
public string? GeneratedBy { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

19
Cloud_Manager/Models/POSModels/Tblpricechange.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tblpricechange
{
public string? Pcode { 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!;
}

31
Cloud_Manager/Models/POSModels/Tblproduct.cs

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; }
public decimal? Costprice { get; set; }
public string? BaseUnit { get; set; }
public string? ProductName { get; set; }
public string? Status { get; set; }
public string BranchId { get; set; } = null!;
public string CountId { get; set; } = null!;
}

13
Cloud_Manager/Models/POSModels/Tblsyncinfo.cs

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
namespace Biskilog_Accounting.Server.POSModels;
public partial class Tblsyncinfo
{
public string TableName { get; set; } = null!;
public DateTime? LastSyncDate { get; set; } = DateTime.MinValue;
public string? BranchId { get; set; }
}

19
Cloud_Manager/Models/POSModels/Tbltruck.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tbltruck
{
public string TruckId { get; set; } = null!;
public string BranchId { get; set; } = null!;
public string? LicensePlate { get; set; }
public string? Brand { get; set; }
public string? Driver { get; set; }
public decimal? Weight { get; set; }
}

19
Cloud_Manager/Models/POSModels/TbltruckDrivermapping.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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 string BranchId { get; set; } = null!;
}

21
Cloud_Manager/Models/POSModels/Tbltruckassignment.cs

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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 string BranchId { get; set; } = null!;
}

19
Cloud_Manager/Models/POSModels/Tbltruckinventory.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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 string BranchId { get; set; } = null!;
}

33
Cloud_Manager/Models/POSModels/Tbluser.cs

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Tbluser
{
public string Username { get; set; } = null!;
public string BranchId { 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; }
public string? AccessLevel { get; set; }
public DateTime? LastLogin { get; set; }
}

23
Cloud_Manager/Models/POSModels/Tbstock.cs

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
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; }
}

17
Cloud_Manager/Models/POSModels/Unitofmeasure.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.POSModels;
public partial class Unitofmeasure
{
public string UnitCode { get; set; } = null!;
public string BranchId { get; set; } = null!;
public string? Unitname { get; set; }
public string? Unitshort { get; set; }
public string? Status { get; set; }
}

199
Cloud_Manager/Models/ServiceRepo/TokenService.cs

@ -0,0 +1,199 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Cloud_Manager.Models.ServiceRepo
{
public class TokenService : ITokenService
{
private IConfiguration m_configuration { get; }
public TokenService(IConfiguration a_configuration)
{
m_configuration = a_configuration;
}
/// <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)
{
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();
}
}
}

103
Cloud_Manager/Program.cs

@ -0,0 +1,103 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text.Json.Serialization;
using System.Text;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager;
using Cloud_Manager.Services;
using Cloud_Manager.Models.ServiceRepo;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSignalR();
builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Services.AddEntityFrameworkMySql().AddDbContext<BiskilogContext>(options =>
{
options.UseMySql(builder.Configuration.GetConnectionString("Connection"), new MariaDbServerVersion(new Version()));
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDbContext<BiskAcdbContext>();
builder.Services.AddScoped<ICompanyInfo, CompanyService>();
builder.Services.AddScoped<IAuthService, AuthenticationService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IConnectionService, ConnectionService>();
builder.Services.AddScoped<IProduct, ProductRepo>();
builder.Services.AddScoped<ISalesInterface, SalesService>();
builder.Services.AddScoped<IUser, UserService>();
builder.Services.AddScoped<ICustomer, CustomerService>();
//builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
//{
// options.RequireHttpsMetadata = false;
// options.SaveToken = true;
// options.TokenValidationParameters = new TokenValidationParameters()
// {
// ValidateIssuer = true,
// ValidateAudience = true,
// ValidAudience = builder.Configuration["Jwt:Audience"],
// ValidIssuer = builder.Configuration["Jwt:Issuer"],
// IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
// };
//});
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyBlazor", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyBlazor v1");
c.RoutePrefix = "api/docs";
});
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

41
Cloud_Manager/Properties/launchSettings.json

@ -0,0 +1,41 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57096",
"sslPort": 44350
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5232",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7122;http://localhost:5232",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

146
Cloud_Manager/Services/AuthenticationService.cs

@ -0,0 +1,146 @@
using Cloud_Manager;
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace Cloud_Manager.Services
{
public class AuthenticationService : IAuthService
{
private readonly BiskilogContext m_context;
private readonly ITokenService m_tokenService;
public AuthenticationService(BiskilogContext a_context, ITokenService a_tokenService)
{
m_context = a_context;
m_tokenService = a_tokenService;
}
/// <summary>
/// Returns the status of a user account
/// </summary>
/// <returns>AuthEnums</returns>
public AuthEnums AccountStatus(int? a_id, string? a_username)
{
if (m_context.Userauths.Any(i => i.UserId == a_id || i.Username == a_username))
{
return AuthEnums.Found;
}
else
{
return AuthEnums.NotFound;
}
}
/// <summary>
/// Autenticates a user and returns a tokenized string
/// </summary>
/// <param name="a_username"></param>
/// <param name="a_password"></param>
/// <returns>strings</returns>
public async Task<string> AuthenticateClient(string a_username, string a_password)
{
var user = await GetUserAsync(a_username, a_password);
if (user == null)
{
return null;
}
user.LastLogin = DateTime.Now;
m_context.Userauths.Update(user);
m_context.SaveChanges();
Databasemap databasemap = GetClientDB(user.ClientId);
List<int> businessIds = GetSiteaccesspermission(user.ClientId, user.UserId).Select(t => t.BusinessId).ToList();
Contract? contract = GetContract(user.ClientId, businessIds);
List<string> businesses = GetClientbusiness(user.ClientId, user.UserId).Select(t => t.BusinessExternalId).ToList();
if (contract == null)
return AuthEnums.Invalid.ToString();
return m_tokenService.GenerateToken(user, contract, databasemap, businesses, false);
}
/// <summary>
/// Creates a new user account
/// </summary>
/// returns AuthEnums.successful if the account was created successfully
public AuthEnums CreateUser(Userauth a_user)
{
throw new NotImplementedException();
//if (AccountStatus(null, a_user.Username) == AuthEnums.Found)
// return AuthEnums.Registered;
//a_user.Role = m_context.UserRoles.First(i => i.RoleId== a_user.RoleId);
//a_user.Password = BCrypt.Net.BCrypt.HashPassword(a_user.Password);
//m_context.Users.Add(a_user);
//var result = m_context.SaveChangesAsync();
//result.Wait();
//if(result.Result > 0)
//{
// return AuthEnums.Successful;
//}
//return AuthEnums.Error;
}
/// <summary>
/// Deletes a user account
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void DeleteUser(int a_id)
{
throw new NotImplementedException();
}
public List<Clientbusiness> GetClientbusiness(int a_clientId, int userId)
{
return (from b in m_context.Clientbusinesses
join p in m_context.Siteaccesspermissions on new { b.ClientId, b.BusinessId } equals new { p.ClientId, p.BusinessId }
where p.UserId == userId && p.ClientId == a_clientId
select b).ToList();
}
public Databasemap GetClientDB(int a_clientId)
{
return m_context.Databasemaps.First(t => t.ClientId == a_clientId);
}
public Contract? GetContract(int a_clientId, List<int> a_businessId)
{
return m_context.Contracts.FirstOrDefault(c => c.ClientId == a_clientId && a_businessId.Contains(c.BusinessId!.Value) && c.EndDate >= DateTime.Now);
}
public List<Siteaccesspermission> GetSiteaccesspermission(int a_clientId, int a_userId)
{
return m_context.Siteaccesspermissions.Where(t => t.ClientId == a_clientId && t.UserId == a_userId).ToList();
}
private async Task<Userauth> GetUserAsync(string username, string password)
{
//Todo have complete implementation after means of creating user is done
//try
//{
// string pa = await m_context.Userauths.Where(u => u.Username == username).Select(u => u.Password).FirstAsync();
// bool verified = BCrypt.Net.BCrypt.Verify(password, pa);
// if (verified)
// {
//TODO have a complete implementation
return await m_context.Userauths.FirstAsync(u => u.Username == username && u.Passsword == password);
// }
// else
// {
// return null;
// }
//}catch(Exception ex)
//{
// //possible is user not found
// return null;
//}
}
}
}

227
Cloud_Manager/Services/CompanyService.cs

@ -0,0 +1,227 @@
using Cloud_Manager;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using MySqlConnector;
using System.Text.Json;
namespace Cloud_Manager.Services
{
public class CompanyService : ICompanyInfo
{
private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService;
private readonly HttpContext m_httpContext;
private Tblcompanydetail m_companyInfo { get; set; }
private IEnumerable<Tblbranch> m_companyBranches { get; set; }
public CompanyService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{
m_context = a_context;
m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
m_companyInfo = new Tblcompanydetail();
m_companyBranches = new List<Tblbranch>();
GetCompanyInfoAsync();
GetBranches();
}
public IEnumerable<Tblbranch> FetchBranches()
{
return m_companyBranches;
}
public async Task<IEnumerable<Tblbranch>> GetBranches()
{
m_companyBranches = m_context.Tblbranches;
return await Task.FromResult(m_companyBranches);
}
public string GetBranchName(string a_branchId)
{
return m_companyBranches.FirstOrDefault(b => b.BranchId == a_branchId).BranchName;
}
public Task<Tblcompanydetail> GetCompanyInfoAsync()
{
m_companyInfo = m_context.Tblcompanydetails.FirstOrDefault();
return Task.FromResult(m_companyInfo);
}
public string GetCompanyName()
{
return m_companyInfo.CompanyName;
}
public async Task SyncBranches(List<Tblbranch> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL BranchSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public DateTime GetLastSyncDate(string a_tablename)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null)
{
return (DateTime)lastSync!;
}
}
return new DateTime(2000, 01, 01);
}
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL SetTableLastSync(@p0,@p1,@p2)";
command.Parameters.Add(new MySqlParameter("@p0", a_tableName));
command.Parameters.Add(new MySqlParameter("@p1", activeBranch));
command.Parameters.Add(new MySqlParameter("@p2", a_timestamp));
command.ExecuteNonQuery();
}
}
}
public async Task SyncSystemRoles(List<Systemuserrole> a_roles)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_roles);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL SystemUserRolesSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCompanyDetails(List<Tblcompanydetail> a_details)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CompanyDetailSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncDriverDetails(List<Tbldriver> a_details)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL DriverSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncTrucks(List<Tbltruck> a_trucks)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_trucks);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL TruckSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncTruckAssignments(List<Tbltruckassignment> a_assignments)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_assignments);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL TruckAssignmentSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncTruckMappings(List<TbltruckDrivermapping> a_mapping)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_mapping);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL TruckDriverMappingSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncTruckInventory(List<Tbltruckinventory> a_inventories)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_inventories);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL TruckInventorySync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
}
}

50
Cloud_Manager/Services/ConnectionService.cs

@ -0,0 +1,50 @@
using Cloud_Manager;
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Cloud_Manager.Services
{
public class ConnectionService : IConnectionService
{
private readonly BiskilogContext m_context;
private readonly IConfiguration m_configuration;
public ConnectionService(BiskilogContext a_context, IConfiguration configuration)
{
m_context = a_context;
m_configuration = configuration;
}
/// <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>
public string GetClientConnectionString(int a_databaseId)
{
Databasemap? dbMap = m_context.Databasemaps.Find(a_databaseId);
if (dbMap != null)
{
string rawConString = m_configuration.GetConnectionString("PrivateConnection")!.ToString();
return string.Format(rawConString, dbMap.Domain, dbMap.DbName);
}
return ConnectionEnums.ConnectionNotEstablished.ToString();
}
/// <summary>
/// Prepare the DB context from the specified connection string
/// </summary>
/// <param name="a_context"></param>
/// <param name="a_connectionString"></param>
/// <returns>A configured BiskAcdbContext</returns>
public object PrepareDBContext(string a_connectionString)
{
throw new NotImplementedException();
//DbContextOptionsBuilder<BiskAcdbContext> acdbContext = new DbContextOptionsBuilder<BiskAcdbContext>();
//acdbContext.UseMySql(a_connectionString, new MariaDbServerVersion(new Version()));
//return new BiskAcdbContext(acdbContext.Options);
}
}
}

89
Cloud_Manager/Services/CustomerService.cs

@ -0,0 +1,89 @@
using Cloud_Manager;
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using MySqlConnector;
using System.Text.Json;
namespace Cloud_Manager.Services
{
public class CustomerService : ICustomer
{
private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService;
private readonly HttpContext m_httpContext;
public CustomerService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{
m_context = a_context;
m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
}
public IEnumerable<CustomerAccounts> FetchCustomers()
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetCustomers(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new CustomerAccounts
{
Customer = new Tblcustomer
{
CustomerId = reader.GetString(0),
BranchId = reader.GetString(1),
Firstname = reader.GetString(2),
Surname = reader.GetString(3),
Address = reader.GetString(4),
Telephone = reader.GetString(5),
DateAdded = reader.GetDateTime(6),
Status = reader.GetString(7),
Email = reader.GetString(8),
FinancialStatus = reader.GetString(9),
},
Debt = reader.GetDecimal(10)
};
}
}
}
}
}
public Task<IEnumerable<CustomerAccounts>> GetCustomers()
{
throw new NotImplementedException();
}
public async Task SyncCustomers(List<Tblcustomer> a_details)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CustomerSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
}
}

411
Cloud_Manager/Services/ProductRepo.cs

@ -0,0 +1,411 @@
using Cloud_Manager;
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using MySqlConnector;
using System.Data;
using System.Data.Common;
using System.Text.Json;
namespace Cloud_Manager.Services
{
public class ProductRepo : IProduct
{
private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService;
private readonly HttpContext m_httpContext;
public event EventHandler ProductsChanged;
public event EventHandler UnitsChanged;
public event EventHandler BrandsChanged;
public event EventHandler CategoriesChanged;
public ProductRepo(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{
m_context = a_context;
m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
}
/// <summary>
/// Gets all products from the server
/// </summary>
/// <returns></returns>
public IEnumerable<ProductItem> GetProducts(string a_productKey = "")
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetProducts(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
List<ProductUnits> pUnits = new List<ProductUnits>();
yield return new ProductItem
{
Product = new Tblproduct
{
Pcode = reader.GetString(0),
ProductName = reader.GetString(1),
Pdesc = reader.GetString(2),
BaseUnit = reader.GetString(3),
Costprice = reader.GetDecimal(4),
Status = reader.GetString(5),
Price = reader.GetDecimal(6),
BranchId = reader.GetString(7),
},
BaseUnit = reader.GetString(3),
Stock = new Tblinventory
{
Quantity = reader.GetInt32(8)
},
Restocklevel = new Restocklevel
{
WarnLevel = reader.GetInt32(9),
Unit = reader.GetString(10),
},
Units = GetAltUnits(reader)
};
}
}
}
}
}
private List<ProductUnits> GetAltUnits(DbDataReader a_reader)
{
List<ProductUnits> pUnits = new List<ProductUnits>();
for (int i = 1; i < 5; i++)
{
if (!a_reader.IsDBNull(a_reader.GetOrdinal($"AltUnit{i}")))
{
pUnits.Add(new ProductUnits
{
UnitCode = a_reader.GetFieldValue<string>($"AltUnit{i}"),
QuantityUnit = a_reader.GetFieldValue<int>($"AltUnit{i}QTY"),
PriceUnit = a_reader.GetFieldValue<decimal>($"AltUnit{i}Price"),
DistinctiveCode = a_reader.GetFieldValue<string>($"AltUnit{i}distinctiveCode")
});
}
else
{
return pUnits;
}
}
return pUnits;
}
public IEnumerable<Unitofmeasure> GetUnitofmeasures()
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Unitofmeasures.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Unitofmeasure>();
}
public IEnumerable<Tblbrand> GetBrands(string a_brandKey = "")
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblbrands.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tblbrand>();
}
public IEnumerable<Tblcategory> GetCategories(string a_categoryKey = "")
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblcategories.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tblcategory>();
}
public async Task SyncProducts(List<Tblproduct> a_item)
{
try
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL ProductSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public async Task SyncInventory(List<Tblinventory> a_item)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL InventorySync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncInventoryEntries(List<Tblinventoryentry> a_item)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL InventoryEntriesSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncPriceChanges(List<Tblpricechange> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL PriceChangeSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncProductAltUnit(List<Productaltunit> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL ProductAltUnitSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncRestockAsync(List<Restocklevel> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL RestockLevelsSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncUnitOfMeasureAsync(List<Unitofmeasure> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL UnitOfMeasureSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncStockAsync(List<Tbstock> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL StockSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncBrandsAsync(List<Tblbrand> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL BrandSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCategoriesAsync(List<Tblcategory> a_items)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CategorySync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public DateTime GetLastSyncDate(string a_tablename)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null)
{
return (DateTime)lastSync!;
}
}
return new DateTime(2000, 01, 01);
}
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL SetTableLastSync(@p0,@p1,@p2)";
command.Parameters.Add(new MySqlParameter("@p0", a_tableName));
command.Parameters.Add(new MySqlParameter("@p1", activeBranch));
command.Parameters.Add(new MySqlParameter("@p2", a_timestamp));
command.ExecuteNonQuery();
}
}
}
#region Only Need to implement in the client Side
public Task FetchUnits()
{
throw new NotImplementedException();
}
public Task FetchProducts()
{
throw new NotImplementedException();
}
public ProductItem GetProductById(string a_id)
{
throw new NotImplementedException();
}
public ProductItem GetProductByName(string name)
{
throw new NotImplementedException();
}
public void RefreshList()
{
throw new NotImplementedException();
}
public string GetUnitName(string a_unitCode)
{
throw new NotImplementedException();
}
public Task FetchBrands()
{
throw new NotImplementedException();
}
public Task FetchCategories()
{
throw new NotImplementedException();
}
public IEnumerable<ProductItem> GetLowstockItems()
{
throw new NotImplementedException();
}
public Task FetchLowStockProducts()
{
throw new NotImplementedException();
}
}
#endregion
}

381
Cloud_Manager/Services/SalesService.cs

@ -0,0 +1,381 @@
using Cloud_Manager.CloudHubs;
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using MySqlConnector;
using System.Text.Json;
namespace Cloud_Manager.Services
{
public class SalesService : ISalesInterface
{
private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService;
private readonly HttpContext m_httpContext;
private readonly IHubContext<SalesHub, ISalesHub> m_salesHub;
public event EventHandler TransactionsChanged;
public event EventHandler FetchComplete;
public event EventHandler FetchStart;
public SalesService(BiskAcdbContext a_context, ITokenService a_tokenService,
IHttpContextAccessor a_httpContextAccessor, IHubContext<SalesHub, ISalesHub> a_salesHub)
{
m_context = a_context;
m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
m_salesHub = a_salesHub;
}
public Task FetchRecentTransaction(int a_limit)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetRecentTransaction()
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetTransactions(DateTime a_start, DateTime a_end)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetTransactionsByDate(@p0,@p1,@p2)";
command.Parameters.Add(new MySqlParameter("@p0", a_start.ToString("yyyy-MM-dd")));
command.Parameters.Add(new MySqlParameter("@p1", a_end.ToString("yyyy-MM-dd")));
command.Parameters.Add(new MySqlParameter("@p2", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new SaleItem
{
Transno = reader.GetString(0),
Total = (decimal)reader.GetDouble(1),
Date = reader.GetDateTime(2),
Cashier = reader.GetString(3),
BranchId = reader.GetString(4),
Customer = reader.GetString(5),
Status = reader.GetString(6),
};
}
}
}
}
}
public Task FetchTransaction(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
public Task FetchReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetReceipt(string a_receiptId)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetTransactionsById(@p0,@p1)";
command.Parameters.Add(new MySqlParameter("@p0", a_receiptId));
command.Parameters.Add(new MySqlParameter("@p1", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new SaleItem
{
Transno = reader.GetString(0),
Total = (decimal)reader.GetDouble(1),
Date = reader.GetDateTime(2),
Cashier = reader.GetString(3),
BranchId = reader.GetString(4),
Customer = reader.GetString(5),
Status = reader.GetString(6),
};
}
}
// Close the connection explicitly
m_context.Database.CloseConnection();
}
}
}
public Task<IEnumerable<Tblcart>> GetReceiptDetail(string a_receiptId)
{
List<Tblcart> details = new List<Tblcart>();
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetReceiptDetails(@p0,@p1)";
command.Parameters.Add(new MySqlParameter("@p0", a_receiptId));
command.Parameters.Add(new MySqlParameter("@p1", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
details.Add(new Tblcart
{
Transno = a_receiptId,
Id = reader.GetString(0),
Quantity = reader.GetInt32(1),
Date = reader.GetDateTime(2),
Price = reader.GetDecimal(3),
Cashier = reader.GetString(4),
Status = reader.GetString(5),
Total = (decimal)reader.GetDouble(6),
Unit = reader.GetString(7),
Costprice = reader.GetDecimal(8),
BranchId = reader.GetString(9),
CountId = reader.GetString(10),
Tendered = reader.GetDecimal(11),
Balance = reader.GetDecimal(12),
ValueAddTax = reader.GetDecimal(13)
});
}
}
}
}
return Task.FromResult(details.AsEnumerable());
}
public async Task SyncCart(List<Tblcart> a_item)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL SaleSyncUpstream(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public DateTime GetLastSyncDate(string a_tablename)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null)
{
return (DateTime)lastSync!;
}
}
return new DateTime(2000, 01, 01);
}
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string activeBranch = m_tokenService.GetBaseBranch(token)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL SetTableLastSync(@p0,@p1,@p2)";
command.Parameters.Add(new MySqlParameter("@p0", a_tableName));
command.Parameters.Add(new MySqlParameter("@p1", activeBranch));
command.Parameters.Add(new MySqlParameter("@p2", a_timestamp));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCancelledTransaction(List<Tblcancelledtransaction> a_item)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CancelledSaleSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCreditPurchase(List<Creditpurchase> a_item)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CreditPurchaseSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCustomerAccount(List<Customeraccount> a_customerAccounts)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_customerAccounts);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CustomerAccountSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncCustomerPurchase(List<Tblcustomerpurchase> a_customerPurchase)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_customerPurchase);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL CustomerPurchasesSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncDiscountLogs(List<Tbldiscountlog> a_discountLog)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_discountLog);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL DiscountLogsSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncDeliveryDetails(List<Tbldeliverydetail> a_details)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL DeliveryDetailsSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncDeliveryHead(List<Tbldeliveryhead> a_heads)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_heads);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL DeliveryheadSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncDeliveryRecipients(List<Tbldeliveryrecipient> a_recipients)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_recipients);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL DeliveryRecipientSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
public async Task SyncInvoice(List<Tblinvoice> a_invoice)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_invoice);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL InvoiceSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
}
}

59
Cloud_Manager/Services/UserService.cs

@ -0,0 +1,59 @@
using Cloud_Manager;
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.POSModels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using MySqlConnector;
using System.Text.Json;
namespace Cloud_Manager.Services
{
public class UserService : IUser
{
private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService;
private readonly HttpContext m_httpContext;
public UserService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{
m_context = a_context;
m_tokenService = a_tokenService;
m_httpContext = a_httpContextAccessor?.HttpContext;
}
public IEnumerable<Tbluser> FetchUsers()
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblusers.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tbluser>();
}
public Task<IEnumerable<Tbluser>> GetUsers()
{
throw new NotImplementedException();
}
public async Task SyncUserAsync(List<Tbluser> a_users)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
string jsonString = JsonSerializer.Serialize(a_users);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
m_context.Database.OpenConnection();
command.CommandText = "CALL UsersSync(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", jsonString));
command.ExecuteNonQuery();
}
}
}
}
}

13
Cloud_Manager/WeatherForecast.cs

@ -0,0 +1,13 @@
namespace Cloud_Manager
{
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; }
}
}

8
Cloud_Manager/appsettings.Development.json

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

18
Cloud_Manager/appsettings.json

@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"Connection": "server=54.37.19.162;database=dev_biskilogclients;user=biskilog;password=mefbuk-6niFsu-fytrew;AllowZeroDateTime=True;",
"PrivateConnection": "server={0};database={1};user=biskilog;password=mefbuk-6niFsu-fytrew;default command timeout=0;AllowZeroDateTime=True;"
},
"AllowedHosts": "*",
"JWT": {
"Key": "@@BISKILOGACCOUNTING2023DEV??//##$",
"Issuer": "AUTH SERVER",
"Audience": "BISKILOG"
}
}
Loading…
Cancel
Save