CompanyController.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Net.Http;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelBI.DI.BIAzureStorage;
  13. using TEAMModelBI.Filter;
  14. using TEAMModelBI.Models.Extension;
  15. using TEAMModelBI.Tool.Context;
  16. using TEAMModelBI.Tool.Extension;
  17. using TEAMModelOS.Models;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Models.Cosmos.BI;
  21. using TEAMModelOS.SDK.Models.Service;
  22. using TEAMModelOS.SDK.Models.Table;
  23. namespace TEAMModelBI.Controllers.BINormal
  24. {
  25. [Route("business")]
  26. [ApiController]
  27. public class CompanyController : ControllerBase
  28. {
  29. public readonly AzureCosmosFactory _azureCosmos;
  30. public readonly AzureStorageFactory _azureStorage;
  31. public readonly DingDing _dingDing;
  32. public readonly Option _option;
  33. private readonly IWebHostEnvironment _environment; //读取文件
  34. public CompanyController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment environment)
  35. {
  36. _azureCosmos = azureCosmos;
  37. _azureStorage = azureStorage;
  38. _dingDing = dingDing;
  39. _option = option?.Value;
  40. _environment = environment;
  41. }
  42. /// <summary>
  43. /// 查询企业信息结集合 若传ID查查询该账户的企业信息
  44. /// </summary>
  45. /// <param name="jsonElenent"></param>
  46. /// <returns></returns>
  47. [ProducesDefaultResponseType]
  48. //[AuthToken(Roles = "admin,rdc,assist,sales,company")]
  49. [HttpPost("get-info")]
  50. public async Task<IActionResult> GetInfo(JsonElement jsonElenent)
  51. {
  52. try
  53. {
  54. jsonElenent.TryGetProperty("id", out JsonElement id);
  55. jsonElenent.TryGetProperty("site", out JsonElement site);
  56. var cosmosClient = _azureCosmos.GetCosmosClient();
  57. var tableClient = _azureStorage.GetCloudTableClient();
  58. if ($"{site}".Equals(BIConst.GlobalSite))
  59. {
  60. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
  61. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  62. }
  63. var table = tableClient.GetTableReference("IESOpenApi");
  64. Dictionary<string, object> keyValue = new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" } };
  65. if (!string.IsNullOrEmpty($"{id}"))
  66. {
  67. keyValue.Add("RowKey", $"{id}");
  68. }
  69. List<BusinessConfig> companys = table.FindListByDictSync<BusinessConfig>(keyValue);
  70. //cosmosDB数据库
  71. //List<ReadCompany> companys = new();
  72. //StringBuilder sqlTxt = new("select c.id,c.pk,c.code,c.name,c.credit,c.picture,c.jti,c.secretKey,c.emall,c.mobile,c.password,c.webhookDomain,c.salt,c.createTime from c");
  73. //if (!string.IsNullOrEmpty($"{id}"))
  74. //{
  75. // sqlTxt.Append($" where c.id='{id}'");
  76. //}
  77. //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<ReadCompany>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
  78. //{
  79. // companys.Add(item);
  80. //}
  81. return Ok(new { state = 200, companys });
  82. }
  83. catch (Exception e)
  84. {
  85. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/get-info \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  86. return BadRequest();
  87. }
  88. }
  89. /// <summary>
  90. /// 新增企业信息和修改企业信息
  91. /// </summary>
  92. /// <param name="appCompany"></param>
  93. /// <returns></returns>
  94. [ProducesDefaultResponseType]
  95. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  96. [HttpPost("set-info")]
  97. public async Task<IActionResult> SetCompany([FromBody] BusinessConfig company, [FromHeader] string site)
  98. {
  99. try
  100. {
  101. //var (loginId, loginName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  102. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  103. StringBuilder strMsg = new();
  104. var cosmosClient = _azureCosmos.GetCosmosClient();
  105. var tableClient = _azureStorage.GetCloudTableClient();
  106. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  107. if ($"{site}".Equals(BIConst.GlobalSite))
  108. {
  109. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
  110. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  111. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  112. }
  113. List<BusinessConfig> companys = new();
  114. var table = tableClient.GetTableReference("IESOpenApi");
  115. string salt = Utils.CreatSaltString(8);
  116. string type = "";
  117. if (string.IsNullOrEmpty(company.RowKey))
  118. {
  119. company.RowKey = Guid.NewGuid().ToString();
  120. company.PartitionKey = "BusinessConfig";
  121. company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  122. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
  123. company.jti = auth_token.jti;
  124. company.token = auth_token.jwt;
  125. company = await table.SaveOrUpdate<BusinessConfig>(company);
  126. companys.Add(company);
  127. strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息。");
  128. type = "business-add";
  129. }
  130. else
  131. {
  132. List<BusinessConfig> companyTables = table.FindListByDictSync<BusinessConfig>(new Dictionary<string, object> { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{company.RowKey}" } });
  133. if (companyTables.Count > 0)
  134. {
  135. foreach (var item in companyTables)
  136. {
  137. item.name = company.name;
  138. item.credit = company.credit;
  139. item.picture = company.picture;
  140. //item.jti = company.jti;
  141. //item.secretKey = company.secretKey;
  142. item.email = company.email;
  143. item.mobile = company.mobile;
  144. //item.salt = company.salt;
  145. //item.password = company.password;
  146. item.domain = company.domain;
  147. strMsg.Append($"{item.name}【{item.RowKey}】修改企业基础信息:{item}。");
  148. companys.Add(item);
  149. }
  150. companyTables = await table.SaveOrUpdateAll<BusinessConfig>(companyTables);
  151. type = "business-add";
  152. }
  153. else
  154. {
  155. company.RowKey = Guid.NewGuid().ToString();
  156. company.PartitionKey = "BusinessConfig";
  157. company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  158. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
  159. company.jti = auth_token.jti;
  160. company.token = auth_token.jwt;
  161. company = await table.SaveOrUpdate<BusinessConfig>(company);
  162. companys.Add(company);
  163. strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息:{company}。");
  164. type = "business-add";
  165. }
  166. }
  167. //保存操作记录
  168. //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  169. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  170. return Ok(new { state = 200, companys });
  171. }
  172. catch (Exception e)
  173. {
  174. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-info \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  175. return BadRequest();
  176. }
  177. }
  178. /// <summary>
  179. /// 关联企业学校
  180. /// </summary>
  181. /// <param name="jsonElement"></param>
  182. /// <returns></returns>
  183. [ProducesDefaultResponseType]
  184. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  185. [HttpPost("set-companyschool")]
  186. public async Task<IActionResult> SetCompanySc(JsonElement jsonElement)
  187. {
  188. try
  189. {
  190. if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
  191. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  192. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  193. jsonElement.TryGetProperty("site", out JsonElement site);
  194. List<RecSc> recScs = _schools.ToObject<List<RecSc>>();
  195. var tableClient = _azureStorage.GetCloudTableClient();
  196. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  197. if ($"{site}".Equals(BIConst.GlobalSite))
  198. {
  199. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  200. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  201. }
  202. var table = tableClient.GetTableReference("IESOpenApi");
  203. StringBuilder strMsg = new($"{tmdName}[{tmdId}]关联企业ID:{id},学校列表:");
  204. List<BusinessSchool> busSchools = new();
  205. foreach (var item in recScs)
  206. {
  207. BusinessSchool businessSchool = new() { PartitionKey = $"BusinessSchool", RowKey = Guid.NewGuid().ToString(), school = $"{item.id}", bizid = $"{id}", name = $"{item.name}", picture = $"{item.picture}" };
  208. busSchools.Add(businessSchool);
  209. strMsg.Append($"{item.name}[{item.id}]|");
  210. }
  211. busSchools = await table.SaveOrUpdateAll<BusinessSchool>(busSchools);
  212. //保存操作记录
  213. //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  214. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-add", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  215. return Ok(new { state = 200, busSchools });
  216. }
  217. catch (Exception e)
  218. {
  219. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  220. return BadRequest();
  221. }
  222. }
  223. /// <summary>
  224. /// 依据企业ID查询关联的学校
  225. /// </summary>
  226. /// <param name="jsonElement"></param>
  227. /// <returns></returns>
  228. [ProducesDefaultResponseType]
  229. [HttpPost("get-companyschool")]
  230. public async Task<IActionResult> GetCompanySc(JsonElement jsonElement)
  231. {
  232. try
  233. {
  234. jsonElement.TryGetProperty("id", out JsonElement id);
  235. jsonElement.TryGetProperty("site", out JsonElement site);
  236. var tableClient = _azureStorage.GetCloudTableClient();
  237. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  238. if ($"{site}".Equals(BIConst.GlobalSite))
  239. {
  240. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  241. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  242. }
  243. var table = tableClient.GetTableReference("IESOpenApi");
  244. Dictionary<string, object> keyValue = new() { { "PartitionKey", $"BusinessSchool" } };
  245. if (!string.IsNullOrEmpty($"{id}"))
  246. {
  247. keyValue.Add("bizid", $"{id}");
  248. }
  249. List<BusinessSchool> busSchools = await table.FindListByDict<BusinessSchool>(keyValue);
  250. return Ok(new { state = 200, busSchools });
  251. }
  252. catch (Exception e)
  253. {
  254. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/get-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  255. return BadRequest();
  256. }
  257. }
  258. /// <summary>
  259. /// 删除企业关联学校
  260. /// </summary>
  261. /// <param name="jsonElement"></param>
  262. /// <returns></returns>
  263. [ProducesDefaultResponseType]
  264. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  265. [HttpPost("del-companysc")]
  266. public async Task<IActionResult> DelCompanySc(JsonElement jsonElement)
  267. {
  268. if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  269. if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
  270. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  271. jsonElement.TryGetProperty("site", out JsonElement site);
  272. List<string> schools = _schools.ToObject<List<string>>();
  273. var tableClient = _azureStorage.GetCloudTableClient();
  274. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  275. if ($"{site}".Equals(BIConst.GlobalSite))
  276. {
  277. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  278. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  279. }
  280. var table = tableClient.GetTableReference("IESOpenApi");
  281. StringBuilder strMsg = new($"{tmdName}[{tmdId}]删除企业关联学校,企业ID:{id},学校列表:");
  282. List<string> noSc = new();
  283. foreach (var school in schools)
  284. {
  285. string sqlTxt = $"PartitionKey eq 'BusinessSchool' and bizid eq '{id}' and school eq '{school}'";
  286. List<BusinessSchool> busSc = await table.QueryWhereString<BusinessSchool>(sqlTxt);
  287. if (busSc.Count > 0)
  288. {
  289. strMsg.Append($"{school}|");
  290. await table.DeleteAll(busSc);
  291. }
  292. else
  293. noSc.Add(school);
  294. }
  295. //保存操作记录
  296. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-del", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  297. if (noSc.Count > 0)
  298. return Ok(new { state = 201, noSc });
  299. else
  300. return Ok(new { state = 200 });
  301. }
  302. /// <summary>
  303. /// 重置密码和token
  304. /// </summary>
  305. /// <param name="jsonElement"></param>
  306. /// <returns></returns>
  307. [ProducesDefaultResponseType]
  308. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  309. [HttpPost("reset-bus")]
  310. public async Task<IActionResult> ResetBus(JsonElement jsonElement)
  311. {
  312. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  313. if (!jsonElement.TryGetProperty("resetType", out JsonElement resetType)) return BadRequest();
  314. jsonElement.TryGetProperty("site", out JsonElement site);
  315. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  316. var tableClient = _azureStorage.GetCloudTableClient();
  317. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  318. if ($"{site}".Equals(BIConst.GlobalSite))
  319. {
  320. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  321. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  322. }
  323. var table = tableClient.GetTableReference("IESOpenApi");
  324. List<BusinessConfig> busConfigs = await table.FindListByDict<BusinessConfig>(new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{id}" } });
  325. if (busConfigs.Count > 0)
  326. {
  327. foreach (var busConfig in busConfigs)
  328. {
  329. if ($"{resetType}".Equals("pwd"))
  330. {
  331. string salt = Utils.CreatSaltString(8);
  332. }
  333. if ($"{resetType}".Equals("token"))
  334. {
  335. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, busConfig.RowKey, _option.JwtSecretKey, "business");
  336. busConfig.jti = auth_token.jti;
  337. busConfig.token = auth_token.jwt;
  338. }
  339. }
  340. if ($"{resetType}".Equals("pwd") || $"{resetType}".Equals("token"))
  341. {
  342. await table.SaveOrUpdateAll(busConfigs);
  343. return Ok(new { state = 200, busConfigs });
  344. }
  345. else
  346. return Ok(new { state = 400, msg = "重置类型错误!" });
  347. }
  348. else
  349. return Ok(new { state = 404, msg = "未找到企业信息" });
  350. }
  351. /// <summary>
  352. /// 关联时传入的学校信息
  353. /// </summary>
  354. public record RecSc
  355. {
  356. public string id { get; set; }
  357. public string name { get; set; }
  358. public string picture { get; set; }
  359. }
  360. /// <summary>
  361. /// 显示第三方信息
  362. /// </summary>
  363. public record ReadCompany
  364. {
  365. public string id { get; set; }
  366. public string code { get; set; }
  367. public string name { get; set; }
  368. public string credit { get; set; }
  369. public string picture { get; set; }
  370. public string jti { get; set; }
  371. public string secretKey { get; set; }
  372. public string emall { get; set; }
  373. public string mobile { get; set; }
  374. public string salt { get; set; }
  375. public string password { get; set; }
  376. public string webhookDomain { get; set; }
  377. public long createTime { get; set; }
  378. }
  379. }
  380. }