BusinessConfigController.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using TEAMModelBI.Filter;
  11. using TEAMModelBI.Tool.Extension;
  12. using TEAMModelOS.Models;
  13. using TEAMModelOS.SDK.Context.BI;
  14. using TEAMModelOS.SDK.Context.Constant;
  15. using TEAMModelOS.SDK.DI;
  16. using TEAMModelOS.SDK.Extension;
  17. using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
  18. namespace TEAMModelBI.Controllers.BINormal
  19. {
  20. [Route("bizconfig")]
  21. [ApiController]
  22. public class BusinessConfigController : ControllerBase
  23. {
  24. public readonly AzureCosmosFactory _azureCosmos;
  25. public readonly AzureStorageFactory _azureStorage;
  26. public readonly DingDing _dingDing;
  27. public readonly Option _option;
  28. public BusinessConfigController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option)
  29. {
  30. _azureCosmos = azureCosmos;
  31. _azureStorage = azureStorage;
  32. _dingDing = dingDing;
  33. _option = option?.Value;
  34. }
  35. /// <summary>
  36. /// 新增企业信息和修改企业信息 //已对接
  37. /// </summary>
  38. /// <param name="bizConfig"></param>
  39. /// <returns></returns>
  40. [ProducesDefaultResponseType]
  41. [AuthToken(Roles = "admin,rdc,assist")]
  42. [HttpPost("set-info")]
  43. public async Task<IActionResult> SetInfo([FromBody] BizConfig bizConfig, [FromHeader] string site)
  44. {
  45. StringBuilder strMsg = new();
  46. var cosmosClient = _azureCosmos.GetCosmosClient();
  47. var tableClient = _azureStorage.GetCloudTableClient();
  48. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  49. //if ($"{site}".Equals(BIConst.Global))
  50. //{
  51. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  52. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  53. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  54. //}
  55. string salt = Utils.CreatSaltString(8);
  56. List<BizUsers> bizUsers = new();
  57. string type = "";
  58. //新增企业信息
  59. if (string.IsNullOrEmpty(bizConfig.id))
  60. {
  61. bizConfig.id = Guid.NewGuid().ToString();
  62. bizConfig.code = "BizConfig";
  63. bizConfig.pk = "BizConfig";
  64. bizConfig.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  65. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
  66. bizConfig.jti = auth_token.jti;
  67. bizConfig.token = auth_token.jwt;
  68. await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizConfig>(bizConfig, new PartitionKey("BizConfig"));
  69. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(queryText: $"select value(c) from c where c.mobile ={bizConfig.mobile}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  70. {
  71. bizUsers.Add(item);
  72. }
  73. BizRel bizRel = new() { bizId = bizConfig.id, role = new List<string>() { "admin" } };
  74. if (bizUsers.Count > 0)
  75. {
  76. foreach (var item in bizUsers)
  77. {
  78. BizRel temp = item.relation.Find(f => f.bizId.Equals(bizConfig.id));
  79. if (temp == null)
  80. {
  81. item.relation.Add(bizRel);
  82. await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(item, item.id, new PartitionKey("BizUsers"));
  83. }
  84. }
  85. }
  86. else
  87. {
  88. BizUsers tBizUsers = new() { id = Guid.NewGuid().ToString(), code= "BizUsers", name = bizConfig.mobile.ToString(), mobile = bizConfig.mobile, salt = salt, pwd = Utils.HashedPassword($"{bizConfig.mobile}", salt),relation= new List<BizRel>() { { bizRel } } };
  89. await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(tBizUsers, new PartitionKey("BizUsers"));
  90. }
  91. strMsg.Append($"{bizConfig.name}【{bizConfig.id}】新增企业基础信息。");
  92. type = "bizconfig-add";
  93. }
  94. //修改企业信息
  95. else
  96. {
  97. var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizConfig.id, new PartitionKey("BizConfig"));
  98. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  99. {
  100. using var json = await JsonDocument.ParseAsync(response.Content);
  101. BizConfig tempBizConfig = json.ToObject<BizConfig>();
  102. bizConfig.pk = "BizConfig";
  103. bizConfig.code = "BizConfig";
  104. bizConfig.ttl = -1;
  105. bizConfig.createTime = tempBizConfig.createTime;
  106. bizConfig.jti = tempBizConfig.jti;
  107. bizConfig.token = tempBizConfig.token;
  108. bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
  109. strMsg.Append($"{bizConfig.name}【{bizConfig.id}】修改企业基础信息。");
  110. type = "bizconfig-update";
  111. }
  112. }
  113. //保存操作记录
  114. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  115. return Ok(new { state = RespondCode.Ok, bizConfig });
  116. }
  117. /// <summary>
  118. /// 获取企业信息列表 //已对接
  119. /// </summary>
  120. /// <param name="jsonElement"></param>
  121. /// <returns></returns>
  122. [ProducesDefaultResponseType]
  123. [AuthToken(Roles = "admin,rdc,assist")]
  124. [HttpPost("get-infos")]
  125. public async Task<IActionResult> GetInfos(JsonElement jsonElement)
  126. {
  127. jsonElement.TryGetProperty("id", out JsonElement id);
  128. var cosmosClient = _azureCosmos.GetCosmosClient();
  129. StringBuilder sqlTxt = new("select value(c) from c");
  130. if (!string.IsNullOrEmpty($"{id}"))
  131. {
  132. sqlTxt.Append($" where c.id='{id}'");
  133. }
  134. List<Business> businesses = new();
  135. await foreach (var items in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<Business>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizConfig") }))
  136. {
  137. businesses.Add(items);
  138. }
  139. return Ok(new { state = RespondCode.Ok, businesses });
  140. }
  141. /// <summary>
  142. /// 刪除企业信息列表
  143. /// </summary>
  144. /// <param name="jsonElement"></param>
  145. /// <returns></returns>
  146. [ProducesDefaultResponseType]
  147. [AuthToken(Roles = "admin,rdc,assist")]
  148. [HttpPost("del-info")]
  149. public async Task<IActionResult> DelInfo(JsonElement jsonElement)
  150. {
  151. try
  152. {
  153. if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  154. var cosmosClient = _azureCosmos.GetCosmosClient();
  155. var tableClient = _azureStorage.GetCloudTableClient();
  156. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  157. //企業聯絡人 刪除該企業聯絡資訊
  158. List<string> bizUsersIdList = new List<string>();
  159. StringBuilder sql = new($"SELECT VALUE c.id FROM c JOIN r IN c.relation WHERE r.bizId = '{id}'");
  160. await foreach (var items in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<string>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") })) {
  161. bizUsersIdList.Add(items);
  162. }
  163. if(bizUsersIdList.Count > 0)
  164. {
  165. string bizUsersIdListStr = JsonSerializer.Serialize(bizUsersIdList);
  166. sql = new($"SELECT * FROM c WHERE ARRAY_CONTAINS({bizUsersIdListStr}, c.id, true)");
  167. await foreach (BizUsers item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  168. {
  169. item.relation.RemoveAll(r => r.bizId == $"{id}");
  170. await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(item, item.id, new PartitionKey("BizUsers"));
  171. }
  172. }
  173. //刪除企業
  174. await cosmosClient.GetContainer("TEAMModelOS", "Normal").DeleteItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
  175. //Log
  176. StringBuilder strMsg = new();
  177. strMsg.Append($"删除企业基础信息。删除ID:{id}");
  178. string type = "bizconfig-del";
  179. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  180. return Ok(new { state = RespondCode.Ok, id = id });
  181. }
  182. catch (Exception ex)
  183. {
  184. await _dingDing.SendBotMsg($"BI,{_option.Location} bizconfig/del-info \n {ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  185. return BadRequest();
  186. }
  187. }
  188. /// <summary>
  189. /// 重置秘钥 //已对接
  190. /// </summary>
  191. /// <param name="jsonElement"></param>
  192. /// <returns></returns>
  193. [ProducesDefaultResponseType]
  194. [AuthToken(Roles = "admin,rdc,assist")]
  195. [HttpPost("reset-secretkey")]
  196. public async Task<IActionResult> ResetSecretKey(JsonElement jsonElement)
  197. {
  198. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  199. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  200. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  201. var cosmosClient = _azureCosmos.GetCosmosClient();
  202. var tableClient = _azureStorage.GetCloudTableClient();
  203. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  204. ////分开部署,就不需要,一站多用时,取消注释
  205. //if ($"{site}".Equals(BIConst.Global))
  206. //{
  207. // cosmosClient = _azureCosmos.GetCosmosClient(BIConst.Global);
  208. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  209. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  210. //}
  211. BizConfig bizConfig = new();
  212. var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
  213. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  214. {
  215. using var json = await JsonDocument.ParseAsync(response.Content);
  216. bizConfig = json.ToObject<BizConfig>();
  217. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
  218. bizConfig.jti = auth_token.jti;
  219. bizConfig.token = auth_token.jwt;
  220. bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
  221. }
  222. return Ok(new { state =RespondCode.Ok, bizConfig });
  223. }
  224. /// <summary>
  225. /// 关联企业学校 //已对接
  226. /// </summary>
  227. /// <param name="jsonElement"></param>
  228. /// <returns></returns>
  229. [ProducesDefaultResponseType]
  230. [AuthToken(Roles = "admin,rdc,assist")]
  231. [HttpPost("rel-school")]
  232. public async Task<IActionResult> RelationSchool(JsonElement jsonElement)
  233. {
  234. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  235. if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
  236. if (!jsonElement.TryGetProperty("type", out JsonElement type)) return BadRequest();
  237. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  238. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  239. List<BizSchool> bizSchool = _schools.ToObject<List<BizSchool>>();
  240. var cosmosClient = _azureCosmos.GetCosmosClient();
  241. var tableClient = _azureStorage.GetCloudTableClient();
  242. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  243. ////分开部署,就不需要,一站多用时,取消注释
  244. //if ($"{site}".Equals(BIConst.Global))
  245. //{
  246. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  247. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  248. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  249. //}
  250. StringBuilder strMsg = new($"{tmdName}[{tmdId}]给");
  251. if ($"{type}".Equals("add"))
  252. {
  253. strMsg.Append($"企业关联学校;学校信息列表:");
  254. }
  255. else if ($"{type}".Equals("del"))
  256. {
  257. strMsg.Append("企业移除学校,学校信息列表:");
  258. }
  259. else { return Ok(new { state = RespondCode.ParamsError, msg = "类型错误" }); }
  260. List<BizSchool> noBizSc = new();
  261. BizConfig bizConfig = new();
  262. var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
  263. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  264. {
  265. using var json = await JsonDocument.ParseAsync(response.Content);
  266. bizConfig = json.ToObject<BizConfig>();
  267. foreach (var item in bizSchool)
  268. {
  269. var temp = bizConfig.schools.Find(f => f.id.Equals(item.id));
  270. if ($"{type}".Equals("add"))
  271. {
  272. if (temp == null)
  273. {
  274. bizConfig.schools.Add(item);
  275. strMsg.Append($"{item.name}[{item.id}]|");
  276. }
  277. else
  278. noBizSc.Add(temp);
  279. }
  280. else if ($"{type}".Equals("del"))
  281. {
  282. if (temp != null)
  283. {
  284. bizConfig.schools.Remove(temp);
  285. strMsg.Append($"{item.name}[{item.id}]|");
  286. }
  287. }
  288. }
  289. bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
  290. }
  291. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该企业" });
  292. //保存操作记录
  293. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, $"bizconfig-{type}School", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  294. if (noBizSc.Count > 0)
  295. return Ok(new { state = RespondCode.Created, bizConfig , noBizSc });
  296. return Ok(new { state = RespondCode.Ok, bizConfig });
  297. }
  298. /// <summary>
  299. /// 查询所有学校 如果传企业ID则查询与企业没有关联的学校 //已对接
  300. /// </summary>
  301. /// <param name="jsonElement"></param>
  302. /// <returns></returns>
  303. [ProducesDefaultResponseType]
  304. [HttpPost("get-schools")]
  305. public async Task<IActionResult> GetSchools(JsonElement jsonElement)
  306. {
  307. jsonElement.TryGetProperty("id", out JsonElement id);
  308. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  309. var cosmosClient = _azureCosmos.GetCosmosClient();
  310. var tableClient = _azureStorage.GetCloudTableClient();
  311. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  312. ////分开部署,就不需要,一站多用时,取消注释
  313. //if ($"{site}".Equals(BIConst.Global))
  314. //{
  315. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  316. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  317. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  318. //}
  319. List<OpenSchool> openSchools = new();
  320. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<OpenSchool>(queryText: "select c.id,c.code,c.name,c.picture from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  321. {
  322. openSchools.Add(item);
  323. }
  324. BizConfig bizConfig = new();
  325. if (!string.IsNullOrEmpty($"id"))
  326. {
  327. var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
  328. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  329. {
  330. using var json = await JsonDocument.ParseAsync(response.Content);
  331. bizConfig = json.ToObject<BizConfig>();
  332. if (bizConfig.schools.Count > 0)
  333. {
  334. foreach (var item in bizConfig.schools)
  335. {
  336. var temp = openSchools.Find(f => f.id.Equals(item.id));
  337. if (temp != null)
  338. openSchools.Remove(temp);
  339. }
  340. }
  341. }
  342. }
  343. return Ok(new { state = RespondCode.Ok , openSchools });
  344. }
  345. public record OpenSchool
  346. {
  347. public string id { get; set; }
  348. public string code { get; set; }
  349. public string name { get; set; }
  350. public string picture { get; set; }
  351. }
  352. }
  353. }