MarketCustomerResourcesController.cs 62 KB

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