MarketCustomerResourcesController.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  1. using Aspose.Cells;
  2. using EyeSoft.Extensions;
  3. using NPOI.SS.Formula.Functions;
  4. using OASystem.API.OAMethodLib;
  5. using OASystem.Domain.AesEncryption;
  6. using OASystem.Domain.Attributes;
  7. using OASystem.Domain.Dtos.CRM;
  8. using OASystem.Domain.Entities.Customer;
  9. using OASystem.Infrastructure.Repositories.CRM;
  10. using OASystem.RedisRepository;
  11. using System.Collections;
  12. using System.Data;
  13. using System.Diagnostics;
  14. using System.Net;
  15. using UAParser;
  16. namespace OASystem.API.Controllers
  17. {
  18. /// <summary>
  19. /// 市场客户资料
  20. /// </summary>
  21. [Route("api/[controller]/[action]")]
  22. public class MarketCustomerResourcesController : ControllerBase
  23. {
  24. private readonly NewClientDataRepository _clientDataRepository;
  25. private readonly SqlSugarClient _sqlSugar;
  26. private string keyName = "newClient_SearchKey";
  27. /// <summary>
  28. /// 初始化
  29. /// </summary>
  30. public MarketCustomerResourcesController(NewClientDataRepository clientDataRepository, SqlSugarClient sqlSugar)
  31. {
  32. this._clientDataRepository = clientDataRepository;
  33. _sqlSugar = sqlSugar;
  34. }
  35. /// <summary>
  36. /// 客户资料数据
  37. /// 基础数据
  38. /// </summary>
  39. /// <returns></returns>
  40. [HttpPost]
  41. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  42. public async Task<IActionResult> MarketCustomerInit(MarketCustomerInitDto dto)
  43. {
  44. JsonView jw = new JsonView();
  45. try
  46. {
  47. Result resultData = await _clientDataRepository._Init(dto);
  48. if (resultData.Code == 0)
  49. {
  50. jw = JsonView(true, "查询成功!", resultData.Data);
  51. }
  52. else
  53. {
  54. jw = JsonView(false, resultData.Msg);
  55. }
  56. }
  57. catch (Exception)
  58. {
  59. jw = JsonView(false, "程序错误!");
  60. }
  61. return Ok(jw);
  62. }
  63. /// <summary>
  64. /// 查询客户资料数据
  65. /// </summary>
  66. /// <returns></returns>
  67. [HttpPost]
  68. //[ApiLog("Crm_NewClientData", OperationEnum.List)]
  69. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  70. public async Task<IActionResult> QueryNewClientData(NewClientDataQueryDto dto)
  71. {
  72. #region 参数验证
  73. if (dto.OperationUserId < 0)
  74. return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  75. if (dto.PortType < 0)
  76. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  77. #endregion
  78. JsonView jw = new JsonView();
  79. var startTime = DateTime.UtcNow;
  80. try
  81. {
  82. Result resultData = await _clientDataRepository.QueryNewClientData(dto);
  83. if (resultData.Code == 0)
  84. {
  85. #region 客户资料表操作记录
  86. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.NoOperation, dto.OperationUserId, 0, "");
  87. #endregion
  88. jw = JsonView(true, resultData.Msg, resultData.Data);
  89. }
  90. else
  91. {
  92. jw = JsonView(false, resultData.Msg);
  93. }
  94. }
  95. catch (Exception)
  96. {
  97. jw = JsonView(false, "程序错误!");
  98. }
  99. finally
  100. {
  101. using var ssg = _sqlSugar.CopyNew();
  102. var status = HttpContext.Response.StatusCode.ToString();
  103. _ = Task.Run(async () =>
  104. {
  105. try
  106. {
  107. string remoteIp = string.Empty,
  108. location = string.Empty;
  109. // 检查请求头中的X-Forwarded-For,以获取真实的客户端IP地址
  110. if (HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
  111. {
  112. remoteIp = HttpContext.Request.Headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
  113. }
  114. else
  115. {
  116. remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
  117. }
  118. var task = GetIpInfo(remoteIp);
  119. string deviceType = string.Empty, browser = string.Empty, os = string.Empty;
  120. var userAgent = HttpContext.Request.Headers["User-Agent"].FirstOrDefault();
  121. if (!string.IsNullOrEmpty(userAgent))
  122. {
  123. // 解析User-Agent头
  124. var parser = Parser.GetDefault();
  125. var client = parser.Parse(userAgent);
  126. // 提取浏览器信息
  127. browser = client.UA.Family; // 浏览器名称
  128. var browserVersion = client.UA.Major + "." + client.UA.Minor + "." + client.UA.Patch; // 浏览器版本
  129. browser += $"({browserVersion})";
  130. // 提取操作系统信息
  131. os = client.OS.Family; // 操作系统名称
  132. var osVersion = string.Empty; // 操作系统版本
  133. if (!string.IsNullOrEmpty(client.OS.Major)) osVersion += client.OS.Major;
  134. if (!string.IsNullOrEmpty(client.OS.Minor)) osVersion += "." + client.OS.Minor;
  135. if (!string.IsNullOrEmpty(client.OS.Patch)) osVersion += "." + client.OS.Patch;
  136. if (!string.IsNullOrEmpty(osVersion)) os += $"({osVersion})";
  137. // 提取设备信息
  138. deviceType = client.Device.Family; // 设备类型,如 'mobile', 'tablet', 'desktop' 等
  139. }
  140. // 记录请求结束时间
  141. var endTime = DateTime.UtcNow;
  142. // 计算耗时
  143. var duration = (long)(endTime - startTime).TotalMilliseconds;
  144. //等待任务进行
  145. (remoteIp, location) = await task;
  146. //单独记录操作
  147. var logInfo = new Crm_TableOperationRecord()
  148. {
  149. TableName = "Crm_NewClientData",
  150. PortType = dto.PortType,
  151. OperationItem = OperationEnum.List,
  152. DataId = 0,
  153. RequestUrl = "/api/MarketCustomerResources/QueryNewClientData",
  154. RemoteIp = remoteIp,
  155. Location = location,
  156. RequestParam = JsonConvert.SerializeObject(dto),
  157. ReturnResult = JsonConvert.SerializeObject(jw),
  158. Elapsed = duration,
  159. Status = status,
  160. CreateUserId = dto.OperationUserId,
  161. UpdatePreData = "",
  162. UpdateBefData = "",
  163. Browser = browser,
  164. Os = os,
  165. DeviceType = deviceType,
  166. };
  167. // 存储到数据库
  168. await ssg.Insertable(logInfo).ExecuteCommandAsync();
  169. }
  170. catch (Exception ex)
  171. {
  172. }
  173. });
  174. }
  175. return Ok(jw);
  176. }
  177. /// <summary>
  178. /// 客户资料数据
  179. /// Details
  180. /// </summary>
  181. /// <returns></returns>
  182. [HttpPost]
  183. [ApiLog("Crm_NewClientData", OperationEnum.Details)]
  184. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  185. public async Task<IActionResult> PostNewClientDataDetails(NewClientDataDetailsDto dto)
  186. {
  187. #region 参数验证
  188. if (dto.Id < 0)
  189. return Ok(JsonView(false, "请传入有效的Id参数!"));
  190. if (dto.UserId < 0)
  191. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  192. if (dto.PortType < 0)
  193. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  194. #endregion
  195. JsonView jw = new JsonView();
  196. try
  197. {
  198. Result resultData = await _clientDataRepository._Details(dto.PortType, dto.Id);
  199. if (resultData.Code == 0)
  200. {
  201. #region 客户资料表操作记录
  202. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Details, dto.UserId, dto.Id, "");
  203. #endregion
  204. jw = JsonView(true, "查询成功!", resultData.Data);
  205. }
  206. else
  207. {
  208. jw = JsonView(false, resultData.Msg);
  209. }
  210. }
  211. catch (Exception)
  212. {
  213. jw = JsonView(false, "程序错误!");
  214. }
  215. return Ok(jw);
  216. }
  217. /// <summary>
  218. /// 客户资料操作(Status:1.新增,2.修改)
  219. /// </summary>
  220. /// <param name="dto"></param>
  221. /// <returns></returns>
  222. [HttpPost]
  223. [ApiLog("Crm_NewClientData", OperationEnum.NoOperation)]
  224. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  225. public async Task<IActionResult> NewClientOp(NewClientOpDto dto)
  226. {
  227. #region 参数验证
  228. if (dto.CreateUserId < 0)
  229. {
  230. return Ok(JsonView(false, "请传入有效的CreateUserId参数!"));
  231. }
  232. if (dto.PortType < 0)
  233. {
  234. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  235. }
  236. #endregion
  237. try
  238. {
  239. Domain.Result result = await _clientDataRepository.NewClientOp(dto);
  240. if (result.Code != 0)
  241. {
  242. return Ok(JsonView(false, result.Msg));
  243. }
  244. #region 客户资料操作记录
  245. //OperationEnum operationEnum = OperationEnum.NoOperation;
  246. //if (dto.Status == 1)
  247. //{
  248. // operationEnum = OperationEnum.Add;
  249. // dto.Id = Convert.ToInt32(result.Data);
  250. //}
  251. //else if (dto.Status == 2) operationEnum = OperationEnum.Edit;
  252. //await GeneralMethod.NewClientOperationRecord(dto.PortType, operationEnum, dto.CreateUserId, dto.Id, "");
  253. #endregion
  254. //this.keyName += "_" + dto.CreateUserId;
  255. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  256. //if (exists) await RedisFactory.CreateRedisRepository().KeyDeleteAsync(keyName);
  257. return Ok(JsonView(true, result.Msg + "Id:" + dto.Id));
  258. }
  259. catch (Exception ex)
  260. {
  261. return Ok(JsonView(false, "程序错误!Msg:" + ex.Message));
  262. }
  263. }
  264. /// <summary>
  265. /// 新客户资料操作(删除)
  266. /// </summary>
  267. /// <param name="dto"></param>
  268. /// <returns></returns>
  269. [HttpPost]
  270. [ApiLog("Crm_NewClientData", OperationEnum.Del)]
  271. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  272. public async Task<IActionResult> NewClientDel(DelBaseDto dto)
  273. {
  274. #region 参数验证
  275. if (dto.Id < 0)
  276. {
  277. return Ok(JsonView(false, "请传入有效的Id参数!"));
  278. }
  279. if (dto.DeleteUserId < 0)
  280. {
  281. return Ok(JsonView(false, "请传入有效的DeleteUserId参数!"));
  282. }
  283. if (dto.PortType < 0)
  284. {
  285. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  286. }
  287. #endregion
  288. var res = await _clientDataRepository.DelNewClientData(dto);
  289. if (res.Code != 0)
  290. {
  291. return Ok(JsonView(false, "删除失败"));
  292. }
  293. #region 客户资料表操作记录
  294. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Del, dto.DeleteUserId, dto.Id, "");
  295. #endregion
  296. //this.keyName += "_" + dto.DeleteUserId;
  297. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  298. //if (exists) await RedisFactory.CreateRedisRepository().KeyDeleteAsync(keyName);
  299. return Ok(JsonView(true, "删除成功!"));
  300. }
  301. /// <summary>
  302. /// 获取下拉列表数据和单条数据信息
  303. /// </summary>
  304. /// <param name="dto"></param>
  305. /// <returns></returns>
  306. [HttpPost]
  307. [ApiLog("Crm_NewClientData", OperationEnum.Details)]
  308. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  309. public async Task<IActionResult> QuerySelectAndSingleData(QuerySingleDto dto)
  310. {
  311. JsonView jw = new JsonView();
  312. var result = await _clientDataRepository.QuerySelectAndSingleData(dto);
  313. if (result.Code == 0)
  314. {
  315. #region 客户资料表操作记录
  316. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Details, dto.UserId, dto.Id, "");
  317. #endregion
  318. jw = JsonView(true, result.Msg, result.Data);
  319. }
  320. else
  321. {
  322. jw = JsonView(false, result.Msg);
  323. }
  324. return Ok(jw);
  325. }
  326. /// <summary>
  327. /// 获取现有负责人
  328. /// </summary>
  329. /// <returns></returns>
  330. [HttpPost]
  331. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  332. public async Task<IActionResult> QueryUserSelect()
  333. {
  334. Result resTable = _clientDataRepository.QueryUserSelect();
  335. return Ok(JsonView(true, resTable.Msg, resTable.Data));
  336. }
  337. /// <summary>
  338. /// 获取出团数据
  339. /// </summary>
  340. /// <returns></returns>
  341. [HttpPost]
  342. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  343. public async Task<IActionResult> QueryNumberGroups()
  344. {
  345. var result = await _clientDataRepository.QueryNumberGroups();
  346. if (result.Code != 0)
  347. {
  348. return Ok(JsonView(false, result.Msg));
  349. }
  350. return Ok(JsonView(true, result.Msg, result.Data));
  351. }
  352. /// <summary>
  353. /// 新客户资料操作
  354. /// 批量分配
  355. /// </summary>
  356. /// <param name="dto"></param>
  357. /// <returns></returns>
  358. [HttpPost]
  359. [ApiLog("Crm_NewClientData", OperationEnum.BatchAssignment)]
  360. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  361. public async Task<IActionResult> PostBatchAssignment(BatchAssignmentDto dto)
  362. {
  363. #region 参数验证
  364. if (dto.UserId < 0)
  365. {
  366. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  367. }
  368. if (dto.PortType < 0)
  369. {
  370. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  371. }
  372. #endregion
  373. var res = await _clientDataRepository._BatchAssignment(dto);
  374. if (res.Code != 0)
  375. {
  376. return Ok(JsonView(false, res.Msg));
  377. }
  378. return Ok(JsonView(true, "操作成功!"));
  379. }
  380. private Dictionary<int, List<int>> MCRSetting()
  381. {
  382. Dictionary<int, List<int>> keyValuePairs = new Dictionary<int, List<int>>();
  383. keyValuePairs.Add(419, new List<int>() //四川
  384. {
  385. 376,377,378,381,382,387,388,389,390,753,754,1296,1303
  386. });
  387. keyValuePairs.Add(420, new List<int>() //云南
  388. {
  389. 407,408,409,410,449,451,452,453,567,754,1297,1304
  390. });
  391. keyValuePairs.Add(421, new List<int>() { 424, 425, 426, 427, 428, 429, 754, 1298, 1305, 1307, 1306 }); // 贵州
  392. keyValuePairs.Add(422, new List<int>() { 415, 416, 754, 1317, 1316, 1315, 455, 1321, 1320, 1319, 1318 }); // 西藏
  393. keyValuePairs.Add(423, new List<int>() { 417, 418, 454, 456, 754, 1313, 1314 }); // 重庆
  394. keyValuePairs.Add(578, new List<int>() { 581, 582, 583, 754, 1299, 1300 }); // 青海
  395. keyValuePairs.Add(605, new List<int>() { 588, 589, 590, 591, 592, 593, 754, 1301, 1310, 1309, 1308 }); // 陕西
  396. keyValuePairs.Add(606, new List<int>() { 597, 598, 599, 600, 601, 602, 603, 604, 754, 1324, 1323, 1322 }); // 宁夏
  397. keyValuePairs.Add(625, new List<int>() { 617, 618, 619, 620, 621, 622, 622, 623, 624, 754, 1302, 1312, 1311 }); // 甘肃
  398. keyValuePairs.Add(634, new List<int>() { 630, 631, 632, 633, 754 }); // 新疆
  399. return keyValuePairs;
  400. }
  401. private Dictionary<int, List<int>> MCRSecondSetting()
  402. {
  403. Dictionary<int, List<int>> keyValuePairs = new Dictionary<int, List<int>>();
  404. // 四川
  405. keyValuePairs.Add(349, new List<int>() { 376, 378, 381, 387, 389, 1296 }); // 四川省级
  406. keyValuePairs.Add(350, new List<int>() { 377, 382, 388, 390, 1303 }); // 成都市级
  407. keyValuePairs.Add(348, new List<int>() { 387 }); // 四川地市州 - Explicitly assigning to ensure all source2 IDs are used
  408. keyValuePairs.Add(701, new List<int>() { 388 }); // 成都区市县
  409. // 云南
  410. keyValuePairs.Add(399, new List<int>() { 407, 408, 409, 410, 451 }); // 云南省级
  411. keyValuePairs.Add(400, new List<int>() { 449, 452, 453, 1297, 1304 }); // 昆明市级
  412. keyValuePairs.Add(450, new List<int>() { 410 }); // 云南地市州
  413. keyValuePairs.Add(566, new List<int>() { 567 }); // 昆明区市县
  414. // 贵州
  415. keyValuePairs.Add(401, new List<int>() { 424, 426, 427, 428, 1298 }); // 贵州省级
  416. keyValuePairs.Add(402, new List<int>() { 425, 429, 1306, 1307, 1305 }); // 贵阳市级
  417. keyValuePairs.Add(414, new List<int>() { 428 }); // 贵州地市州
  418. //keyValuePairs.Add(1305, new List<int>() { /* Add relevant IDs if available */ }); // 贵阳区市县 - Placeholder for now
  419. // 重庆
  420. keyValuePairs.Add(403, new List<int>() { 417, 418, 454, 456, 1314 }); // 重庆市级
  421. keyValuePairs.Add(404, new List<int>() { 1313 }); // 重庆区县 - No direct match in source1
  422. // 西藏
  423. keyValuePairs.Add(405, new List<int>() { 415, 1317, 1316, 1315 }); // 西藏自治区
  424. keyValuePairs.Add(406, new List<int>() { 455, 1321, 1320, 1319, 1318 }); // 拉萨市级
  425. keyValuePairs.Add(413, new List<int>() { 416 }); // 西藏地市州
  426. // 青海
  427. keyValuePairs.Add(579, new List<int>() { 581, 582, 583, 1300 }); // 青海省级
  428. keyValuePairs.Add(580, new List<int>() { 1299 }); // 青海市州县 (Includes 地市州)
  429. // 陕西
  430. keyValuePairs.Add(585, new List<int>() { 588, 589, 590, 591, 1301 }); // 陕西省级
  431. keyValuePairs.Add(586, new List<int>() { 589 }); // 陕西地市州
  432. keyValuePairs.Add(587, new List<int>() { 592, 593, 1309, 1310, 1308 }); // 西安市级
  433. //keyValuePairs.Add(1308, new List<int>() { /* Add relevant IDs if available */ }); // 西安区市县 - Placeholder
  434. // 宁夏
  435. keyValuePairs.Add(594, new List<int>() { 597, 598, 599, 600, 601, 1322 }); // 宁夏自治区 (Includes 地市州 and 区级)
  436. keyValuePairs.Add(595, new List<int>() { 597 }); // 宁夏地市州
  437. keyValuePairs.Add(596, new List<int>() { 598, 599, 600, 603, 604, 602, 1323, 1324 }); // 银川市级 (Includes 区级)
  438. //keyValuePairs.Add(602, new List<int>()); // 银川区市县 - No direct match, but could be considered covered by "区级"
  439. // 甘肃
  440. keyValuePairs.Add(614, new List<int>() { 617, 618, 619, 620, 621, 1302 }); // 甘肃省级
  441. keyValuePairs.Add(615, new List<int>() { 618 }); // 甘肃地市州
  442. keyValuePairs.Add(616, new List<int>() { 622, 623, 624, 1312, 1311 }); // 兰州市级
  443. //keyValuePairs.Add(1311, new List<int>() { /* Add relevant IDs if available */ }); // 兰州区市县 - Placeholder
  444. // 新疆
  445. keyValuePairs.Add(627, new List<int>() { 630, 631, 632, 1327, 1326, 1325 }); // 新疆自治区级
  446. keyValuePairs.Add(628, new List<int>() { 1326 }); // 新疆地市州 - No direct match
  447. keyValuePairs.Add(629, new List<int>() { 633, 1331, 1330, 1329, 1328 }); // 乌鲁木齐市级
  448. // 中央直属企业 (Special case)
  449. keyValuePairs.Add(351, new List<int>() { 754 }); // Using "未分级" for 中央直属企业
  450. return keyValuePairs;
  451. }
  452. private Dictionary<int, List<int>> MCRLvSetting()
  453. {
  454. var keyValuePairs = new Dictionary<int, List<int>>();
  455. // 四川 (419)
  456. keyValuePairs.Add(419, new List<int>() { 348, 349, 350, 701 }); // Includes all Sichuan-related IDs from source2
  457. // 云南 (420)
  458. keyValuePairs.Add(420, new List<int>() { 399, 400, 450, 566 }); // Includes all Yunnan-related IDs
  459. // 贵州 (421)
  460. keyValuePairs.Add(421, new List<int>() { 401, 402, 414 });
  461. // 西藏 (422)
  462. keyValuePairs.Add(422, new List<int>() { 405, 406, 413 });
  463. // 重庆 (423)
  464. keyValuePairs.Add(423, new List<int>() { 403, 404 });
  465. // 青海 (578)
  466. keyValuePairs.Add(578, new List<int>() { 579, 580, 626 }); // Includes 市州县 and 西宁市级
  467. // 陕西 (605)
  468. keyValuePairs.Add(605, new List<int>() { 585, 586, 587 });
  469. // 宁夏 (606)
  470. keyValuePairs.Add(606, new List<int>() { 594, 595, 596 });
  471. // 甘肃 (625)
  472. keyValuePairs.Add(625, new List<int>() { 614, 615, 616 });
  473. // 新疆 (634)
  474. keyValuePairs.Add(634, new List<int>() { 627, 628, 629 });
  475. // 未分级 (351) - You'll likely want to remove this as it's no longer a primary key.
  476. // keyValuePairs.Add(351, new List<int>()); //Remove this line.
  477. return keyValuePairs;
  478. }
  479. [HttpPost]
  480. public IActionResult QueryClientType(QueryClientTypeDto Dto)
  481. {
  482. var jw = JsonView(true, "获取成功!");
  483. var dic_lv = MCRLvSetting();
  484. var keyValuePairs = MCRSetting();
  485. ArrayList arr = new ArrayList();
  486. ArrayList lvArr = new ArrayList();
  487. var ids = new List<int>();
  488. var lvids = new List<int>();
  489. foreach (var item in Dto.SetDataIdArr)
  490. {
  491. if (keyValuePairs.Keys.Contains(item))
  492. {
  493. ids.AddRange(keyValuePairs[item]);
  494. }
  495. if (dic_lv.Keys.Contains(item))
  496. {
  497. lvids.AddRange(dic_lv[item]);
  498. }
  499. }
  500. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  501. .Where(u => ids.Contains(u.Id) && u.IsDel == 0)
  502. .Select(x => new { x.Id, x.Name, x.Remark })
  503. .ToList());
  504. if (arr.Count == 0)
  505. {
  506. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  507. .Where(u => u.STid == 37 && u.IsDel == 0)
  508. .Select(x => new { x.Id, x.Name, x.Remark }).ToList());
  509. }
  510. // 创建比较器实例
  511. IComparer remakeComparer = new RemakeComparer();
  512. // 使用ArrayList.Sort方法和自定义比较器对arr进行排序
  513. arr.Sort(remakeComparer);
  514. var rangelv = _sqlSugar.Queryable<Sys_SetData>()
  515. .Where(u => lvids.Contains(u.Id) && u.IsDel == 0)
  516. .Select(x => new { x.Id, x.Name })
  517. .ToList();
  518. lvArr.AddRange(rangelv);
  519. if (lvArr.Count == 0)
  520. {
  521. lvArr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  522. .Where(u => u.STid == 33 && u.IsDel == 0)
  523. .Select(x => new { x.Id, x.Name }).ToList());
  524. }
  525. jw.Data = new
  526. {
  527. TypeArr = arr,
  528. LvArr = lvArr,
  529. };
  530. return Ok(jw);
  531. }
  532. [HttpPost]
  533. public IActionResult QueryClientTypeSecond(QueryClientTypeDto Dto)
  534. {
  535. var jw = JsonView(true, "获取成功!");
  536. var keyValuePairs = MCRSecondSetting();
  537. ArrayList arr = new ArrayList();
  538. var ids = new List<int>();
  539. foreach (var item in Dto.SetDataIdArr)
  540. {
  541. if (keyValuePairs.Keys.Contains(item))
  542. {
  543. ids.AddRange(keyValuePairs[item]);
  544. }
  545. }
  546. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  547. .Where(u => ids.Contains(u.Id) && u.IsDel == 0)
  548. .Select(x => new { x.Id, x.Name, x.Remark })
  549. .ToList());
  550. if (arr.Count == 0)
  551. {
  552. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  553. .Where(u => u.STid == 37 && u.IsDel == 0)
  554. .Select(x => new { x.Id, x.Name, x.Remark }).ToList());
  555. }
  556. // 创建比较器实例
  557. IComparer remakeComparer = new RemakeComparer();
  558. // 使用ArrayList.Sort方法和自定义比较器对arr进行排序
  559. arr.Sort(remakeComparer);
  560. jw.Data = arr;
  561. return Ok(jw);
  562. }
  563. /// <summary>
  564. /// 客户资料数据 全信息导出 excel 下载
  565. /// </summary>
  566. /// <param name="dto"></param>
  567. /// <returns></returns>
  568. [HttpPost]
  569. [ApiLog("Crm_NewClientData", OperationEnum.Download)]
  570. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  571. public async Task<IActionResult> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)
  572. {
  573. #region 参数验证
  574. if (dto.OperationUserId < 0) return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  575. if (dto.PortType < 0) return Ok(JsonView(false, "请传入有效的PortType参数!"));
  576. if (dto.PageId < 0) return Ok(JsonView(false, "请传入有效的PageId参数!"));
  577. #endregion
  578. #region 页面操作权限验证
  579. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.OperationUserId, dto.PageId);
  580. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  581. #endregion
  582. var dt = await _clientDataRepository.NewClientDataExcelDownload(dto);
  583. if (dt != null)
  584. {
  585. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/公司客户资料导出模板.xlsx");
  586. var designer = new WorkbookDesigner();
  587. designer.Workbook = new Workbook(tempPath);
  588. designer.SetDataSource("NCDDT", dt);
  589. designer.Process();
  590. //文件名
  591. string fileName = $"公司客户资料(全信息导出){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  592. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/" + fileName);
  593. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
  594. #region 客户资料表操作记录
  595. var respose = JsonView(true, "成功", url);
  596. //var paramData = new
  597. //{
  598. // APIName = @"MarketCustomerResources/NewClientDataExcelDownload",
  599. // RequestParam = dto,
  600. // ResposeParam = respose
  601. //};
  602. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Download, dto.OperationUserId, 0, JsonConvert.SerializeObject(paramData));
  603. #endregion
  604. return Ok(respose);
  605. }
  606. return Ok(JsonView(false));
  607. }
  608. /// <summary>
  609. /// 客户资料数据 分权限导出 excel 下载
  610. /// </summary>
  611. /// <param name="dto"></param>
  612. /// <returns></returns>
  613. [HttpPost]
  614. [ApiLog("Crm_NewClientData", OperationEnum.Download)]
  615. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  616. public async Task<IActionResult> NewClientDataAuthorityExcelDownload(NewClientDataExcelDownloadDto dto)
  617. {
  618. #region 参数验证
  619. if (dto.OperationUserId < 0) return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  620. if (dto.PortType < 0) return Ok(JsonView(false, "请传入有效的PortType参数!"));
  621. if (dto.PageId < 0) return Ok(JsonView(false, "请传入有效的PageId参数!"));
  622. #endregion
  623. #region 页面操作权限验证
  624. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.OperationUserId, dto.PageId);
  625. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  626. #endregion
  627. var dt = await _clientDataRepository.NewClientDataExcelDownload(dto);
  628. if (dt != null)
  629. {
  630. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/公司客户资料分权限导出模板.xlsx");
  631. var designer = new WorkbookDesigner();
  632. designer.Workbook = new Workbook(tempPath);
  633. designer.SetDataSource("NCDDT", dt);
  634. designer.Process();
  635. //文件名
  636. string fileName = $"公司客户资料(分权限导出){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  637. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/" + fileName);
  638. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
  639. var respose = JsonView(true, "成功", url);
  640. return Ok(respose);
  641. }
  642. return Ok(JsonView(false));
  643. }
  644. /// <summary>
  645. /// 客户资料数据 历史记录 Init
  646. /// </summary>
  647. /// <param name="dto"></param>
  648. /// <returns></returns>
  649. [HttpPost]
  650. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  651. public async Task<IActionResult> NewClientDataRecordInit(NewClientDataRecordInitDto dto)
  652. {
  653. #region 参数验证
  654. if (dto.UserId < 0) return Ok(JsonView(false, MsgTips.UserId));
  655. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  656. if (dto.PageId < 0) return Ok(JsonView(false, MsgTips.PageId));
  657. #endregion
  658. #region 页面操作权限验证
  659. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  660. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  661. #endregion
  662. var enumfiltrates = new string[] { "NoOperation", "Audit", "Login" };
  663. var operations = EnumHelper.GetEnumDescriptions(typeof(OperationEnum), enumfiltrates);
  664. var operation1 = new List<dynamic>();
  665. foreach (var item in operations)
  666. {
  667. operation1.Add(new { value = item.Key, text = item.Value });
  668. }
  669. object userDatas = Array.Empty<object>();
  670. if (dto.UserId == 21)
  671. {
  672. var userIds = await _sqlSugar.Queryable<Crm_ClientDataAndUser>().Where(x => x.IsDel == 0).Select(x => x.usersId).Distinct().ToListAsync();
  673. if (userIds.Any())
  674. {
  675. userDatas = await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && userIds.Contains(x.Id)).Select(x => new { value = x.Id, text = x.CnName }).ToListAsync();
  676. }
  677. }
  678. var data = new
  679. {
  680. operations = operation1,
  681. userDatas = userDatas
  682. };
  683. return Ok(JsonView(data));
  684. }
  685. /// <summary>
  686. /// 客户资料数据 历史记录
  687. /// </summary>
  688. /// <param name="dto"></param>
  689. /// <returns></returns>
  690. [HttpPost]
  691. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  692. public async Task<IActionResult> NewClientDataRecord(NewClientDataRecordDto dto)
  693. {
  694. #region 参数验证
  695. if (dto.UserId < 0) return Ok(JsonView(false, MsgTips.UserId));
  696. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  697. if (dto.PageId < 0) return Ok(JsonView(false, MsgTips.PageId));
  698. #endregion
  699. #region 页面操作权限验证
  700. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  701. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  702. #endregion
  703. return Ok(await _clientDataRepository.NewClientDataRecord(dto));
  704. }
  705. #region 修改数据
  706. //[HttpPost]
  707. //public IActionResult SynchronizationData()
  708. //{
  709. // var keyValuePairs = new Dictionary<int, List<string>>
  710. // {
  711. // { 5, new List<string> { "省级部门", "省级单位" } },
  712. // { 10, new List<string> { "市州" } },
  713. // { 15, new List<string> { "省属国企" } },
  714. // { 20, new List<string> { "省属学校", "省属高校" } },
  715. // { 25, new List<string> { "省级行业协会", "省级社团", "省级联合会" , "省属行业协会", "民营企业", "地方国企" } },
  716. // { 30, new List<string> { "市级部门", "市级单位" } },
  717. // { 35, new List<string> { "区市县" } },
  718. // { 40, new List<string> { "市级国企", "市属国企" } },
  719. // { 45, new List<string> { "市属学校", "市属高校" } },
  720. // { 50, new List<string> { "市级行业协会", "市级社团", "市级联合会" } }
  721. // };
  722. // var setting = MCRSetting();
  723. // var arr = new List<List<Sys_SetData>>();
  724. // foreach (var item in setting.Keys)
  725. // {
  726. // var setDataList_DB = _sqlSugar.Queryable<Sys_SetData>()
  727. // .Where(x => x.IsDel == 0 && setting[item].Contains(x.Id))
  728. // .ToList();
  729. // foreach (var setData in setDataList_DB)
  730. // {
  731. // foreach (var lv in keyValuePairs.Keys)
  732. // {
  733. // var islv = keyValuePairs[lv].Where(x => setData.Name.Contains(x)).Count() > 0;
  734. // if (islv)
  735. // {
  736. // setData.Remark = lv.ToString();
  737. // }
  738. // }
  739. // }
  740. // arr.Add(setDataList_DB);
  741. // }
  742. // _sqlSugar.Updateable(arr.SelectMany(x => x).ToList()).UpdateColumns(x => new
  743. // {
  744. // x.Remark
  745. // }).ExecuteCommand();
  746. // return Ok(arr);
  747. //}
  748. [HttpPost]
  749. public IActionResult QueryData()
  750. {
  751. var db = _sqlSugar.Queryable<Crm_NewClientData>()
  752. .Where(x => x.IsDel == 0)
  753. .Select(x => new Crm_NewClientData
  754. {
  755. Id = x.Id,
  756. Client = x.Client,
  757. Category = x.Category,
  758. Location = x.Location,
  759. }).ToList();
  760. var count = 0;
  761. var updateid = new List<int>();
  762. foreach (var item in db)
  763. {
  764. EncryptionProcessor.DecryptProperties(item);
  765. if (!string.IsNullOrWhiteSpace(item.Location) && item.Location.Contains("重庆") && item.Category == 0)
  766. {
  767. count++;
  768. //if (!string.IsNullOrWhiteSpace(item.Client) && (item.Client.Contains("大学") || item.Client.Contains("学院")))
  769. {
  770. updateid.Add(item.Id);
  771. }
  772. }
  773. }
  774. var updateCount = _sqlSugar.Updateable<Crm_NewClientData>().Where(x => updateid.Contains(x.Id))
  775. .SetColumns(x => new Crm_NewClientData { Category = 456 }).ExecuteCommand();
  776. return Ok(new
  777. {
  778. notCount = count,
  779. updateCount = updateCount
  780. });
  781. }
  782. [HttpPost]
  783. public IActionResult InsertData()
  784. {
  785. string sql = $@"SELECT * FROM [dbo].[Crm_NewClientData] WHERE ID IN (
  786. --所有四川省域的
  787. select Id from [dbo].[Crm_NewClientData] where ISDEL = 0 AND Lvlid IN (
  788. select S.Id from Sys_SetData S
  789. where STid = 33 and isdel = 0 and
  790. (Name like '%四%川%' or Name like '%成%都%')
  791. )
  792. ) AND IsDel = 0
  793. AND ID IN (
  794. SELECT NewClientDataId FROM [dbo].[Crm_ClientDataAndUser]
  795. WHERE NewClientDataId IN (
  796. --所有单独数据
  797. SELECT NewClientDataId FROM [dbo].[Crm_ClientDataAndUser]
  798. WHERE ISDEL = 0
  799. GROUP BY NewClientDataId
  800. HAVING COUNT(NewClientDataId) = 1
  801. ) AND IsDel = 0 AND UsersId = 21
  802. )";
  803. var clientList = _sqlSugar.SqlQueryable<Crm_NewClientData>(sql).Select(x => x.Id).ToList().Select(x => new Crm_ClientDataAndUser
  804. {
  805. NewClientDataId = x,
  806. usersId = 330,
  807. CreateTime = DateTime.Now,
  808. CreateUserId = 235,
  809. IsDel = 0,
  810. }).ToList();
  811. var insertCount = _sqlSugar.Insertable(clientList).ExecuteCommand();
  812. return Ok(insertCount);
  813. }
  814. [HttpPost]
  815. public IActionResult ExportData()
  816. {
  817. var soure = _sqlSugar.Queryable<Crm_NewClientData>()
  818. .InnerJoin<Crm_ClientDataAndUser>((a, b) => b.NewClientDataId == a.Id && b.IsDel == 0)
  819. .Where((a, b) => a.IsDel == 0 && b.usersId == 95)
  820. .Select((a, b) => a)
  821. .ToList();
  822. foreach (var item in soure)
  823. {
  824. EncryptionProcessor.DecryptProperties(item);
  825. }
  826. // 创建WorkbookDesigner对象
  827. WorkbookDesigner designer = new WorkbookDesigner();
  828. // 加载模板文件(包含智能标记)
  829. designer.Workbook = new Workbook("C:\\Users\\PC\\Desktop\\111.xlsx");
  830. // 设置数据源,这里假设你的List集合名为listData
  831. designer.SetDataSource("ListData", soure);
  832. // 处理智能标记以将数据填充到工作表中
  833. designer.Process();
  834. // 保存Excel文件
  835. designer.Workbook.Save("C:\\Users\\PC\\Desktop\\111000.xlsx");
  836. return Ok(1);
  837. }
  838. [HttpPost]
  839. public IActionResult DeleteData()
  840. {
  841. var soure = _sqlSugar.Queryable<Crm_NewClientData>()
  842. .InnerJoin<Crm_ClientDataAndUser>((a, b) => b.NewClientDataId == a.Id && b.IsDel == 0)
  843. .Where((a, b) => a.IsDel == 0 && b.usersId == 330)
  844. .Select((a, b) => b.Id)
  845. .ToList();
  846. var count = _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  847. .Where(u => soure.Contains(u.Id) && u.IsDel == 0)
  848. .SetColumns(x => new Crm_ClientDataAndUser
  849. {
  850. DeleteTime = DateTime.Now.ToString(),
  851. DeleteUserId = 235,
  852. IsDel = 1
  853. }).ExecuteCommand();
  854. return Ok(count);
  855. }
  856. [HttpPost]
  857. public IActionResult ReassignCustomers()
  858. {
  859. var user_Client = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  860. .Where(x => x.usersId == 302 && x.IsDel == 0)
  861. .Select(x => new
  862. {
  863. x.Id,
  864. x.NewClientDataId
  865. })
  866. .ToList();
  867. var ids = user_Client.Select(x => x.NewClientDataId).ToList();
  868. string setDataSql = $"select * from Sys_SetData where STid = 33 and isdel = 0 and (Name like '%重庆%') ";
  869. var setDataids = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();
  870. var clients = _sqlSugar.Queryable<Crm_NewClientData>().Where(x => ids.Contains(x.Id) && setDataids.Contains(x.Lvlid) && x.IsDel == 0).ToList();
  871. var clients_ids = clients.Select(x => x.Id).ToList();
  872. int updateCount = 0;
  873. _sqlSugar.BeginTran();
  874. if (clients.Count == 223)
  875. {
  876. updateCount = _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  877. .Where(x => x.usersId == 302 && clients_ids.Contains(x.NewClientDataId) && x.IsDel == 0)
  878. .SetColumns(x => new Crm_ClientDataAndUser
  879. {
  880. usersId = 21
  881. })
  882. .ExecuteCommand();
  883. }
  884. if (updateCount == clients.Count)
  885. {
  886. _sqlSugar.CommitTran();
  887. }
  888. else
  889. {
  890. _sqlSugar.RollbackTran();
  891. }
  892. return Ok(new
  893. {
  894. count = clients.Count,
  895. updateCount,
  896. });
  897. }
  898. [HttpPost]
  899. public IActionResult InsertDataJiang()
  900. {
  901. var list_DB = _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0).ToList();
  902. foreach (var item in list_DB)
  903. {
  904. EncryptionProcessor.DecryptProperties(item);
  905. }
  906. list_DB = list_DB.Where(x => !string.IsNullOrWhiteSpace(x.Client) && (x.Client.Contains("学院") || x.Client.Contains("大学"))).ToList();
  907. var arr = list_DB.Select(x => x.Id).ToList().Select(x => new Crm_ClientDataAndUser
  908. {
  909. NewClientDataId = x,
  910. usersId = 327,
  911. CreateTime = DateTime.Now,
  912. CreateUserId = 235,
  913. IsDel = 0,
  914. }).ToList();
  915. var insertCount = _sqlSugar.Insertable(arr).ExecuteCommand();
  916. return Ok(insertCount);
  917. }
  918. [HttpPost]
  919. public IActionResult InsertDataGu()
  920. {
  921. string sql = @"SELECT * FROM Crm_NewClientData cncd WHERE IsDel = 0
  922. AND Lvlid in (
  923. select Id from Sys_SetData where STid = 33 and isdel = 0
  924. and (Name like '%云%南%' or Name like '%昆%明%')
  925. )";
  926. var list = _sqlSugar.SqlQueryable<Crm_NewClientData>(sql).Select(x => x.Id).ToList();
  927. var toUserList = new List<Crm_ClientDataAndUser>();
  928. foreach (var item in list)
  929. {
  930. toUserList.Add(new Crm_ClientDataAndUser
  931. {
  932. CreateTime = DateTime.Now,
  933. CreateUserId = 235,
  934. NewClientDataId = item,
  935. usersId = 364,
  936. IsDel = 0,
  937. });
  938. }
  939. var updateCount = 0;
  940. if (toUserList.Count == 327)
  941. {
  942. updateCount = _sqlSugar.Insertable(toUserList).ExecuteCommand();
  943. }
  944. return Ok(new
  945. {
  946. updateCount
  947. });
  948. }
  949. [HttpPost]
  950. public IActionResult CloneUserClient(CloneUserClientDto dto)
  951. {
  952. var list = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  953. .Where(x => x.IsDel == 0 && x.usersId == dto.UserId)
  954. .ToList();
  955. foreach (var item in list)
  956. {
  957. item.usersId = dto.ToUserId;
  958. }
  959. var count = _sqlSugar.Insertable<Crm_ClientDataAndUser>(list).ExecuteCommand();
  960. return Ok(new
  961. {
  962. count,
  963. });
  964. }
  965. #endregion
  966. /// <summary>
  967. /// 客户资料 操作记录记录查询
  968. /// </summary>
  969. /// <param name="userId"></param>
  970. /// <returns></returns>
  971. [HttpGet]
  972. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  973. public async Task<IActionResult> NewClientDataOperatingRrecord(int userId)
  974. {
  975. var datas = await _sqlSugar.Queryable<Crm_TableOperationRecord, Crm_NewClientData, Sys_Users>((tor, ncd, u) =>
  976. new JoinQueryInfos(
  977. JoinType.Left, tor.DataId == ncd.Id,
  978. JoinType.Left, tor.CreateUserId == u.Id
  979. ))
  980. .Where((tor, ncd, u) => tor.TableName == "Crm_NewClientData" && tor.CreateUserId == userId && (int)tor.OperationItem > 1)
  981. .Select((tor, ncd, u) => new
  982. {
  983. tor.PortType,
  984. tor.OperationItem,
  985. tor.DataId,
  986. ncd.Client,
  987. u.CnName,
  988. tor.CreateTime
  989. }).ToListAsync();
  990. var view = new List<dynamic>();
  991. if (datas.Any())
  992. {
  993. datas = datas.OrderByDescending(x => x.CreateTime).ToList();
  994. foreach (var item in datas)
  995. {
  996. var text = item.OperationItem.GetDescription();
  997. view.Add(new
  998. {
  999. Client = AesEncryptionHelper.Decrypt(item.Client),
  1000. item.PortType,
  1001. item.OperationItem,
  1002. text = text,
  1003. item.DataId,
  1004. item.CnName,
  1005. item.CreateTime
  1006. });
  1007. }
  1008. }
  1009. return Ok(JsonView(view));
  1010. }
  1011. [HttpPost]
  1012. public async Task<IActionResult> SearchClientByKeyword(SearchClientByKeywordDto dto)
  1013. {
  1014. var jw = JsonView(true);
  1015. var expression = Expressionable.Create<Crm_NewClientData>()
  1016. .And(x => x.IsDel == 0)
  1017. .AndIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid)
  1018. .AndIF(dto.Category != 0, x => x.Category == dto.Category);
  1019. if (dto.Range != 0)
  1020. {
  1021. var rangeSetDataList = await _clientDataRepository.GetCachedRangeSetDataAsync(dto.Range);
  1022. expression = expression.And(x => rangeSetDataList.Contains(x.Lvlid));
  1023. }
  1024. this.keyName += "_" + dto.UserId;
  1025. //获取个人的客户
  1026. if (dto.UserId != 21)
  1027. {
  1028. var userList = _clientDataRepository.GetNewExistClient(dto.UserId).Select(x => x.Id);
  1029. var newClientData = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1030. .Where(x => x.IsDel == 0 && userList.Contains(x.usersId))
  1031. .Select(x => x.NewClientDataId)
  1032. .Distinct()
  1033. .ToList();
  1034. expression = expression.And(x => newClientData.Contains(x.Id));
  1035. }
  1036. var exists = false;
  1037. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  1038. //if (exists) exists = await RedisFactory.CreateRedisRepository().HashFieldExistAsync(keyName, dto.Keyword);
  1039. if (!exists)
  1040. {
  1041. string field = "Id,Client";
  1042. var newClitnData = _sqlSugar.Queryable<Crm_NewClientData>()
  1043. .Where(expression.ToExpression())
  1044. .Select(field)
  1045. .ToList();
  1046. foreach (var item in newClitnData)
  1047. {
  1048. EncryptionProcessor.DecryptProperties(item);
  1049. }
  1050. var keywordArray = dto.Keyword.ToCharArray();
  1051. var matches = newClitnData
  1052. .Where(fullString => !string.IsNullOrWhiteSpace(fullString.Client) &&
  1053. keywordArray.All(keyword => fullString.Client.Contains(keyword)))
  1054. .Select(x => new
  1055. {
  1056. x.Client,
  1057. x.Id
  1058. })
  1059. .DistinctBy(x => x.Client)
  1060. .ToList();
  1061. if (matches.Any())
  1062. {
  1063. //await RedisFactory.CreateRedisRepository().HashSetAsync(keyName, dto.Keyword, matches);
  1064. //await RedisFactory.CreateRedisRepository().KeyExpireInAsync(keyName, new TimeSpan(0,1,0));
  1065. jw.Data = matches;
  1066. }
  1067. else
  1068. {
  1069. jw.Code = 201;
  1070. jw.Msg = "empty list";
  1071. jw.Data = new List<string>(1);
  1072. }
  1073. }
  1074. else
  1075. {
  1076. jw.Data = await RedisFactory.CreateRedisRepository().HashGetAsync<List<string>>(keyName, dto.Keyword);
  1077. }
  1078. return Ok(jw);
  1079. }
  1080. [HttpGet("{userId}")]
  1081. public async Task<IActionResult> SearchClientByUserId(int userId)
  1082. {
  1083. var sw = Stopwatch.StartNew();
  1084. var jw = JsonView(true);
  1085. if (!await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == userId).AnyAsync())
  1086. {
  1087. jw.Code = StatusCodes.Status400BadRequest;
  1088. jw.Msg = $"请传入有效的UserId";
  1089. return Ok(jw);
  1090. }
  1091. var expression = Expressionable.Create<Crm_NewClientData>().And(x => x.IsDel == 0);
  1092. //获取个人的客户
  1093. if (userId != 21)
  1094. {
  1095. var userList = _clientDataRepository.GetNewExistClient(userId).Select(x => x.Id);
  1096. var newClientData = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1097. .Where(x => x.IsDel == 0 && userList.Contains(x.usersId))
  1098. .Select(x => x.NewClientDataId)
  1099. .Distinct()
  1100. .ToList();
  1101. expression = expression.And(x => newClientData.Contains(x.Id));
  1102. }
  1103. string field = "Id,Client";
  1104. var newClitnData = _sqlSugar.Queryable<Crm_NewClientData>()
  1105. .Where(expression.ToExpression())
  1106. .Select(field)
  1107. .ToList();
  1108. foreach (var item in newClitnData)
  1109. {
  1110. EncryptionProcessor.DecryptProperties(item);
  1111. }
  1112. var matches = newClitnData
  1113. .Where(fullString => !string.IsNullOrWhiteSpace(fullString.Client))
  1114. .OrderByDescending(x => x.Id)
  1115. .Select(x => new { x.Id, x.Client })
  1116. .DistinctBy(x => x.Client)
  1117. .ToList();
  1118. if (matches.Any())
  1119. {
  1120. jw.Data = matches;
  1121. jw.Count = matches.Count();
  1122. }
  1123. else
  1124. {
  1125. jw.Code = 201;
  1126. jw.Msg = "empty list";
  1127. jw.Data = new List<string>(1);
  1128. }
  1129. sw.Stop();
  1130. jw.Msg = $"操作成功!耗时:{sw.Elapsed.TotalMilliseconds}ms.";
  1131. return Ok(jw);
  1132. }
  1133. [HttpPost]
  1134. public async Task<IActionResult> QueryUnlockDropList()
  1135. {
  1136. var jw = JsonView(true);
  1137. var userList = await _sqlSugar.Queryable<Sys_SetData>().FirstAsync
  1138. (x => x.Id == 1434 && x.IsDel == 0);
  1139. try
  1140. {
  1141. if (userList != null)
  1142. {
  1143. var result = JsonConvert.DeserializeObject<List<int>>(userList.Remark);
  1144. jw.Data = result;
  1145. }
  1146. }
  1147. catch (Exception)
  1148. {
  1149. jw.Code = 500;
  1150. jw.Msg = "数据源错误!";
  1151. jw.Data = new List<int>(1);
  1152. }
  1153. return Ok(jw);
  1154. }
  1155. [HttpPost]
  1156. public IActionResult InsertDataExcel(InsertDataExcelDto dto)
  1157. {
  1158. //string client = dto.Client;
  1159. int toUser = dto.ToUser;
  1160. var clietnArr = dto.Client;
  1161. var count = 0;
  1162. //var notClentUser = new List<int>() { 21, 95 , 327 };
  1163. var notClentUser = new List<int>() { 213, 327 };
  1164. var insertList = new List<Crm_ClientDataAndUser>();
  1165. if (clietnArr.Count > 0)
  1166. {
  1167. _sqlSugar.BeginTran();
  1168. //检索相关客户数据
  1169. var newClientArr = _sqlSugar.Queryable<Crm_NewClientData>()
  1170. .Where(x => x.IsDel == 0)
  1171. .Select(x => new Crm_NewClientData
  1172. {
  1173. Client = x.Client,
  1174. Id = x.Id
  1175. })
  1176. .ToList()
  1177. .Select(x => new
  1178. {
  1179. Client = AesEncryptionHelper.Decrypt(x.Client),
  1180. Id = x.Id
  1181. });
  1182. foreach (var item in clietnArr)
  1183. {
  1184. var searchClient = newClientArr.Where(x => x.Client == item).ToList();
  1185. foreach (var clientData in searchClient)
  1186. {
  1187. var clientDataAndUser = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1188. .Where(x => x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1189. .ToList();
  1190. if (clientDataAndUser.Count > 0)
  1191. {
  1192. //清除关联表数据
  1193. _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  1194. .Where(x => !notClentUser.Contains(x.usersId)
  1195. && x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1196. .SetColumns(x => new Crm_ClientDataAndUser
  1197. {
  1198. IsDel = 1,
  1199. DeleteTime = DateTime.Now.ToString(),
  1200. DeleteUserId = 235
  1201. })
  1202. .ExecuteCommand();
  1203. }
  1204. insertList.Add(new Crm_ClientDataAndUser
  1205. {
  1206. usersId = toUser,
  1207. NewClientDataId = clientData.Id,
  1208. CreateTime = DateTime.Now,
  1209. CreateUserId = 235,
  1210. });
  1211. }
  1212. }
  1213. count = _sqlSugar.Insertable(insertList).ExecuteCommand();
  1214. _sqlSugar.CommitTran();
  1215. }
  1216. return Ok(new
  1217. {
  1218. count,
  1219. });
  1220. }
  1221. /// <summary>
  1222. /// 客户资料分配(按照数据ID) - UserId
  1223. /// </summary>
  1224. /// <param name="file"></param>
  1225. /// <returns></returns>
  1226. [HttpPost]
  1227. public IActionResult InsertDataExcel1(IFormFile file)
  1228. {
  1229. // 检查文件是否为空
  1230. if (file == null || file.Length == 0)
  1231. {
  1232. return BadRequest("No file uploaded.");
  1233. }
  1234. // 保存文件到服务器
  1235. var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "File");
  1236. if (!Directory.Exists(uploadsFolder))
  1237. {
  1238. Directory.CreateDirectory(uploadsFolder);
  1239. }
  1240. var filePath = Path.Combine(uploadsFolder, file.FileName);
  1241. using (var stream = new FileStream(filePath, FileMode.Create))
  1242. {
  1243. file.CopyToAsync(stream);
  1244. }
  1245. Workbook workbook = new Workbook(filePath);
  1246. // 获取第一个工作表
  1247. Worksheet worksheet = workbook.Worksheets[0];
  1248. // 获取表头(第一行作为列名)
  1249. int headerRowIndex = 0; // 假设第一行是表头
  1250. Aspose.Cells.Row headerRow = worksheet.Cells.Rows[headerRowIndex];
  1251. int colCount = worksheet.Cells.MaxDataColumn + 1;
  1252. // 动态存储列名
  1253. var clients = new List<Crm_ClientDataAndUser>();
  1254. // 遍历数据行(从第二行开始)
  1255. int rowCount = worksheet.Cells.MaxDataRow + 1;
  1256. for (int row = headerRowIndex + 1; row < rowCount; row++)
  1257. {
  1258. var cellVal1 = worksheet.Cells[row, 0].Value; //序号
  1259. var cellVal2 = worksheet.Cells[row, 1].Value; //数据Id
  1260. var cellVal3 = worksheet.Cells[row, 2].Value; //userId
  1261. int parentId = !string.IsNullOrEmpty(cellVal2?.ToString()) ? int.Parse(cellVal2?.ToString()) : 0;
  1262. int userId = !string.IsNullOrEmpty(cellVal3?.ToString()) ? int.Parse(cellVal3?.ToString()) : 0;
  1263. var rowData = new Crm_ClientDataAndUser()
  1264. {
  1265. usersId = userId,
  1266. NewClientDataId = parentId
  1267. };
  1268. clients.Add(rowData); // 将当前行数据添加到集合中
  1269. }
  1270. var count = 0;
  1271. //var notClentUser = new List<int>() { 21, 95 , 327 };
  1272. var notClentUser = new List<int>() { 21, 95, 327, 213 };
  1273. var insertList = new List<Crm_ClientDataAndUser>();
  1274. if (clients.Count > 0)
  1275. {
  1276. _sqlSugar.BeginTran();
  1277. //检索相关客户数据
  1278. var newClientArr = _sqlSugar.Queryable<Crm_NewClientData>()
  1279. .Where(x => x.IsDel == 0)
  1280. .Select(x => new Crm_NewClientData
  1281. {
  1282. Client = x.Client,
  1283. Id = x.Id
  1284. })
  1285. .ToList();
  1286. foreach (var item in clients)
  1287. {
  1288. var searchClient = newClientArr.Where(x => x.Id == item.NewClientDataId).ToList();
  1289. foreach (var clientData in searchClient)
  1290. {
  1291. var clientDataAndUser = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1292. .Where(x => x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1293. .ToList();
  1294. if (clientDataAndUser.Count > 0)
  1295. {
  1296. //清除关联表数据
  1297. _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  1298. .Where(x => !notClentUser.Contains(x.usersId)
  1299. && x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1300. .SetColumns(x => new Crm_ClientDataAndUser
  1301. {
  1302. IsDel = 1,
  1303. DeleteTime = DateTime.Now.ToString(),
  1304. DeleteUserId = 235
  1305. })
  1306. .ExecuteCommand();
  1307. }
  1308. insertList.Add(new Crm_ClientDataAndUser
  1309. {
  1310. usersId = item.usersId,
  1311. NewClientDataId = clientData.Id,
  1312. CreateTime = DateTime.Now,
  1313. CreateUserId = 235,
  1314. });
  1315. }
  1316. }
  1317. count = _sqlSugar.Insertable(insertList).ExecuteCommand();
  1318. _sqlSugar.CommitTran();
  1319. }
  1320. return Ok(new
  1321. {
  1322. count,
  1323. });
  1324. }
  1325. [HttpPost]
  1326. public IActionResult SchoolAllocation()
  1327. {
  1328. var clients = _sqlSugar.Queryable<Crm_NewClientData>()
  1329. .Where(x => x.IsDel == 0)
  1330. .Select(x => new Crm_NewClientData { Id = x.Id, Client = x.Client })
  1331. .ToList();
  1332. var keys = new List<string>()
  1333. {
  1334. "大学", "学院", "中学", "教育", "学校", "一中", "二中", "七中", "十五中", "二十五中","高校"
  1335. };
  1336. var count = 0;
  1337. var insertArr = new List<Crm_ClientDataAndBusiness>();
  1338. // --368 教育
  1339. foreach (var item in clients)
  1340. {
  1341. EncryptionProcessor.DecryptProperties(item);
  1342. foreach (var key in keys)
  1343. {
  1344. if (!string.IsNullOrWhiteSpace(item.Client) && item.Client.Contains(key))
  1345. {
  1346. insertArr.Add(new Crm_ClientDataAndBusiness
  1347. {
  1348. NewClientDataId = item.Id,
  1349. SetDataId = 368, // 教育
  1350. CreateTime = DateTime.Now,
  1351. CreateUserId = 235,
  1352. IsDel = 0
  1353. });
  1354. }
  1355. }
  1356. }
  1357. count = _sqlSugar.Insertable(insertArr)
  1358. .ExecuteCommand();
  1359. return count > 0 ? Ok(JsonView(true, "分配成功!", count)) : Ok(JsonView(false, "分配失败!"));
  1360. }
  1361. /// <summary>
  1362. /// 获取IP信息
  1363. /// </summary>
  1364. /// <param name="ip">ipv4 or ipv6</param>
  1365. /// <returns></returns>
  1366. private async Task<(string ip, string local)> GetIpInfo(string ip)
  1367. {
  1368. string local = string.Empty;
  1369. if (IPAddress.TryParse(ip, out _))
  1370. {
  1371. using HttpClient _httpClient = new HttpClient();
  1372. var response = await _httpClient.GetAsync($"https://api.vore.top/api/IPdata?ip={ip}");
  1373. response.EnsureSuccessStatusCode();
  1374. var json = await response.Content.ReadAsStringAsync();
  1375. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  1376. if (ipInfo.code == 200)
  1377. {
  1378. ip = ipInfo.ipinfo.text;
  1379. local = $"{ipInfo.adcode.o}";
  1380. }
  1381. }
  1382. return (ip, local);
  1383. }
  1384. #region 回滚数据记录
  1385. //[HttpPost]
  1386. //public async Task<IActionResult> actionResult()
  1387. //{
  1388. // var jw = JsonView(true);
  1389. // var sql = @" SELECT * FROM OA2023DB.dbo.Crm_TableOperationRecord
  1390. // WHERE TableName ='Crm_NewClientData'
  1391. // AND OperationItem IN(4) AND CreateTime > '2025-02-03' AND CreateTime < '2025-03-06'
  1392. // AND ReturnResult LIKE '%修改成功%' ";
  1393. // var list = _sqlSugar.SqlQueryable<Crm_TableOperationRecord>(sql).Select(x=>new Crm_TableOperationRecord
  1394. // {
  1395. // RequestParam = x.RequestParam
  1396. // }).ToList();
  1397. // foreach (var item in list)
  1398. // {
  1399. // var string1 = item.RequestParam.Trim('"').Replace("\\", "");
  1400. // //if (!string.IsNullOrEmpty(item.RequestParam))
  1401. // //{
  1402. // // var req = item.RequestParam;
  1403. // // if (CommonFun.IsValidJson(item.RequestParam))
  1404. // // {
  1405. // // var res1 = JToken.Parse(item.RequestParam);
  1406. // // }
  1407. // // NewClientOpDto dto = JsonConvert.DeserializeObject<NewClientOpDto>(JsonConvert.DeserializeObject<string>(item.RequestParam));
  1408. // NewClientOpDto dto1 = JsonConvert.DeserializeObject<NewClientOpDto>(string1);
  1409. // var result = await this.NewClientOp(dto1);
  1410. // //}
  1411. // }
  1412. // return Ok(jw);
  1413. //}
  1414. #endregion
  1415. }
  1416. }