MarketCustomerResourcesController.cs 68 KB

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