CompanyController.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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.Extension;
  16. using TEAMModelOS.Models;
  17. using TEAMModelOS.SDK.Context.BI;
  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.BITable
  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.Global))
  59. {
  60. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  61. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  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.Global))
  108. {
  109. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  110. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  111. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  112. }
  113. List<BusinessConfig> companys = new();
  114. BusinessUser businessUser = new();
  115. BizRelUser bizRelUser = new();
  116. var table = tableClient.GetTableReference("IESOpenApi");
  117. string salt = Utils.CreatSaltString(8);
  118. string type = "";
  119. if (string.IsNullOrEmpty(company.RowKey))
  120. {
  121. company.RowKey = Guid.NewGuid().ToString();
  122. company.PartitionKey = "BusinessConfig";
  123. company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  124. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
  125. company.jti = auth_token.jti;
  126. company.token = auth_token.jwt;
  127. company = await table.SaveOrUpdate<BusinessConfig>(company);
  128. businessUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{company.mobile}", mobile = company.mobile, salt = salt, pwd = Utils.HashedPassword($"{company.mobile}", salt) };
  129. businessUser = await table.SaveOrUpdate<BusinessUser>(businessUser);
  130. bizRelUser = new() { RowKey = $"{businessUser.RowKey}-{company.RowKey}",userId= $"{company.RowKey}", bizId = $"{company.RowKey}",bizName = company.name ,roles = "admin" };
  131. bizRelUser = await table.SaveOrUpdate<BizRelUser>(bizRelUser);
  132. companys.Add(company);
  133. strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息。新增该企业管理员信息{businessUser.name}【{businessUser.RowKey}】。");
  134. type = "business-add";
  135. }
  136. else
  137. {
  138. //List<BusinessConfig> companyTables = table.FindListByDictSync<BusinessConfig>(new Dictionary<string, object> { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{company.RowKey}" } });
  139. BusinessConfig businessConfig = table.Get<BusinessConfig>("BusinessConfig", $"{company.RowKey}");
  140. if (businessConfig != null)
  141. {
  142. company.PartitionKey = businessConfig.PartitionKey;
  143. company.RowKey = businessConfig.RowKey;
  144. company.credit = businessConfig.credit;
  145. company.jti = businessConfig.jti;
  146. company.token = businessConfig.token;
  147. businessConfig = await table.SaveOrUpdate<BusinessConfig>(company);
  148. companys.Add(businessConfig);
  149. strMsg.Append($"{company.name}【{company.RowKey}】修改企业基础信息:{company}。");
  150. type = "business-add";
  151. }
  152. else
  153. {
  154. company.RowKey = Guid.NewGuid().ToString();
  155. company.PartitionKey = "BusinessConfig";
  156. company.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  157. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, company.RowKey, _option.JwtSecretKey, "business");
  158. company.jti = auth_token.jti;
  159. company.token = auth_token.jwt;
  160. company = await table.SaveOrUpdate<BusinessConfig>(company);
  161. businessUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{company.mobile}", mobile = company.mobile, salt = salt, pwd = Utils.HashedPassword($"{company.mobile}", salt) };
  162. businessUser = await table.SaveOrUpdate<BusinessUser>(businessUser);
  163. bizRelUser = new() { RowKey = $"{businessUser.RowKey}-{company.RowKey}", userId = $"{company.RowKey}", bizId = $"{company.RowKey}", bizName = company.name, roles = "admin" };
  164. bizRelUser = await table.SaveOrUpdate<BizRelUser>(bizRelUser);
  165. companys.Add(company);
  166. strMsg.Append($"{company.name}【{company.RowKey}】新增企业基础信息:{company}。新增该企业管理员信息{businessUser.name}【{businessUser.RowKey}】。");
  167. type = "business-add";
  168. }
  169. }
  170. //保存操作记录
  171. //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  172. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  173. return Ok(new { state = 200, companys, businessUser });
  174. }
  175. catch (Exception e)
  176. {
  177. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-info \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  178. return BadRequest();
  179. }
  180. }
  181. /// <summary>
  182. /// 关联企业学校
  183. /// </summary>
  184. /// <param name="jsonElement"></param>
  185. /// <returns></returns>
  186. [ProducesDefaultResponseType]
  187. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  188. [HttpPost("set-companyschool")]
  189. public async Task<IActionResult> SetCompanySc(JsonElement jsonElement)
  190. {
  191. try
  192. {
  193. if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
  194. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  195. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  196. jsonElement.TryGetProperty("site", out JsonElement site);
  197. List<RecSc> recScs = _schools.ToObject<List<RecSc>>();
  198. var tableClient = _azureStorage.GetCloudTableClient();
  199. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  200. if ($"{site}".Equals(BIConst.Global))
  201. {
  202. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  203. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  204. }
  205. var table = tableClient.GetTableReference("IESOpenApi");
  206. StringBuilder strMsg = new($"{tmdName}[{tmdId}]关联企业ID:{id},学校列表:");
  207. List<BusinessSchool> busSchools = new();
  208. foreach (var item in recScs)
  209. {
  210. BusinessSchool businessSchool = new() { PartitionKey = $"BusinessSchool", RowKey = Guid.NewGuid().ToString(), school = $"{item.id}", bizid = $"{id}", name = $"{item.name}", picture = $"{item.picture}" };
  211. busSchools.Add(businessSchool);
  212. strMsg.Append($"{item.name}[{item.id}]|");
  213. }
  214. busSchools = await table.SaveOrUpdateAll<BusinessSchool>(busSchools);
  215. //保存操作记录
  216. //await _azureStorage.SaveBILog(type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
  217. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-add", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  218. return Ok(new { state = 200, busSchools });
  219. }
  220. catch (Exception e)
  221. {
  222. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/set-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  223. return BadRequest();
  224. }
  225. }
  226. /// <summary>
  227. /// 依据企业ID查询关联的学校
  228. /// </summary>
  229. /// <param name="jsonElement"></param>
  230. /// <returns></returns>
  231. [ProducesDefaultResponseType]
  232. [HttpPost("get-companyschool")]
  233. public async Task<IActionResult> GetCompanySc(JsonElement jsonElement)
  234. {
  235. try
  236. {
  237. jsonElement.TryGetProperty("id", out JsonElement id);
  238. jsonElement.TryGetProperty("site", out JsonElement site);
  239. var tableClient = _azureStorage.GetCloudTableClient();
  240. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  241. if ($"{site}".Equals(BIConst.Global))
  242. {
  243. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  244. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  245. }
  246. var table = tableClient.GetTableReference("IESOpenApi");
  247. Dictionary<string, object> keyValue = new() { { "PartitionKey", $"BusinessSchool" } };
  248. if (!string.IsNullOrEmpty($"{id}"))
  249. {
  250. keyValue.Add("bizid", $"{id}");
  251. }
  252. List<BusinessSchool> busSchools = await table.FindListByDict<BusinessSchool>(keyValue);
  253. return Ok(new { state = 200, busSchools });
  254. }
  255. catch (Exception e)
  256. {
  257. await _dingDing.SendBotMsg($"BI,{_option.Location} , /business/get-companyschool \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
  258. return BadRequest();
  259. }
  260. }
  261. /// <summary>
  262. /// 删除企业关联学校
  263. /// </summary>
  264. /// <param name="jsonElement"></param>
  265. /// <returns></returns>
  266. [ProducesDefaultResponseType]
  267. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  268. [HttpPost("del-companysc")]
  269. public async Task<IActionResult> DelCompanySc(JsonElement jsonElement)
  270. {
  271. if(!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  272. if (!jsonElement.TryGetProperty("schools", out JsonElement _schools)) return BadRequest();
  273. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  274. jsonElement.TryGetProperty("site", out JsonElement site);
  275. List<string> schools = _schools.ToObject<List<string>>();
  276. var tableClient = _azureStorage.GetCloudTableClient();
  277. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  278. if ($"{site}".Equals(BIConst.Global))
  279. {
  280. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  281. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  282. }
  283. var table = tableClient.GetTableReference("IESOpenApi");
  284. StringBuilder strMsg = new($"{tmdName}[{tmdId}]删除企业关联学校,企业ID:{id},学校列表:");
  285. List<string> noSc = new();
  286. foreach (var school in schools)
  287. {
  288. string sqlTxt = $"PartitionKey eq 'BusinessSchool' and bizid eq '{id}' and school eq '{school}'";
  289. List<BusinessSchool> busSc = await table.QueryWhereString<BusinessSchool>(sqlTxt);
  290. if (busSc.Count > 0)
  291. {
  292. strMsg.Append($"{school}|");
  293. await table.DeleteAll(busSc);
  294. }
  295. else
  296. noSc.Add(school);
  297. }
  298. //保存操作记录
  299. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "BusinessSchool-del", strMsg.ToString(), _dingDing, httpContext: HttpContext);
  300. if (noSc.Count > 0)
  301. return Ok(new { state = 201, noSc });
  302. else
  303. return Ok(new { state = 200 });
  304. }
  305. /// <summary>
  306. /// 重置密码和token
  307. /// </summary>
  308. /// <param name="jsonElement"></param>
  309. /// <returns></returns>
  310. [ProducesDefaultResponseType]
  311. [AuthToken(Roles = "admin,rdc,assist,sales,company")]
  312. [HttpPost("reset-bus")]
  313. public async Task<IActionResult> ResetBus(JsonElement jsonElement)
  314. {
  315. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  316. if (!jsonElement.TryGetProperty("resetType", out JsonElement resetType)) return BadRequest();
  317. jsonElement.TryGetProperty("site", out JsonElement site);
  318. var (tmdId, tmdName, pic, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  319. var tableClient = _azureStorage.GetCloudTableClient();
  320. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  321. if ($"{site}".Equals(BIConst.Global))
  322. {
  323. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  324. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  325. }
  326. var table = tableClient.GetTableReference("IESOpenApi");
  327. List<BusinessConfig> busConfigs = await table.FindListByDict<BusinessConfig>(new Dictionary<string, object>() { { "PartitionKey", "BusinessConfig" }, { "RowKey", $"{id}" } });
  328. if (busConfigs.Count > 0)
  329. {
  330. foreach (var busConfig in busConfigs)
  331. {
  332. if ($"{resetType}".Equals("token"))
  333. {
  334. var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, busConfig.RowKey, _option.JwtSecretKey, "business");
  335. busConfig.jti = auth_token.jti;
  336. busConfig.token = auth_token.jwt;
  337. }
  338. }
  339. if ($"{resetType}".Equals("token"))
  340. {
  341. await table.SaveOrUpdateAll(busConfigs);
  342. return Ok(new { state = 200, busConfigs });
  343. }
  344. else
  345. return Ok(new { state = 400, msg = "重置类型错误!" });
  346. }
  347. else
  348. return Ok(new { state = 404, msg = "未找到企业信息" });
  349. }
  350. /// <summary>
  351. /// 关联时传入的学校信息
  352. /// </summary>
  353. public record RecSc
  354. {
  355. public string id { get; set; }
  356. public string name { get; set; }
  357. public string picture { get; set; }
  358. }
  359. /// <summary>
  360. /// 显示第三方信息
  361. /// </summary>
  362. public record ReadCompany
  363. {
  364. public string id { get; set; }
  365. public string code { get; set; }
  366. public string name { get; set; }
  367. public string credit { get; set; }
  368. public string picture { get; set; }
  369. public string jti { get; set; }
  370. public string secretKey { get; set; }
  371. public string emall { get; set; }
  372. public string mobile { get; set; }
  373. public string salt { get; set; }
  374. public string password { get; set; }
  375. public string webhookDomain { get; set; }
  376. public long createTime { get; set; }
  377. }
  378. }
  379. }