MarketCustomerResourcesController.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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. [HttpPost]
  1325. public IActionResult SchoolAllocation()
  1326. {
  1327. var clients = _sqlSugar.Queryable<Crm_NewClientData>()
  1328. .Where(x => x.IsDel == 0)
  1329. .Select(x => new Crm_NewClientData { Id = x.Id, Client = x.Client })
  1330. .ToList();
  1331. var keys = new List<string>()
  1332. {
  1333. "大学", "学院", "中学", "教育", "学校", "一中", "二中", "七中", "十五中", "二十五中","高校"
  1334. };
  1335. var count = 0;
  1336. var insertArr = new List<Crm_ClientDataAndBusiness>();
  1337. // --368 教育
  1338. foreach (var item in clients)
  1339. {
  1340. EncryptionProcessor.DecryptProperties(item);
  1341. foreach (var key in keys)
  1342. {
  1343. if (!string.IsNullOrWhiteSpace(item.Client) && item.Client.Contains(key))
  1344. {
  1345. insertArr.Add(new Crm_ClientDataAndBusiness
  1346. {
  1347. NewClientDataId = item.Id,
  1348. SetDataId = 368, // 教育
  1349. CreateTime = DateTime.Now,
  1350. CreateUserId = 235,
  1351. IsDel = 0
  1352. });
  1353. }
  1354. }
  1355. }
  1356. count = _sqlSugar.Insertable(insertArr)
  1357. .ExecuteCommand();
  1358. return count > 0 ? Ok(JsonView(true, "分配成功!", count)) : Ok(JsonView(false, "分配失败!"));
  1359. }
  1360. /// <summary>
  1361. /// 获取IP信息
  1362. /// </summary>
  1363. /// <param name="ip">ipv4 or ipv6</param>
  1364. /// <returns></returns>
  1365. private async Task<(string ip, string local)> GetIpInfo(string ip)
  1366. {
  1367. string local = string.Empty;
  1368. if (IPAddress.TryParse(ip, out _))
  1369. {
  1370. using HttpClient _httpClient = new HttpClient();
  1371. var response = await _httpClient.GetAsync($"https://api.vore.top/api/IPdata?ip={ip}");
  1372. response.EnsureSuccessStatusCode();
  1373. var json = await response.Content.ReadAsStringAsync();
  1374. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  1375. if (ipInfo.code == 200)
  1376. {
  1377. ip = ipInfo.ipinfo.text;
  1378. local = $"{ipInfo.adcode.o}";
  1379. }
  1380. }
  1381. return (ip, local);
  1382. }
  1383. #region 回滚数据记录
  1384. //[HttpPost]
  1385. //public async Task<IActionResult> actionResult()
  1386. //{
  1387. // var jw = JsonView(true);
  1388. // var sql = @" SELECT * FROM OA2023DB.dbo.Crm_TableOperationRecord
  1389. // WHERE TableName ='Crm_NewClientData'
  1390. // AND OperationItem IN(4) AND CreateTime > '2025-02-03' AND CreateTime < '2025-03-06'
  1391. // AND ReturnResult LIKE '%修改成功%' ";
  1392. // var list = _sqlSugar.SqlQueryable<Crm_TableOperationRecord>(sql).Select(x=>new Crm_TableOperationRecord
  1393. // {
  1394. // RequestParam = x.RequestParam
  1395. // }).ToList();
  1396. // foreach (var item in list)
  1397. // {
  1398. // var string1 = item.RequestParam.Trim('"').Replace("\\", "");
  1399. // //if (!string.IsNullOrEmpty(item.RequestParam))
  1400. // //{
  1401. // // var req = item.RequestParam;
  1402. // // if (CommonFun.IsValidJson(item.RequestParam))
  1403. // // {
  1404. // // var res1 = JToken.Parse(item.RequestParam);
  1405. // // }
  1406. // // NewClientOpDto dto = JsonConvert.DeserializeObject<NewClientOpDto>(JsonConvert.DeserializeObject<string>(item.RequestParam));
  1407. // NewClientOpDto dto1 = JsonConvert.DeserializeObject<NewClientOpDto>(string1);
  1408. // var result = await this.NewClientOp(dto1);
  1409. // //}
  1410. // }
  1411. // return Ok(jw);
  1412. //}
  1413. #endregion
  1414. }
  1415. }