WorkspaceService.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Principal;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using BO.AppServer.Business.Exceptions;
  8. using BO.AppServer.Business.Mapper;
  9. using BO.AppServer.Business.Services.Base;
  10. using BO.AppServer.Data.Entity;
  11. using BO.AppServer.Data.Repository;
  12. using BO.AppServer.Metadata.Configuration;
  13. using BO.AppServer.Metadata.Dto;
  14. using BO.AppServer.Metadata.Enums;
  15. using Microsoft.AspNetCore.Identity;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Extensions.Options;
  18. using Quadarax.Foundation.Core.Data;
  19. using Quadarax.Foundation.Core.Data.Interface;
  20. using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
  21. using Quadarax.Foundation.Core.Exceptions;
  22. namespace BO.AppServer.Business.Services
  23. {
  24. public class WorkspaceService: UserContextService
  25. {
  26. #region *** Private fields ***
  27. private readonly WorkspaceRepo _repoWorkspace;
  28. private readonly BillingPlanRepo _repoBillingPlan;
  29. private readonly WorkspaceBillingRepo _repoWorkspaceBilling;
  30. #endregion
  31. #region *** Constructor ***
  32. public WorkspaceService(WorkspaceRepo repoWorkspace,
  33. BillingPlanRepo repoBillingPlan,
  34. WorkspaceBillingRepo repoWorkspaceBilling,
  35. IOptions<Configuration> config,
  36. UserRepo repoUser,
  37. UserManager<IdentityUser> userManager,
  38. IPrincipal currentPrincipal,
  39. ILoggerFactory logger) : base(config, repoUser, userManager, currentPrincipal, logger)
  40. {
  41. _repoWorkspace = repoWorkspace ?? throw new ArgumentNullException(nameof(repoWorkspace));
  42. _repoBillingPlan = repoBillingPlan ?? throw new ArgumentNullException(nameof(repoBillingPlan));
  43. _repoWorkspaceBilling = repoWorkspaceBilling ?? throw new ArgumentNullException(nameof(repoWorkspaceBilling));
  44. }
  45. #endregion
  46. #region *** Public Operations ***
  47. public async Task<ResultValueDto<WorkspaceRDto>> CreateWorkspaceAsync(WorkspaceCDto workspace)
  48. {
  49. var billingPlan = _repoBillingPlan.GetByCode(workspace.BillingPlanCode);
  50. if (billingPlan == null)
  51. {
  52. var exc = new EntityNotExistsException(typeof(BillingPlan), workspace.BillingPlanCode, 0);
  53. Log.LogWarning(exc.Message);
  54. throw exc;
  55. }
  56. var owner = _repoUser.GetByName(workspace.AssignedUserName);
  57. if (owner == null)
  58. {
  59. var exc = new EntityNotExistsException(typeof(User), workspace.AssignedUserName, 0);
  60. Log.LogWarning(exc.Message);
  61. throw exc;
  62. }
  63. var current = GetCurrentUser();
  64. var newWorkspace = _repoWorkspace.CreateWorkspace(workspace.Name, billingPlan, workspace.Apipassword, true, owner,current);
  65. _repoWorkspace.Commit();
  66. Log.LogInformation($"Workspace '{newWorkspace.Name}' [API-KEY:{newWorkspace.Apikey}] created and appends to users: {string.Join(",", newWorkspace.UserWorkspaces.Select(x=>x.User.Name))}");
  67. return new ResultValueDto<WorkspaceRDto>(newWorkspace.Map<Workspace, WorkspaceRDto>());
  68. }
  69. public async Task<ResultsValueDto<WorkspaceRDto>> GetWorkspacesAsync(WorkspaceScopeEnums scope, PagingDto paging,string ownerUserName)
  70. {
  71. List<Workspace> workspaces = null;
  72. switch (scope)
  73. {
  74. case WorkspaceScopeEnums.All:
  75. workspaces = _repoWorkspace.Query(paging).ToList();
  76. break;
  77. case WorkspaceScopeEnums.Empty:
  78. workspaces = _repoWorkspace.GetAllEmpty(paging).ToList();
  79. break;
  80. case WorkspaceScopeEnums.NotEmpty:
  81. workspaces = _repoWorkspace.GetAllNonEmpty(paging).ToList();
  82. break;
  83. case WorkspaceScopeEnums.My:
  84. var owner = _repoUser.GetByName(ownerUserName);
  85. if (owner == null)
  86. {
  87. var exc = new EntityNotExistsException(typeof(User), ownerUserName, 0);
  88. Log.LogWarning(exc.Message);
  89. throw exc;
  90. }
  91. workspaces = _repoWorkspace.GetAllByOwner(owner, paging).ToList();
  92. break;
  93. case WorkspaceScopeEnums.MyDefault:
  94. owner = _repoUser.GetByName(ownerUserName);
  95. if (owner == null)
  96. {
  97. var exc = new EntityNotExistsException(typeof(User), ownerUserName, 0);
  98. Log.LogWarning(exc.Message);
  99. throw exc;
  100. }
  101. var workspace = _repoWorkspace.GetDefaultByOwner(owner);
  102. if (workspace == null)
  103. {
  104. var exc = new CodeException(1410,$"User '{ownerUserName}' has any default workspace set!");
  105. Log.LogWarning(exc.Message);
  106. throw exc;
  107. }
  108. workspaces = new List<Workspace>(new[] { workspace });
  109. break;
  110. }
  111. return new ResultsValueDto<WorkspaceRDto>(workspaces.MapList<Workspace, WorkspaceRDto>());
  112. }
  113. public async Task<long> GetWorkspaceIdByAPIAccess(string apiKey, string apiPassword, string currentUserName)
  114. {
  115. var owner = string.IsNullOrEmpty(currentUserName) ? GetCurrentUser() : _repoUser.GetByName(currentUserName);
  116. if (owner == null)
  117. {
  118. var exc = new EntityNotExistsException(typeof(User), currentUserName, 0);
  119. Log.LogWarning(exc.Message);
  120. throw exc;
  121. }
  122. if (!Guid.TryParse(apiKey, out var apiKeyGuid))
  123. apiKeyGuid = Guid.Empty;
  124. Workspace workspace = null;
  125. if (await HasUserElevation(currentUserName))
  126. {
  127. // if elevated user and system user
  128. workspace = _repoWorkspace.GetByApiKey(apiKey);
  129. if (workspace.Apipassword != apiPassword)
  130. workspace = null;
  131. }
  132. else
  133. {
  134. // for rest
  135. workspace = _repoWorkspace.GetAllByOwner(owner, new Paging())
  136. .FirstOrDefault(x => x.Apikey == apiKeyGuid && x.Apipassword == apiPassword);
  137. }
  138. if (workspace == null)
  139. {
  140. var exc = new CodeException(1400, $"Workspace with APIKey '{apiKey}' not exists or API password is not valid!");
  141. Log.LogWarning(exc.Message + $"\nUser Context:'{owner.Name}' [{owner.Id}]");
  142. throw exc;
  143. }
  144. return workspace.Id;
  145. }
  146. public async Task<ResultValueDto<WorkspaceRDto>> GetWorkspace(WorkspaceIdentificationTypeEnum identificationType, string identificationValue)
  147. {
  148. var workspace = identificationType == WorkspaceIdentificationTypeEnum.Id ?
  149. _repoWorkspace.Get(ArgumentAsLong(nameof(identificationValue), identificationValue))
  150. : identificationType == WorkspaceIdentificationTypeEnum.ApiKey ? _repoWorkspace.GetByApiKey(identificationValue)
  151. : _repoWorkspace.GetByName(identificationValue);
  152. if (workspace == null)
  153. throw new NoDataException();
  154. var currentBillingPlan = GetCurrentWorkspaceBillingOrCreate(workspace.Id);
  155. // gather rest of data
  156. var result = new ResultValueDto<WorkspaceRDto>(workspace.Map<Workspace, WorkspaceRDto>());
  157. result.Value.CreditAmount = currentBillingPlan.ValueNumber;
  158. result.Value.BillingPlanCode = currentBillingPlan.BillingPlan.Code;
  159. return result;
  160. }
  161. public async Task<bool> ExistsWorkspace(WorkspaceIdentificationTypeEnum identificationType, string identificationValue)
  162. {
  163. var workspace = identificationType == WorkspaceIdentificationTypeEnum.Id ?
  164. _repoWorkspace.Get(ArgumentAsLong(nameof(identificationValue), identificationValue))
  165. : identificationType == WorkspaceIdentificationTypeEnum.ApiKey ? _repoWorkspace.GetByApiKey(identificationValue)
  166. : _repoWorkspace.GetByName(identificationValue);
  167. return workspace != null;
  168. }
  169. #endregion
  170. #region *** Private Operations ***
  171. private WorkspaceBilling GetCurrentWorkspaceBillingOrCreate(long workspaceId)
  172. {
  173. var currentBillingPlan = _repoWorkspaceBilling.GetByCurrentForWorkspace(workspaceId);
  174. if (currentBillingPlan == null)
  175. {
  176. currentBillingPlan = _repoWorkspaceBilling.CreateForWorkspace(workspaceId,
  177. _repoBillingPlan.GetByCode(_configuration.Business.DefaultBillingPlanCode));
  178. _repoWorkspaceBilling.Commit();
  179. Log.LogWarning($"Default billing plan was not set for workspace [{workspaceId}]. Set default billing plan '{currentBillingPlan.BillingPlan.Code}'.");
  180. }
  181. return currentBillingPlan;
  182. }
  183. #endregion
  184. }
  185. }