777dbe40
“wangming”
feat: 实现集团驾驶舱移动端功...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Entitys.Dto.LqBusinessUnitDashboard;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_xh_hyhk;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_kd_pxmx;
using NCC.Extend.Entitys.lq_hytk_mx;
using NCC.Extend.Entitys.lq_md_target;
using NCC.Extend.Entitys.lq_xh_pxmx;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_md_general_manager_lifeline;
using NCC.Extend.Entitys.lq_business_unit_manager_salary_statistics;
using NCC.Extend.Entitys.lq_kd_jksyj;
using NCC.Extend.Entitys.lq_xh_jksyj;
using NCC.Extend.Entitys.lq_hytk_jksyj;
using NCC.System.Entitys.Permission;
using NCC.Extend.Entitys;
using SqlSugar;
namespace NCC.Extend
{
/// <summary>
/// 事业部驾驶舱服务
/// </summary>
[ApiDescriptionSettings(Tag = "事业部驾驶舱服务", Name = "LqBusinessUnitDashboard", Order = 203)]
[Route("api/Extend/[controller]")]
public class LqBusinessUnitDashboardService : IDynamicApiController, ITransient
{
private readonly ISqlSugarClient _db;
private readonly ILogger<LqBusinessUnitDashboardService> _logger;
/// <summary>
/// 初始化事业部驾驶舱服务
/// </summary>
public LqBusinessUnitDashboardService(ISqlSugarClient db, ILogger<LqBusinessUnitDashboardService> logger)
{
_db = db;
_logger = logger;
}
// 辅助方法:获取门店列表
private async Task<List<string>> GetStoreIdsAsync(string businessUnitId, List<string> storeIds, string statisticsMonth)
{
if (!string.IsNullOrWhiteSpace(businessUnitId))
{
return await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.BusinessUnit == businessUnitId && x.Month == statisticsMonth)
.Select(x => x.StoreId)
.Distinct()
.ToListAsync();
}
return storeIds ?? new List<string>();
}
// 辅助方法:获取门店列表(重载)
private async Task<List<string>> GetStoreIdsAsync(BusinessUnitDashboardStatisticsInput input)
{
return await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
}
// 辅助方法:获取指定月份的门店列表
private async Task<List<string>> GetStoreIdsForMonthAsync(string businessUnitId, List<string> storeIds, string month)
{
if (!string.IsNullOrWhiteSpace(businessUnitId))
{
return await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.BusinessUnit == businessUnitId && x.Month == month)
.Select(x => x.StoreId)
.Distinct()
.ToListAsync();
}
return storeIds ?? new List<string>();
}
// 辅助方法:计算单月业绩指标
private async Task<(decimal billingPerformance, decimal consumePerformance, decimal refundAmount, decimal netPerformance, decimal targetPerformance, decimal completionRate,
decimal lifeBeauty, decimal techBeauty, decimal medicalBeauty, decimal product)> CalculateMonthlyPerformance(
List<string> storeIds, string month)
{
if (!storeIds.Any()) return (0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
var year = int.Parse(month.Substring(0, 4));
var monthNum = int.Parse(month.Substring(4, 2));
var startDate = new DateTime(year, monthNum, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = month == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
// 消耗业绩
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 目标业绩
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => storeIds.Contains(x.StoreId) && x.Month == month)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
// 品项分类业绩
var (billingLifeBeauty, billingTechBeauty, billingMedicalBeauty, billingProduct) =
await CalculatePerformanceByCategory(storeIds, month, false);
var (refundLifeBeauty, refundTechBeauty, refundMedicalBeauty, refundProduct) =
await CalculatePerformanceByCategory(storeIds, month, true);
var lifeBeauty = billingLifeBeauty - refundLifeBeauty;
var techBeauty = billingTechBeauty - refundTechBeauty;
var medicalBeauty = billingMedicalBeauty - refundMedicalBeauty;
var product = billingProduct - refundProduct;
return (billingAmount, consumeAmount, refundAmount, netPerformance, targetPerformance, completionRate,
lifeBeauty, techBeauty, medicalBeauty, product);
}
// 辅助方法:计算品项分类业绩
private async Task<(decimal lifeBeauty, decimal techBeauty, decimal medicalBeauty, decimal product)> CalculatePerformanceByCategory(
List<string> storeIds, string month, bool isRefund = false)
{
if (!storeIds.Any()) return (0, 0, 0, 0);
var year = int.Parse(month.Substring(0, 4));
var monthNum = int.Parse(month.Substring(4, 2));
var startDate = new DateTime(year, monthNum, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = month == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
var storeIdsStr = string.Join("','", storeIds);
if (isRefund)
{
// 退卡品项分类业绩
var refundSql = $@"
SELECT
COALESCE(refund_mx.F_ItemCategory, '') as ItemCategory,
COALESCE(SUM(COALESCE(refund_mx.tkje, 0)), 0) as Amount
FROM lq_hytk_mx refund_mx
INNER JOIN lq_hytk_hytk refund ON refund_mx.F_RefundInfoId = refund.F_Id
WHERE refund_mx.F_IsEffective = 1
AND refund.F_IsEffective = 1
AND refund.md IN ('{storeIdsStr}')
AND refund.tksj >= '{startDate:yyyy-MM-dd} 00:00:00'
AND refund.tksj < '{endDate.AddDays(1):yyyy-MM-dd} 00:00:00'
GROUP BY refund_mx.F_ItemCategory";
var refundData = await _db.Ado.SqlQueryAsync<dynamic>(refundSql);
decimal lifeBeauty = 0, techBeauty = 0, medicalBeauty = 0, product = 0;
foreach (var row in refundData ?? Enumerable.Empty<dynamic>())
{
var category = row?.ItemCategory?.ToString() ?? "";
var amount = row?.Amount != null ? Convert.ToDecimal(row.Amount) : 0m;
if (category == "生美") lifeBeauty = amount;
else if (category == "科美") techBeauty = amount;
else if (category == "医美") medicalBeauty = amount;
else if (category == "产品") product = amount;
}
return (lifeBeauty, techBeauty, medicalBeauty, product);
}
else
{
// 开单品项分类业绩(从lq_kd_pxmx表的F_ActualPrice字段统计)
var billingSql = $@"
SELECT
COALESCE(pxmx.F_ItemCategory, '') as ItemCategory,
COALESCE(SUM(COALESCE(pxmx.F_ActualPrice, 0)), 0) as Amount
FROM lq_kd_pxmx pxmx
INNER JOIN lq_kd_kdjlb billing ON pxmx.glkdbh = billing.F_Id
WHERE pxmx.F_IsEffective = 1
AND billing.F_IsEffective = 1
AND billing.djmd IN ('{storeIdsStr}')
AND billing.kdrq >= '{startDate:yyyy-MM-dd} 00:00:00'
AND billing.kdrq < '{endDate.AddDays(1):yyyy-MM-dd} 00:00:00'
GROUP BY pxmx.F_ItemCategory";
var billingData = await _db.Ado.SqlQueryAsync<dynamic>(billingSql);
decimal lifeBeauty = 0, techBeauty = 0, medicalBeauty = 0, product = 0;
foreach (var row in billingData ?? Enumerable.Empty<dynamic>())
{
var category = row?.ItemCategory?.ToString() ?? "";
var amount = row?.Amount != null ? Convert.ToDecimal(row.Amount) : 0m;
if (category == "生美") lifeBeauty = amount;
else if (category == "科美") techBeauty = amount;
else if (category == "医美") medicalBeauty = amount;
else if (category == "产品") product = amount;
}
return (lifeBeauty, techBeauty, medicalBeauty, product);
}
}
/// <summary>
/// 获取事业部驾驶舱统计数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的核心指标:开单业绩、消耗业绩、净业绩、目标业绩、完成率、管理的门店数、活跃门店数、品项分类业绩等
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "1649328471923847169",
/// "statisticsMonth": "202512"
/// }
/// ```
///
/// 或者:
/// ```json
/// {
/// "storeIds": ["1649328471923847169", "1649328471923847170"],
/// "statisticsMonth": "202512"
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
///
/// 返回数据说明:
/// - BillingPerformance: 开单业绩(开单实付业绩总和)
/// - ConsumePerformance: 消耗业绩(消耗金额总和)
/// - RefundAmount: 退卡金额(退卡实退金额总和)
/// - NetPerformance: 净业绩(开单业绩 - 退卡金额)
/// - TargetPerformance: 目标业绩(管理的所有门店的事业部业绩目标总和)
/// - CompletionRate: 完成率(净业绩 / 目标业绩 × 100%)
/// - ManagedStoreCount: 管理的门店数
/// - ActiveStoreCount: 活跃门店数(有开单或消耗的门店数量)
/// - 其他运营指标:开单次数、消耗次数、退卡次数、平均金额、人头数、人次、项目数、消耗率、退卡率
/// - 品项分类业绩:生美业绩、科美业绩、医美业绩、产品业绩
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱统计数据</returns>
/// <response code="200">成功返回统计数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetStatistics")]
public async Task<BusinessUnitDashboardStatisticsOutput> GetStatistics([FromBody] BusinessUnitDashboardStatisticsInput input)
{
try
{
if (input == null)
{
throw NCCException.Oh("请求参数不能为空");
}
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
{
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
}
// 参数验证:事业部ID和门店ID列表两者必填其一
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) &&
(input.StoreIds == null || !input.StoreIds.Any()))
{
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
}
if (!string.IsNullOrWhiteSpace(input.BusinessUnitId) &&
input.StoreIds != null && input.StoreIds.Any())
{
throw NCCException.Oh("事业部ID和门店ID列表不能同时传入,请只传入其中一个");
}
_logger.LogInformation("开始查询事业部驾驶舱统计数据,事业部ID:{BusinessUnitId},门店ID列表:{StoreIds},统计月份:{StatisticsMonth}",
input.BusinessUnitId, input.StoreIds != null ? string.Join(",", input.StoreIds) : "", input.StatisticsMonth);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
List<string> storeIds;
if (!string.IsNullOrWhiteSpace(input.BusinessUnitId))
{
// 方式1:从lq_md_target表查询该月份、该事业部归属的门店列表
storeIds = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.BusinessUnit == input.BusinessUnitId && x.Month == input.StatisticsMonth)
.Select(x => x.StoreId)
.Distinct()
.ToListAsync();
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
// 返回空数据
return new BusinessUnitDashboardStatisticsOutput();
}
}
else
{
// 方式2:直接使用传入的门店ID列表
storeIds = input.StoreIds;
}
// 1. 统计开单业绩(从lq_kd_kdjlb表的sfyj字段)
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 2. 统计退卡金额(从lq_hytk_hytk表的F_ActualRefundAmount或tkje字段)
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 3. 计算净业绩
var netPerformance = billingAmount - refundAmount;
// 4. 统计消耗业绩(从lq_xh_hyhk表的xfje字段)
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 5. 统计目标业绩(从lq_md_target表的F_BusinessUnitTarget字段)
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => storeIds.Contains(x.StoreId) && x.Month == input.StatisticsMonth)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 6. 计算完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
// 7. 管理的门店数
var managedStoreCount = storeIds.Count;
// 8. 统计活跃门店数(有开单或消耗的门店数量)
var storesWithBilling = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.Select(x => x.Djmd)
.Distinct()
.ToListAsync();
var storesWithConsume = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.Select(x => x.Md)
.Distinct()
.ToListAsync();
var allActiveStoreIds = storesWithBilling.Union(storesWithConsume).Distinct().ToList();
var activeStoreCount = allActiveStoreIds.Count;
// 9. 统计开单次数
var billingCount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.CountAsync();
// 10. 统计消耗次数
var consumeCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.CountAsync();
// 11. 统计退卡次数
var refundCount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.CountAsync();
// 12. 计算平均开单金额
var avgBillingAmount = billingCount > 0 ? billingAmount / (decimal)billingCount : 0m;
// 13. 计算平均消耗金额
var avgConsumeAmount = consumeCount > 0 ? consumeAmount / (decimal)consumeCount : 0m;
// 14. 统计人头数(去重后的消费会员数)
var headCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.Select(x => x.Hy)
.Distinct()
.CountAsync();
// 15. 统计人次(日度去重客户数)- 使用SQL查询
var storeIdsStr = string.Join("','", storeIds);
var personCountSql = $@"
SELECT COUNT(DISTINCT CONCAT(xh.Hy, '-', DATE_FORMAT(xh.Hksj, '%Y-%m-%d'))) as PersonCount
FROM lq_xh_hyhk xh
WHERE xh.Md IN ('{storeIdsStr}')
AND xh.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var personCountResult = await _db.Ado.SqlQueryAsync<dynamic>(personCountSql);
var personCount = personCountResult?.FirstOrDefault() != null
? Convert.ToInt32(personCountResult.FirstOrDefault().PersonCount ?? 0)
: 0;
// 16. 统计项目数(消耗的项目总数,从品项明细表统计原始项目数)
var projectCountSql = $@"
SELECT COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) as ProjectCount
FROM lq_xh_pxmx px
INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
WHERE xh.Md IN ('{storeIdsStr}')
AND xh.F_IsEffective = 1
AND px.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var projectCountResult = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);
var projectCount = projectCountResult?.FirstOrDefault() != null
? Convert.ToDecimal(projectCountResult.FirstOrDefault().ProjectCount ?? 0)
: 0m;
// 17. 计算消耗率
var consumeRate = billingAmount > 0 ? (consumeAmount / billingAmount * 100m) : 0m;
// 18. 计算退卡率
var refundRate = billingAmount > 0 ? (refundAmount / billingAmount * 100m) : 0m;
// 19. 计算品项分类业绩(开单业绩 - 退卡业绩)
var (billingLifeBeauty, billingTechBeauty, billingMedicalBeauty, billingProduct) =
await CalculatePerformanceByCategory(storeIds, input.StatisticsMonth, false);
var (refundLifeBeauty, refundTechBeauty, refundMedicalBeauty, refundProduct) =
await CalculatePerformanceByCategory(storeIds, input.StatisticsMonth, true);
var lifeBeautyPerformance = billingLifeBeauty - refundLifeBeauty;
var techBeautyPerformance = billingTechBeauty - refundTechBeauty;
var medicalBeautyPerformance = billingMedicalBeauty - refundMedicalBeauty;
var productPerformance = billingProduct - refundProduct;
var result = new BusinessUnitDashboardStatisticsOutput
{
BillingPerformance = billingAmount,
ConsumePerformance = consumeAmount,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
TargetPerformance = targetPerformance,
CompletionRate = completionRate,
ManagedStoreCount = managedStoreCount,
ActiveStoreCount = activeStoreCount,
BillingCount = billingCount,
ConsumeCount = consumeCount,
RefundCount = refundCount,
AvgBillingAmount = avgBillingAmount,
AvgConsumeAmount = avgConsumeAmount,
HeadCount = headCount,
PersonCount = personCount,
ProjectCount = projectCount,
ConsumeRate = consumeRate,
RefundRate = refundRate,
LifeBeautyPerformance = lifeBeautyPerformance,
TechBeautyPerformance = techBeautyPerformance,
MedicalBeautyPerformance = medicalBeautyPerformance,
ProductPerformance = productPerformance
};
_logger.LogInformation("事业部驾驶舱统计数据查询完成,开单业绩:{BillingPerformance},消耗业绩:{ConsumePerformance},净业绩:{NetPerformance}",
result.BillingPerformance, result.ConsumePerformance, result.NetPerformance);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱统计数据失败");
throw;
}
}
/// <summary>
/// 获取事业部驾驶舱业绩趋势数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定时间范围内的业绩趋势:开单业绩趋势、消耗业绩趋势、净业绩趋势、品项分类业绩趋势
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "monthCount": 12
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填,作为结束月份)
/// - monthCount: 月份数量(可选,默认12,支持:3、6、12)
///
/// 返回数据说明:
/// - TrendData: 趋势数据列表,每个数据点包含月份、开单业绩、消耗业绩、退卡金额、净业绩、目标业绩、完成率、品项分类业绩等
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱业绩趋势数据</returns>
/// <response code="200">成功返回趋势数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetPerformanceTrend")]
public async Task<BusinessUnitDashboardPerformanceTrendOutput> GetPerformanceTrend([FromBody] BusinessUnitDashboardPerformanceTrendInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
var monthCount = input.MonthCount;
if (monthCount != 3 && monthCount != 6 && monthCount != 12)
monthCount = 12;
var baseMonth = DateTime.ParseExact(input.StatisticsMonth, "yyyyMM", null);
var result = new BusinessUnitDashboardPerformanceTrendOutput();
for (int i = monthCount - 1; i >= 0; i--)
{
var trendMonth = baseMonth.AddMonths(-i);
var trendMonthStr = trendMonth.ToString("yyyyMM");
List<string> storeIds;
if (!string.IsNullOrWhiteSpace(input.BusinessUnitId))
{
storeIds = await GetStoreIdsForMonthAsync(input.BusinessUnitId, null, trendMonthStr);
}
else
{
storeIds = input.StoreIds;
}
if (!storeIds.Any())
{
result.TrendData.Add(new BusinessUnitPerformanceTrendPoint { Month = trendMonthStr });
continue;
}
var (billingPerformance, consumePerformance, refundAmount, netPerformance, targetPerformance, completionRate,
lifeBeauty, techBeauty, medicalBeauty, product) = await CalculateMonthlyPerformance(storeIds, trendMonthStr);
result.TrendData.Add(new BusinessUnitPerformanceTrendPoint
{
Month = trendMonthStr,
BillingPerformance = billingPerformance,
ConsumePerformance = consumePerformance,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
TargetPerformance = targetPerformance,
CompletionRate = completionRate,
LifeBeautyPerformance = lifeBeauty,
TechBeautyPerformance = techBeauty,
MedicalBeautyPerformance = medicalBeauty,
ProductPerformance = product
});
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱业绩趋势数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱门店排行数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的门店业绩排行数据,支持按开单业绩、消耗业绩、完成率排序
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "rankingType": "Billing",
/// "topCount": 10
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
/// - rankingType: 排行类型(可选,默认:Billing)
/// - Billing - 开单业绩排行
/// - Consume - 消耗业绩排行
/// - CompletionRate - 完成率排行
/// - topCount: 排行数量(可选,默认10)
///
/// 返回数据说明:
/// - RankingData: 门店排行数据列表,包含排名、门店信息、业绩数据、完成率、运营指标等
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱门店排行数据</returns>
/// <response code="200">成功返回排行数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetStoreRanking")]
public async Task<BusinessUnitDashboardStoreRankingOutput> GetStoreRanking([FromBody] BusinessUnitDashboardStoreRankingInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱门店排行数据,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth},排行类型:{RankingType}",
input.BusinessUnitId, input.StatisticsMonth, input.RankingType);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
return new BusinessUnitDashboardStoreRankingOutput();
}
// 获取门店信息(名称、编码)
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm, x.Mdbm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => new { Name = x.Dm ?? "", Code = x.Mdbm ?? "" });
// 计算每个门店的业绩数据
var storeIdsStr = string.Join("','", storeIds);
var rankingData = new List<BusinessUnitStoreRankingItem>();
foreach (var storeId in storeIds)
{
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
// 消耗业绩
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 目标业绩
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.StoreId == storeId && x.Month == input.StatisticsMonth)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
// 开单次数
var billingCount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.CountAsync();
// 消耗次数
var consumeCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.CountAsync();
// 人头数
var headCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.Select(x => x.Hy)
.Distinct()
.CountAsync();
// 人次
var personCountSql = $@"
SELECT COUNT(DISTINCT CONCAT(xh.Hy, '-', DATE_FORMAT(xh.Hksj, '%Y-%m-%d'))) as PersonCount
FROM lq_xh_hyhk xh
WHERE xh.Md = '{storeId}'
AND xh.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var personCountResult = await _db.Ado.SqlQueryAsync<dynamic>(personCountSql);
var personCount = personCountResult?.FirstOrDefault() != null
? Convert.ToInt32(personCountResult.FirstOrDefault().PersonCount ?? 0)
: 0;
// 项目数
var projectCountSql = $@"
SELECT COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) as ProjectCount
FROM lq_xh_pxmx px
INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
WHERE xh.Md = '{storeId}'
AND xh.F_IsEffective = 1
AND px.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var projectCountResult = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);
var projectCount = projectCountResult?.FirstOrDefault() != null
? Convert.ToDecimal(projectCountResult.FirstOrDefault().ProjectCount ?? 0)
: 0m;
var storeInfo = storeDict.ContainsKey(storeId) ? storeDict[storeId] : new { Name = "", Code = "" };
rankingData.Add(new BusinessUnitStoreRankingItem
{
StoreId = storeId,
StoreCode = storeInfo.Code,
StoreName = storeInfo.Name,
BillingPerformance = billingAmount,
ConsumePerformance = consumeAmount,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
TargetPerformance = targetPerformance,
CompletionRate = completionRate,
BillingCount = billingCount,
ConsumeCount = consumeCount,
HeadCount = headCount,
PersonCount = personCount,
ProjectCount = projectCount,
Percentage = 0m // 占比稍后计算
});
}
// 根据排行类型排序
var rankingType = (input.RankingType ?? "Billing").ToLower();
switch (rankingType)
{
case "consume":
rankingData = rankingData.OrderByDescending(x => x.ConsumePerformance).ToList();
break;
case "completionrate":
rankingData = rankingData.OrderByDescending(x => x.CompletionRate).ToList();
break;
default: // Billing
rankingData = rankingData.OrderByDescending(x => x.BillingPerformance).ToList();
break;
}
// 计算总业绩(用于计算占比)
decimal totalPerformance = 0m;
switch (rankingType)
{
case "consume":
totalPerformance = rankingData.Sum(x => x.ConsumePerformance);
break;
case "completionrate":
totalPerformance = rankingData.Sum(x => x.NetPerformance);
break;
default: // Billing
totalPerformance = rankingData.Sum(x => x.BillingPerformance);
break;
}
// 计算占比并设置排名
var topCount = input.TopCount > 0 ? input.TopCount : 10;
var result = new BusinessUnitDashboardStoreRankingOutput();
for (int i = 0; i < Math.Min(topCount, rankingData.Count); i++)
{
var item = rankingData[i];
item.Ranking = i + 1;
item.Percentage = totalPerformance > 0
? (rankingType == "billing" ? item.BillingPerformance :
rankingType == "consume" ? item.ConsumePerformance : item.NetPerformance) / totalPerformance * 100m
: 0m;
result.RankingData.Add(item);
}
_logger.LogInformation("事业部驾驶舱门店排行数据查询完成,返回{Count}条数据", result.RankingData.Count);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱门店排行数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱运营统计数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的运营分析数据:开单分析、消耗分析、退卡分析
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512"
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
///
/// 返回数据说明:
/// - BillingAnalysis: 开单分析(开单次数、平均开单金额、开单门店数)
/// - ConsumeAnalysis: 消耗分析(消耗次数、消耗金额、消耗率)
/// - RefundAnalysis: 退卡分析(退卡次数、退卡金额、退卡率)
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱运营统计数据</returns>
/// <response code="200">成功返回运营统计数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetOperationStatistics")]
public async Task<BusinessUnitDashboardOperationStatisticsOutput> GetOperationStatistics([FromBody] BusinessUnitDashboardStatisticsInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱运营统计数据,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth}",
input.BusinessUnitId, input.StatisticsMonth);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
return new BusinessUnitDashboardOperationStatisticsOutput();
}
// 1. 开单分析
var billingQuery = _db.Queryable<LqKdKdjlbEntity>()
.Where(x => storeIds.Contains(x.Djmd) && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime);
var billingCount = await billingQuery.CountAsync();
var billingAmount = await billingQuery.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
var avgBillingAmount = billingCount > 0 ? billingAmount / (decimal)billingCount : 0m;
// 开单门店数(有开单的门店数量)
var billingStoreIds = await billingQuery
.Select(x => x.Djmd)
.Distinct()
.ToListAsync();
var billingStoreCount = billingStoreIds.Count;
// 2. 消耗分析
var consumeQuery = _db.Queryable<LqXhHyhkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime);
var consumeCount = await consumeQuery.CountAsync();
var consumeAmount = await consumeQuery.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
var consumeRate = billingAmount > 0 ? (consumeAmount / billingAmount * 100m) : 0m;
// 3. 退卡分析
var refundQuery = _db.Queryable<LqHytkHytkEntity>()
.Where(x => storeIds.Contains(x.Md) && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date);
var refundCount = await refundQuery.CountAsync();
var refundAmount = await refundQuery.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
var refundRate = billingAmount > 0 ? (refundAmount / billingAmount * 100m) : 0m;
var result = new BusinessUnitDashboardOperationStatisticsOutput
{
BillingAnalysis = new BusinessUnitBillingAnalysis
{
BillingCount = billingCount,
AverageBillingAmount = avgBillingAmount,
BillingStoreCount = billingStoreCount
},
ConsumeAnalysis = new BusinessUnitConsumeAnalysis
{
ConsumeCount = consumeCount,
ConsumeAmount = consumeAmount,
ConsumeRate = consumeRate
},
RefundAnalysis = new BusinessUnitRefundAnalysis
{
RefundCount = refundCount,
RefundAmount = refundAmount,
RefundRate = refundRate
}
};
_logger.LogInformation("事业部驾驶舱运营统计数据查询完成,开单次数:{BillingCount},消耗次数:{ConsumeCount},退卡次数:{RefundCount}",
result.BillingAnalysis.BillingCount, result.ConsumeAnalysis.ConsumeCount, result.RefundAnalysis.RefundCount);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱运营统计数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱门店明细列表
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的门店业绩明细列表,支持分页、排序、筛选
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "currentPage": 1,
/// "pageSize": 10,
/// "storeName": "门店名称(可选,模糊查询)"
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
/// - currentPage: 当前页码(可选,默认1)
/// - pageSize: 每页数量(可选,默认10)
/// - storeName: 门店名称(可选,模糊查询)
///
/// 返回数据说明:
/// - 返回分页结果,包含门店列表和分页信息
/// - 每个门店明细包含:门店信息、业绩数据、运营指标等
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱门店明细列表</returns>
/// <response code="200">成功返回明细列表</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetStoreDetailList")]
public async Task<dynamic> GetStoreDetailList([FromBody] BusinessUnitDashboardStoreDetailListInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱门店明细列表,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth},页码:{CurrentPage},每页数量:{PageSize}",
input.BusinessUnitId, input.StatisticsMonth, input.currentPage, input.pageSize);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
return new { total = 0, list = new List<BusinessUnitDashboardStoreDetailListOutput>() };
}
// 获取门店信息(名称、编码),支持门店名称筛选
var storeQuery = _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id));
if (!string.IsNullOrWhiteSpace(input.StoreName))
{
storeQuery = storeQuery.Where(x => x.Dm.Contains(input.StoreName));
}
var stores = await storeQuery.Select(x => new { x.Id, x.Dm, x.Mdbm }).ToListAsync();
var filteredStoreIds = stores.Select(x => x.Id).ToList();
if (!filteredStoreIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardStoreDetailListOutput>() };
}
// 计算每个门店的业绩数据
var detailList = new List<BusinessUnitDashboardStoreDetailListOutput>();
var storeDict = stores.ToDictionary(x => x.Id, x => new { Name = x.Dm ?? "", Code = x.Mdbm ?? "" });
foreach (var storeId in filteredStoreIds)
{
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
// 消耗业绩
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 目标业绩
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.StoreId == storeId && x.Month == input.StatisticsMonth)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
// 开单次数
var billingCount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.CountAsync();
// 消耗次数
var consumeCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.CountAsync();
// 退卡次数
var refundCount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.CountAsync();
// 平均开单金额
var avgBillingAmount = billingCount > 0 ? billingAmount / (decimal)billingCount : 0m;
// 平均消耗金额
var avgConsumeAmount = consumeCount > 0 ? consumeAmount / (decimal)consumeCount : 0m;
// 人头数
var headCount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.Select(x => x.Hy)
.Distinct()
.CountAsync();
// 人次
var personCountSql = $@"
SELECT COUNT(DISTINCT CONCAT(xh.Hy, '-', DATE_FORMAT(xh.Hksj, '%Y-%m-%d'))) as PersonCount
FROM lq_xh_hyhk xh
WHERE xh.Md = '{storeId}'
AND xh.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var personCountResult = await _db.Ado.SqlQueryAsync<dynamic>(personCountSql);
var personCount = personCountResult?.FirstOrDefault() != null
? Convert.ToInt32(personCountResult.FirstOrDefault().PersonCount ?? 0)
: 0;
// 项目数
var projectCountSql = $@"
SELECT COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) as ProjectCount
FROM lq_xh_pxmx px
INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
WHERE xh.Md = '{storeId}'
AND xh.F_IsEffective = 1
AND px.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var projectCountResult = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);
var projectCount = projectCountResult?.FirstOrDefault() != null
? Convert.ToDecimal(projectCountResult.FirstOrDefault().ProjectCount ?? 0)
: 0m;
var storeInfo = storeDict.ContainsKey(storeId) ? storeDict[storeId] : new { Name = "", Code = "" };
detailList.Add(new BusinessUnitDashboardStoreDetailListOutput
{
StoreId = storeId,
StoreCode = storeInfo.Code,
StoreName = storeInfo.Name,
BillingPerformance = billingAmount,
ConsumePerformance = consumeAmount,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
TargetPerformance = targetPerformance,
CompletionRate = completionRate,
BillingCount = billingCount,
ConsumeCount = consumeCount,
RefundCount = refundCount,
AvgBillingAmount = avgBillingAmount,
AvgConsumeAmount = avgConsumeAmount,
HeadCount = headCount,
PersonCount = personCount,
ProjectCount = projectCount
});
}
// 分页处理
var currentPage = input.currentPage > 0 ? input.currentPage : 1;
var pageSize = input.pageSize > 0 ? input.pageSize : 10;
var total = detailList.Count;
var pagedList = detailList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
_logger.LogInformation("事业部驾驶舱门店明细列表查询完成,总数:{Total},返回{Count}条数据", total, pagedList.Count);
return new { total = total, list = pagedList };
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱门店明细列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱总经理/经理业绩排行
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的总经理/经理业绩排行数据
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "topCount": 10
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
/// - topCount: 排行数量(可选,默认10)
///
/// 返回数据说明:
/// - RankingData: 总经理/经理排行数据列表,包含排名、姓名、管理的门店、业绩、工资等信息
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱总经理/经理排行数据</returns>
/// <response code="200">成功返回排行数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetManagerRanking")]
public async Task<BusinessUnitDashboardManagerRankingOutput> GetManagerRanking([FromBody] BusinessUnitDashboardManagerRankingInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱总经理/经理排行数据,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth}",
input.BusinessUnitId, input.StatisticsMonth);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
return new BusinessUnitDashboardManagerRankingOutput();
}
// 1. 获取总经理/经理归属信息(从lq_md_general_manager_lifeline表,只查询管理这些门店的总经理/经理)
var lifelineList = await _db.Queryable<LqMdGeneralManagerLifelineEntity>()
.Where(x => x.Month == input.StatisticsMonth && storeIds.Contains(x.StoreId))
.ToListAsync();
if (!lifelineList.Any())
{
return new BusinessUnitDashboardManagerRankingOutput();
}
// 2. 获取所有不重复的总经理/经理ID
var allManagerIds = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId))
.Select(x => x.GeneralManagerId)
.Distinct()
.ToList();
// 3. 获取用户信息
var users = await _db.Queryable<UserEntity>()
.Where(x => allManagerIds.Contains(x.Id) && x.DeleteMark == null)
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = users.ToDictionary(x => x.Id, x => x.RealName ?? "");
// 4. 获取门店信息
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 5. 获取工资统计数据
var salaryStats = await _db.Queryable<LqBusinessUnitManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == input.StatisticsMonth && allManagerIds.Contains(x.EmployeeId))
.ToListAsync();
var salaryDict = salaryStats.ToDictionary(x => x.EmployeeId, x => x);
// 6. 按总经理/经理ID分组,获取每个总经理/经理管理的门店
var managerStoreDict = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId) && !string.IsNullOrEmpty(x.StoreId))
.GroupBy(x => x.GeneralManagerId)
.ToDictionary(g => g.Key, g => g.Select(x => x.StoreId).Distinct().ToList());
// 7. 计算每个总经理/经理的业绩数据
var rankingData = new List<BusinessUnitManagerRankingItem>();
foreach (var managerId in allManagerIds)
{
var managerStores = managerStoreDict.ContainsKey(managerId) ? managerStoreDict[managerId] : new List<string>();
if (!managerStores.Any()) continue;
// 计算管理的门店总业绩
decimal totalBilling = 0m;
decimal totalRefund = 0m;
decimal totalConsume = 0m;
foreach (var storeId in managerStores)
{
// 开单业绩
var billing = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
totalBilling += billing;
// 退卡金额
var refund = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
totalRefund += refund;
// 消耗业绩
var consume = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
totalConsume += consume;
}
var totalPerformance = totalBilling - totalRefund;
// 获取工资数据
var salary = salaryDict.ContainsKey(managerId) ? salaryDict[managerId] : null;
var managerLifeline = lifelineList.FirstOrDefault(x => x.GeneralManagerId == managerId);
var storeNames = managerStores
.Where(s => storeDict.ContainsKey(s))
.Select(s => storeDict[s])
.ToList();
rankingData.Add(new BusinessUnitManagerRankingItem
{
ManagerId = managerId,
ManagerName = userDict.ContainsKey(managerId) ? userDict[managerId] : "",
ManagerType = managerLifeline?.ManagerType ?? 1,
Position = managerLifeline?.ManagerType == 1 ? "总经理" : "经理",
ManagedStoreCount = managerStores.Count,
ManagedStoreNames = storeNames,
TotalBillingPerformance = totalBilling,
TotalConsumePerformance = totalConsume,
TotalGrossProfit = salary?.GrossProfit ?? 0m,
BaseSalary = salary?.BaseSalary ?? 0m,
Commission = salary?.TotalCommission ?? 0m,
TotalSalary = salary?.FinalGrossSalary ?? 0m,
Percentage = 0m // 稍后计算
});
}
// 8. 按总业绩排序
rankingData = rankingData.OrderByDescending(x => x.TotalBillingPerformance).ToList();
// 9. 计算总业绩和占比
var totalPerformanceSum = rankingData.Sum(x => x.TotalBillingPerformance);
var topCount = input.TopCount > 0 ? input.TopCount : 10;
var result = new BusinessUnitDashboardManagerRankingOutput();
for (int i = 0; i < Math.Min(topCount, rankingData.Count); i++)
{
var item = rankingData[i];
item.Ranking = i + 1;
item.Percentage = totalPerformanceSum > 0 ? (item.TotalBillingPerformance / totalPerformanceSum * 100m) : 0m;
result.RankingData.Add(item);
}
_logger.LogInformation("事业部驾驶舱总经理/经理排行数据查询完成,返回{Count}条数据", result.RankingData.Count);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱总经理/经理排行数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱对比分析数据
/// </summary>
/// <remarks>
/// 获取指定事业部的对比分析数据:时间对比(环比、同比)、部门对比
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "comparisonType": "Time"
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
/// - comparisonType: 对比类型(可选,默认:Time)
/// - Time - 时间对比(环比、同比)
/// - Department - 部门对比(各事业部对比)
///
/// 返回数据说明:
/// - TimeComparison: 时间对比数据(环比、同比)
/// - DepartmentComparison: 部门对比数据(各事业部对比)
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱对比分析数据</returns>
/// <response code="200">成功返回对比分析数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetComparisonAnalysis")]
public async Task<BusinessUnitDashboardComparisonAnalysisOutput> GetComparisonAnalysis([FromBody] BusinessUnitDashboardComparisonAnalysisInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱对比分析数据,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth}",
input.BusinessUnitId, input.StatisticsMonth);
var result = new BusinessUnitDashboardComparisonAnalysisOutput();
// 1. 时间对比(环比、同比)
var currentMonth = DateTime.ParseExact(input.StatisticsMonth, "yyyyMM", null);
var lastMonth = currentMonth.AddMonths(-1);
var lastYearMonth = currentMonth.AddYears(-1);
// 当前月数据
var currentData = await CalculateMonthlyPerformance(
await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth),
input.StatisticsMonth);
// 上月数据(环比)
var lastMonthStr = lastMonth.ToString("yyyyMM");
var lastMonthStoreIds = await GetStoreIdsForMonthAsync(input.BusinessUnitId, input.StoreIds, lastMonthStr);
var lastMonthData = await CalculateMonthlyPerformance(lastMonthStoreIds, lastMonthStr);
// 去年同月数据(同比)
var lastYearMonthStr = lastYearMonth.ToString("yyyyMM");
var lastYearMonthStoreIds = await GetStoreIdsForMonthAsync(input.BusinessUnitId, input.StoreIds, lastYearMonthStr);
var lastYearMonthData = await CalculateMonthlyPerformance(lastYearMonthStoreIds, lastYearMonthStr);
// 环比对比
result.TimeComparison.MonthOverMonth = new BusinessUnitComparisonItem
{
BillingPerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.billingPerformance,
CompareValue = lastMonthData.billingPerformance,
GrowthRate = lastMonthData.billingPerformance > 0
? ((currentData.billingPerformance - lastMonthData.billingPerformance) / lastMonthData.billingPerformance * 100m)
: 0m
},
ConsumePerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.consumePerformance,
CompareValue = lastMonthData.consumePerformance,
GrowthRate = lastMonthData.consumePerformance > 0
? ((currentData.consumePerformance - lastMonthData.consumePerformance) / lastMonthData.consumePerformance * 100m)
: 0m
},
NetPerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.netPerformance,
CompareValue = lastMonthData.netPerformance,
GrowthRate = lastMonthData.netPerformance > 0
? ((currentData.netPerformance - lastMonthData.netPerformance) / lastMonthData.netPerformance * 100m)
: 0m
},
CompletionRate = new BusinessUnitComparisonValue
{
CurrentValue = currentData.completionRate,
CompareValue = lastMonthData.completionRate,
GrowthRate = lastMonthData.completionRate > 0
? ((currentData.completionRate - lastMonthData.completionRate) / lastMonthData.completionRate * 100m)
: 0m
}
};
// 同比对比
result.TimeComparison.YearOverYear = new BusinessUnitComparisonItem
{
BillingPerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.billingPerformance,
CompareValue = lastYearMonthData.billingPerformance,
GrowthRate = lastYearMonthData.billingPerformance > 0
? ((currentData.billingPerformance - lastYearMonthData.billingPerformance) / lastYearMonthData.billingPerformance * 100m)
: 0m
},
ConsumePerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.consumePerformance,
CompareValue = lastYearMonthData.consumePerformance,
GrowthRate = lastYearMonthData.consumePerformance > 0
? ((currentData.consumePerformance - lastYearMonthData.consumePerformance) / lastYearMonthData.consumePerformance * 100m)
: 0m
},
NetPerformance = new BusinessUnitComparisonValue
{
CurrentValue = currentData.netPerformance,
CompareValue = lastYearMonthData.netPerformance,
GrowthRate = lastYearMonthData.netPerformance > 0
? ((currentData.netPerformance - lastYearMonthData.netPerformance) / lastYearMonthData.netPerformance * 100m)
: 0m
},
CompletionRate = new BusinessUnitComparisonValue
{
CurrentValue = currentData.completionRate,
CompareValue = lastYearMonthData.completionRate,
GrowthRate = lastYearMonthData.completionRate > 0
? ((currentData.completionRate - lastYearMonthData.completionRate) / lastYearMonthData.completionRate * 100m)
: 0m
}
};
// 2. 部门对比(各事业部对比)- 如果comparisonType包含Department
if (input.ComparisonType != null && input.ComparisonType.ToLower().Contains("department"))
{
// 获取所有事业部ID(从BASE_ORGANIZE表)
var allBusinessUnits = await _db.Queryable<OrganizeEntity>()
.Where(x => x.DeleteMark == null && x.EnabledMark == 1)
.Where(x => x.Category == "事业部" || x.FullName.Contains("事业部"))
.Select(x => new { x.Id, x.FullName })
.ToListAsync();
foreach (var bu in allBusinessUnits)
{
var buStoreIds = await GetStoreIdsForMonthAsync(bu.Id, null, input.StatisticsMonth);
if (!buStoreIds.Any()) continue;
var buData = await CalculateMonthlyPerformance(buStoreIds, input.StatisticsMonth);
result.DepartmentComparison.DepartmentData.Add(new BusinessUnitDepartmentComparisonItem
{
BusinessUnitId = bu.Id,
BusinessUnitName = bu.FullName ?? "",
BillingPerformance = buData.billingPerformance,
ConsumePerformance = buData.consumePerformance,
NetPerformance = buData.netPerformance,
CompletionRate = buData.completionRate
});
}
}
_logger.LogInformation("事业部驾驶舱对比分析数据查询完成");
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱对比分析数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱门店业绩分布数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的门店业绩分布数据(饼图和柱状图数据)
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512"
/// }
/// ```
///
/// 参数说明:
/// - businessUnitId: 事业部ID(BASE_ORGANIZE表的组织ID),与storeIds两者必填其一
/// - storeIds: 门店ID列表,与businessUnitId两者必填其一
/// - statisticsMonth: 统计月份,格式为YYYYMM(必填)
///
/// 返回数据说明:
/// - DistributionData: 门店业绩分布数据列表(饼图数据,包含占比)
/// - ComparisonData: 门店业绩对比数据列表(柱状图数据)
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱门店业绩分布数据</returns>
/// <response code="200">成功返回分布数据</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetStoreDistribution")]
public async Task<BusinessUnitDashboardStoreDistributionOutput> GetStoreDistribution([FromBody] BusinessUnitDashboardStatisticsInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
_logger.LogInformation("开始查询事业部驾驶舱门店业绩分布数据,事业部ID:{BusinessUnitId},统计月份:{StatisticsMonth}",
input.BusinessUnitId, input.StatisticsMonth);
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
_logger.LogWarning("事业部ID:{BusinessUnitId} 在 {StatisticsMonth} 月份没有管理的门店", input.BusinessUnitId, input.StatisticsMonth);
return new BusinessUnitDashboardStoreDistributionOutput();
}
// 获取门店信息
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 计算每个门店的业绩
var distributionList = new List<BusinessUnitStoreDistributionItem>();
decimal totalPerformance = 0m;
foreach (var storeId in storeIds)
{
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
totalPerformance += netPerformance;
distributionList.Add(new BusinessUnitStoreDistributionItem
{
StoreId = storeId,
StoreName = storeDict.ContainsKey(storeId) ? storeDict[storeId] : "",
Performance = netPerformance,
Percentage = 0m // 稍后计算
});
}
// 计算占比
foreach (var item in distributionList)
{
item.Percentage = totalPerformance > 0 ? (item.Performance / totalPerformance * 100m) : 0m;
}
var result = new BusinessUnitDashboardStoreDistributionOutput
{
DistributionData = distributionList,
ComparisonData = distributionList.OrderByDescending(x => x.Performance).ToList()
};
_logger.LogInformation("事业部驾驶舱门店业绩分布数据查询完成,门店数量:{Count}", distributionList.Count);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱门店业绩分布数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱总经理/经理业绩分布数据
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的总经理/经理业绩分布数据(饼图数据)
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512"
/// }
/// ```
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱总经理/经理业绩分布数据</returns>
[HttpPost("GetManagerDistribution")]
public async Task<BusinessUnitDashboardManagerDistributionOutput> GetManagerDistribution([FromBody] BusinessUnitDashboardStatisticsInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new BusinessUnitDashboardManagerDistributionOutput();
}
// 获取总经理/经理归属信息
var lifelineList = await _db.Queryable<LqMdGeneralManagerLifelineEntity>()
.Where(x => x.Month == input.StatisticsMonth && storeIds.Contains(x.StoreId))
.ToListAsync();
if (!lifelineList.Any())
{
return new BusinessUnitDashboardManagerDistributionOutput();
}
var allManagerIds = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId))
.Select(x => x.GeneralManagerId)
.Distinct()
.ToList();
// 获取用户信息
var users = await _db.Queryable<UserEntity>()
.Where(x => allManagerIds.Contains(x.Id) && x.DeleteMark == null)
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = users.ToDictionary(x => x.Id, x => x.RealName ?? "");
// 按总经理/经理ID分组,获取每个总经理/经理管理的门店
var managerStoreDict = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId) && !string.IsNullOrEmpty(x.StoreId))
.GroupBy(x => x.GeneralManagerId)
.ToDictionary(g => g.Key, g => g.Select(x => x.StoreId).Distinct().ToList());
// 计算每个总经理/经理的业绩
var distributionList = new List<BusinessUnitManagerDistributionItem>();
decimal totalPerformance = 0m;
foreach (var managerId in allManagerIds)
{
var managerStores = managerStoreDict.ContainsKey(managerId) ? managerStoreDict[managerId] : new List<string>();
if (!managerStores.Any()) continue;
decimal totalBilling = 0m;
decimal totalRefund = 0m;
foreach (var storeId in managerStores)
{
var billing = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
totalBilling += billing;
var refund = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
totalRefund += refund;
}
var performance = totalBilling - totalRefund;
totalPerformance += performance;
distributionList.Add(new BusinessUnitManagerDistributionItem
{
ManagerId = managerId,
ManagerName = userDict.ContainsKey(managerId) ? userDict[managerId] : "",
Performance = performance,
Percentage = 0m // 稍后计算
});
}
// 计算占比
foreach (var item in distributionList)
{
item.Percentage = totalPerformance > 0 ? (item.Performance / totalPerformance * 100m) : 0m;
}
return new BusinessUnitDashboardManagerDistributionOutput
{
DistributionData = distributionList.OrderByDescending(x => x.Performance).ToList()
};
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱总经理/经理业绩分布数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱总经理/经理业绩趋势数据
/// </summary>
/// <remarks>
/// 获取指定总经理/经理的近N个月业绩趋势数据
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "managerIds": ["1649328471923847169"],
/// "monthCount": 12
/// }
/// ```
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱总经理/经理业绩趋势数据</returns>
[HttpPost("GetManagerTrend")]
public async Task<BusinessUnitDashboardManagerTrendOutput> GetManagerTrend([FromBody] BusinessUnitDashboardManagerTrendInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (input.ManagerIds == null || !input.ManagerIds.Any())
throw NCCException.Oh("总经理/经理ID列表不能为空");
var monthCount = input.MonthCount;
if (monthCount != 3 && monthCount != 6 && monthCount != 12)
monthCount = 12;
var baseMonth = DateTime.ParseExact(input.StatisticsMonth, "yyyyMM", null);
var result = new BusinessUnitDashboardManagerTrendOutput();
// 获取用户信息
var users = await _db.Queryable<UserEntity>()
.Where(x => input.ManagerIds.Contains(x.Id) && x.DeleteMark == null)
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = users.ToDictionary(x => x.Id, x => x.RealName ?? "");
foreach (var managerId in input.ManagerIds)
{
var trendData = new BusinessUnitManagerTrendData
{
ManagerId = managerId,
ManagerName = userDict.ContainsKey(managerId) ? userDict[managerId] : ""
};
for (int i = monthCount - 1; i >= 0; i--)
{
var trendMonth = baseMonth.AddMonths(-i);
var trendMonthStr = trendMonth.ToString("yyyyMM");
// 获取该月份该总经理/经理管理的门店
var managerStores = await _db.Queryable<LqMdGeneralManagerLifelineEntity>()
.Where(x => x.GeneralManagerId == managerId && x.Month == trendMonthStr)
.Select(x => x.StoreId)
.Distinct()
.ToListAsync();
if (!managerStores.Any())
{
trendData.TrendPoints.Add(new BusinessUnitManagerTrendPoint { Month = trendMonthStr });
continue;
}
// 计算该月份的总业绩
var year = trendMonth.Year;
var month = trendMonth.Month;
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = trendMonthStr == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
decimal totalBilling = 0m;
decimal totalRefund = 0m;
foreach (var storeId in managerStores)
{
var billing = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
totalBilling += billing;
var refund = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
totalRefund += refund;
}
trendData.TrendPoints.Add(new BusinessUnitManagerTrendPoint
{
Month = trendMonthStr,
TotalPerformance = totalBilling - totalRefund
});
}
result.ManagerTrendData.Add(trendData);
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱总经理/经理业绩趋势数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱店长业绩排行
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的店长业绩排行数据
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "topCount": 10
/// }
/// ```
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱店长业绩排行数据</returns>
[HttpPost("GetStoreManagerRanking")]
public async Task<BusinessUnitDashboardStoreManagerRankingOutput> GetStoreManagerRanking([FromBody] BusinessUnitDashboardStoreManagerRankingInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new BusinessUnitDashboardStoreManagerRankingOutput();
}
// 获取店长信息(BASE_USER表,F_GW = '店长')
var storeManagers = await _db.Queryable<UserEntity>()
.Where(x => x.Gw == "店长" && storeIds.Contains(x.Mdid) && x.DeleteMark == null && x.EnabledMark == 1)
.Select(x => new { x.Id, x.RealName, x.Mdid })
.ToListAsync();
if (!storeManagers.Any())
{
return new BusinessUnitDashboardStoreManagerRankingOutput();
}
// 获取门店信息
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 计算每个店长的业绩
var rankingData = new List<BusinessUnitStoreManagerRankingItem>();
foreach (var manager in storeManagers)
{
var storeId = manager.Mdid;
if (string.IsNullOrEmpty(storeId)) continue;
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
// 消耗业绩
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 目标业绩
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.StoreId == storeId && x.Month == input.StatisticsMonth)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
rankingData.Add(new BusinessUnitStoreManagerRankingItem
{
StoreManagerId = manager.Id,
StoreManagerName = manager.RealName ?? "",
StoreId = storeId,
StoreName = storeDict.ContainsKey(storeId) ? storeDict[storeId] : "",
BillingPerformance = billingAmount,
ConsumePerformance = consumeAmount,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
CompletionRate = completionRate,
Ranking = 0 // 稍后设置
});
}
// 按净业绩排序
rankingData = rankingData.OrderByDescending(x => x.NetPerformance).ToList();
// 设置排名
var topCount = input.TopCount > 0 ? input.TopCount : 10;
var result = new BusinessUnitDashboardStoreManagerRankingOutput();
for (int i = 0; i < Math.Min(topCount, rankingData.Count); i++)
{
rankingData[i].Ranking = i + 1;
result.RankingData.Add(rankingData[i]);
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱店长业绩排行数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱健康师业绩排行
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的健康师业绩排行数据
///
/// 示例请求:
/// ```json
/// {
/// "businessUnitId": "734725299018663173",
/// "statisticsMonth": "202512",
/// "topCount": 10
/// }
/// ```
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱健康师业绩排行数据</returns>
[HttpPost("GetHealthCoachRanking")]
public async Task<BusinessUnitDashboardHealthCoachRankingOutput> GetHealthCoachRanking([FromBody] BusinessUnitDashboardHealthCoachRankingInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new BusinessUnitDashboardHealthCoachRankingOutput();
}
// 获取健康师信息(BASE_USER表,F_GW = '健康师')
var healthCoaches = await _db.Queryable<UserEntity>()
.Where(x => x.Gw == "健康师" && storeIds.Contains(x.Mdid) && x.DeleteMark == null && x.EnabledMark == 1)
.Select(x => new { x.Id, x.RealName, x.Mdid })
.ToListAsync();
if (!healthCoaches.Any())
{
return new BusinessUnitDashboardHealthCoachRankingOutput();
}
// 获取门店信息
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 计算每个健康师的业绩
var rankingData = new List<BusinessUnitHealthCoachRankingItem>();
var storeIdsStr = string.Join("','", storeIds);
foreach (var coach in healthCoaches)
{
var storeId = coach.Mdid;
if (string.IsNullOrEmpty(storeId)) continue;
// 开单业绩(从lq_kd_jksyj表,jksyj字段是字符串类型,需要转换,使用jkszh字段匹配健康师ID)
var billingSql = $@"
SELECT COALESCE(SUM(CAST(jksyj AS DECIMAL(18,2))), 0) as Amount
FROM lq_kd_jksyj
WHERE F_IsEffective = 1
AND F_StoreId = '{storeId}'
AND jkszh = '{coach.Id}'
AND yjsj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND yjsj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var billingResult = await _db.Ado.SqlQueryAsync<dynamic>(billingSql);
var billingPerformance = billingResult?.FirstOrDefault() != null
? Convert.ToDecimal(billingResult.FirstOrDefault().Amount ?? 0)
: 0m;
// 消耗业绩(从lq_xh_jksyj表,使用jkszh字段匹配健康师ID)
var consumePerformance = await _db.Queryable<LqXhJksyjEntity>()
.Where(x => x.StoreId == storeId && x.Jkszh == coach.Id && x.IsEffective == 1)
.Where(x => x.Yjsj.HasValue && x.Yjsj.Value >= startDate && x.Yjsj.Value <= endDateTime)
.SumAsync(x => (decimal?)(x.Jksyj ?? 0)) ?? 0m;
// 退卡业绩(从lq_hytk_jksyj表,使用jkszh字段匹配健康师ID)
var refundPerformance = await _db.Queryable<LqHytkJksyjEntity>()
.Where(x => x.StoreId == storeId && x.Jkszh == coach.Id && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.Jksyj ?? 0)) ?? 0m;
// 总业绩
var totalPerformance = billingPerformance - refundPerformance;
// 项目数(从lq_xh_pxmx表,关联lq_xh_hyhk,再关联lq_xh_jksyj)
var projectCountSql = $@"
SELECT COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) as ProjectCount
FROM lq_xh_pxmx px
INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
INNER JOIN lq_xh_jksyj jksyj ON jksyj.glkdbh = xh.F_Id
WHERE xh.Md = '{storeId}'
AND jksyj.jkszh = '{coach.Id}'
AND xh.F_IsEffective = 1
AND jksyj.F_IsEffective = 1
AND px.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var projectCountResult = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);
var projectCount = projectCountResult?.FirstOrDefault() != null
? Convert.ToDecimal(projectCountResult.FirstOrDefault().ProjectCount ?? 0)
: 0m;
rankingData.Add(new BusinessUnitHealthCoachRankingItem
{
HealthCoachId = coach.Id,
HealthCoachName = coach.RealName ?? "",
StoreId = storeId,
StoreName = storeDict.ContainsKey(storeId) ? storeDict[storeId] : "",
BillingPerformance = billingPerformance,
ConsumePerformance = consumePerformance,
RefundPerformance = refundPerformance,
TotalPerformance = totalPerformance,
ProjectCount = projectCount,
Ranking = 0 // 稍后设置
});
}
// 按总业绩排序
rankingData = rankingData.OrderByDescending(x => x.TotalPerformance).ToList();
// 设置排名
var topCount = input.TopCount > 0 ? input.TopCount : 10;
var result = new BusinessUnitDashboardHealthCoachRankingOutput();
for (int i = 0; i < Math.Min(topCount, rankingData.Count); i++)
{
rankingData[i].Ranking = i + 1;
result.RankingData.Add(rankingData[i]);
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱健康师业绩排行数据失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱总经理/经理明细列表
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的总经理/经理明细列表,支持分页、排序、筛选
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱总经理/经理明细列表</returns>
[HttpPost("GetManagerDetailList")]
public async Task<dynamic> GetManagerDetailList([FromBody] BusinessUnitDashboardManagerDetailListInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardManagerDetailListOutput>() };
}
// 获取总经理/经理归属信息
var lifelineList = await _db.Queryable<LqMdGeneralManagerLifelineEntity>()
.Where(x => x.Month == input.StatisticsMonth && storeIds.Contains(x.StoreId))
.ToListAsync();
if (!lifelineList.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardManagerDetailListOutput>() };
}
var allManagerIds = lifelineList
.Where(x => !string.IsNullOrEmpty(x.GeneralManagerId))
.Select(x => x.GeneralManagerId)
.Distinct()
.ToList();
// 获取用户信息,支持姓名筛选
var userQuery = _db.Queryable<UserEntity>()
.Where(x => allManagerIds.Contains(x.Id) && x.DeleteMark == null);
if (!string.IsNullOrWhiteSpace(input.ManagerName))
{
userQuery = userQuery.Where(x => x.RealName.Contains(input.ManagerName));
}
var users = await userQuery.Select(x => new { x.Id, x.RealName }).ToListAsync();
var filteredManagerIds = users.Select(x => x.Id).ToList();
if (!filteredManagerIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardManagerDetailListOutput>() };
}
var userDict = users.ToDictionary(x => x.Id, x => x.RealName ?? "");
// 获取门店信息
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 获取工资统计数据
var salaryStats = await _db.Queryable<LqBusinessUnitManagerSalaryStatisticsEntity>()
.Where(x => x.StatisticsMonth == input.StatisticsMonth && filteredManagerIds.Contains(x.EmployeeId))
.ToListAsync();
var salaryDict = salaryStats.ToDictionary(x => x.EmployeeId, x => x);
// 按总经理/经理ID分组
var managerStoreDict = lifelineList
.Where(x => filteredManagerIds.Contains(x.GeneralManagerId) && !string.IsNullOrEmpty(x.StoreId))
.GroupBy(x => x.GeneralManagerId)
.ToDictionary(g => g.Key, g => g.Select(x => x.StoreId).Distinct().ToList());
// 计算每个总经理/经理的业绩数据
var detailList = new List<BusinessUnitDashboardManagerDetailListOutput>();
foreach (var managerId in filteredManagerIds)
{
var managerStores = managerStoreDict.ContainsKey(managerId) ? managerStoreDict[managerId] : new List<string>();
if (!managerStores.Any()) continue;
decimal totalBilling = 0m;
decimal totalRefund = 0m;
decimal totalConsume = 0m;
foreach (var storeId in managerStores)
{
var billing = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
totalBilling += billing;
var refund = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
totalRefund += refund;
var consume = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
totalConsume += consume;
}
var salary = salaryDict.ContainsKey(managerId) ? salaryDict[managerId] : null;
var managerLifeline = lifelineList.FirstOrDefault(x => x.GeneralManagerId == managerId);
var storeNames = managerStores
.Where(s => storeDict.ContainsKey(s))
.Select(s => storeDict[s])
.ToList();
detailList.Add(new BusinessUnitDashboardManagerDetailListOutput
{
ManagerId = managerId,
ManagerName = userDict.ContainsKey(managerId) ? userDict[managerId] : "",
ManagerType = managerLifeline?.ManagerType ?? 1,
Position = managerLifeline?.ManagerType == 1 ? "总经理" : "经理",
ManagedStoreCount = managerStores.Count,
ManagedStoreNames = storeNames,
TotalBillingPerformance = totalBilling,
TotalConsumePerformance = totalConsume,
TotalGrossProfit = salary?.GrossProfit ?? 0m,
BaseSalary = salary?.BaseSalary ?? 0m,
Commission = salary?.TotalCommission ?? 0m,
TotalSalary = salary?.FinalGrossSalary ?? 0m
});
}
// 分页处理
var currentPage = input.currentPage > 0 ? input.currentPage : 1;
var pageSize = input.pageSize > 0 ? input.pageSize : 10;
var total = detailList.Count;
var pagedList = detailList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
return new { total = total, list = pagedList };
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱总经理/经理明细列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱店长明细列表
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的店长明细列表,支持分页、排序、筛选
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱店长明细列表</returns>
[HttpPost("GetStoreManagerDetailList")]
public async Task<dynamic> GetStoreManagerDetailList([FromBody] BusinessUnitDashboardStoreManagerDetailListInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardStoreManagerDetailListOutput>() };
}
// 获取门店信息,支持门店名称筛选
var storeQuery = _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id));
if (!string.IsNullOrWhiteSpace(input.StoreName))
{
storeQuery = storeQuery.Where(x => x.Dm.Contains(input.StoreName));
}
var stores = await storeQuery.Select(x => new { x.Id, x.Dm }).ToListAsync();
var filteredStoreIds = stores.Select(x => x.Id).ToList();
if (!filteredStoreIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardStoreManagerDetailListOutput>() };
}
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 获取店长信息,支持店长姓名筛选
var managerQuery = _db.Queryable<UserEntity>()
.Where(x => x.Gw == "店长" && filteredStoreIds.Contains(x.Mdid) && x.DeleteMark == null && x.EnabledMark == 1);
if (!string.IsNullOrWhiteSpace(input.StoreManagerName))
{
managerQuery = managerQuery.Where(x => x.RealName.Contains(input.StoreManagerName));
}
var storeManagers = await managerQuery.Select(x => new { x.Id, x.RealName, x.Mdid }).ToListAsync();
if (!storeManagers.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardStoreManagerDetailListOutput>() };
}
// 计算每个店长的业绩数据
var detailList = new List<BusinessUnitDashboardStoreManagerDetailListOutput>();
foreach (var manager in storeManagers)
{
var storeId = manager.Mdid;
if (string.IsNullOrEmpty(storeId)) continue;
// 开单业绩
var billingAmount = await _db.Queryable<LqKdKdjlbEntity>()
.Where(x => x.Djmd == storeId && x.IsEffective == 1)
.Where(x => x.Kdrq.HasValue && x.Kdrq.Value >= startDate && x.Kdrq.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Sfyj) ?? 0m;
// 退卡金额
var refundAmount = await _db.Queryable<LqHytkHytkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.ActualRefundAmount ?? x.Tkje ?? 0)) ?? 0m;
// 净业绩
var netPerformance = billingAmount - refundAmount;
// 消耗业绩
var consumeAmount = await _db.Queryable<LqXhHyhkEntity>()
.Where(x => x.Md == storeId && x.IsEffective == 1)
.Where(x => x.Hksj.HasValue && x.Hksj.Value >= startDate && x.Hksj.Value <= endDateTime)
.SumAsync(x => (decimal?)x.Xfje) ?? 0m;
// 目标业绩
var targetPerformance = await _db.Queryable<LqMdTargetEntity>()
.Where(x => x.StoreId == storeId && x.Month == input.StatisticsMonth)
.SumAsync(x => (decimal?)x.BusinessUnitTarget) ?? 0m;
// 完成率
var completionRate = targetPerformance > 0 ? (netPerformance / targetPerformance * 100m) : 0m;
detailList.Add(new BusinessUnitDashboardStoreManagerDetailListOutput
{
StoreManagerId = manager.Id,
StoreManagerName = manager.RealName ?? "",
StoreId = storeId,
StoreName = storeDict.ContainsKey(storeId) ? storeDict[storeId] : "",
BillingPerformance = billingAmount,
ConsumePerformance = consumeAmount,
RefundAmount = refundAmount,
NetPerformance = netPerformance,
TargetPerformance = targetPerformance,
CompletionRate = completionRate
});
}
// 分页处理
var currentPage = input.currentPage > 0 ? input.currentPage : 1;
var pageSize = input.pageSize > 0 ? input.pageSize : 10;
var total = detailList.Count;
var pagedList = detailList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
return new { total = total, list = pagedList };
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱店长明细列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 获取事业部驾驶舱健康师明细列表
/// </summary>
/// <remarks>
/// 获取指定事业部在指定月份的健康师明细列表,支持分页、排序、筛选
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>事业部驾驶舱健康师明细列表</returns>
[HttpPost("GetHealthCoachDetailList")]
public async Task<dynamic> GetHealthCoachDetailList([FromBody] BusinessUnitDashboardHealthCoachDetailListInput input)
{
try
{
if (input == null) throw NCCException.Oh("请求参数不能为空");
if (string.IsNullOrWhiteSpace(input.StatisticsMonth) || input.StatisticsMonth.Length != 6)
throw NCCException.Oh("统计月份格式错误,必须为YYYYMM格式");
if (string.IsNullOrWhiteSpace(input.BusinessUnitId) && (input.StoreIds == null || !input.StoreIds.Any()))
throw NCCException.Oh("事业部ID和门店ID列表不能同时为空,必须传入其中一个");
// 解析月份获取时间范围
var year = int.Parse(input.StatisticsMonth.Substring(0, 4));
var month = int.Parse(input.StatisticsMonth.Substring(4, 2));
var startDate = new DateTime(year, month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
var endDateTime = input.StatisticsMonth == DateTime.Now.ToString("yyyyMM")
? DateTime.Now
: endDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
// 获取门店列表
var storeIds = await GetStoreIdsAsync(input.BusinessUnitId, input.StoreIds, input.StatisticsMonth);
if (!storeIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardHealthCoachDetailListOutput>() };
}
// 获取门店信息,支持门店名称筛选
var storeQuery = _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id));
if (!string.IsNullOrWhiteSpace(input.StoreName))
{
storeQuery = storeQuery.Where(x => x.Dm.Contains(input.StoreName));
}
var stores = await storeQuery.Select(x => new { x.Id, x.Dm }).ToListAsync();
var filteredStoreIds = stores.Select(x => x.Id).ToList();
if (!filteredStoreIds.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardHealthCoachDetailListOutput>() };
}
var storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
// 获取健康师信息,支持健康师姓名筛选
var coachQuery = _db.Queryable<UserEntity>()
.Where(x => x.Gw == "健康师" && filteredStoreIds.Contains(x.Mdid) && x.DeleteMark == null && x.EnabledMark == 1);
if (!string.IsNullOrWhiteSpace(input.HealthCoachName))
{
coachQuery = coachQuery.Where(x => x.RealName.Contains(input.HealthCoachName));
}
var healthCoaches = await coachQuery.Select(x => new { x.Id, x.RealName, x.Mdid }).ToListAsync();
if (!healthCoaches.Any())
{
return new { total = 0, list = new List<BusinessUnitDashboardHealthCoachDetailListOutput>() };
}
// 计算每个健康师的业绩数据
var detailList = new List<BusinessUnitDashboardHealthCoachDetailListOutput>();
var storeIdsStr = string.Join("','", filteredStoreIds);
foreach (var coach in healthCoaches)
{
var storeId = coach.Mdid;
if (string.IsNullOrEmpty(storeId)) continue;
// 开单业绩(从lq_kd_jksyj表,jksyj字段是字符串类型,需要转换,使用jkszh字段匹配健康师ID)
var billingSql = $@"
SELECT COALESCE(SUM(CAST(jksyj AS DECIMAL(18,2))), 0) as Amount
FROM lq_kd_jksyj
WHERE F_IsEffective = 1
AND F_StoreId = '{storeId}'
AND jkszh = '{coach.Id}'
AND yjsj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND yjsj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var billingResult = await _db.Ado.SqlQueryAsync<dynamic>(billingSql);
var billingPerformance = billingResult?.FirstOrDefault() != null
? Convert.ToDecimal(billingResult.FirstOrDefault().Amount ?? 0)
: 0m;
// 消耗业绩(从lq_xh_jksyj表,使用jkszh字段匹配健康师ID)
var consumePerformance = await _db.Queryable<LqXhJksyjEntity>()
.Where(x => x.StoreId == storeId && x.Jkszh == coach.Id && x.IsEffective == 1)
.Where(x => x.Yjsj.HasValue && x.Yjsj.Value >= startDate && x.Yjsj.Value <= endDateTime)
.SumAsync(x => (decimal?)(x.Jksyj ?? 0)) ?? 0m;
// 退卡业绩(从lq_hytk_jksyj表,使用jkszh字段匹配健康师ID)
var refundPerformance = await _db.Queryable<LqHytkJksyjEntity>()
.Where(x => x.StoreId == storeId && x.Jkszh == coach.Id && x.IsEffective == 1)
.Where(x => x.Tksj.HasValue && x.Tksj.Value.Date >= startDate.Date && x.Tksj.Value.Date <= endDate.Date)
.SumAsync(x => (decimal?)(x.Jksyj ?? 0)) ?? 0m;
// 总业绩
var totalPerformance = billingPerformance - refundPerformance;
// 项目数(从lq_xh_pxmx表,关联lq_xh_hyhk,再关联lq_xh_jksyj)
var projectCountSql = $@"
SELECT COALESCE(SUM(COALESCE(px.F_OriginalProjectNumber, px.F_ProjectNumber, 0)), 0) as ProjectCount
FROM lq_xh_pxmx px
INNER JOIN lq_xh_hyhk xh ON px.F_ConsumeInfoId = xh.F_Id
INNER JOIN lq_xh_jksyj jksyj ON jksyj.glkdbh = xh.F_Id
WHERE xh.Md = '{storeId}'
AND jksyj.jkszh = '{coach.Id}'
AND xh.F_IsEffective = 1
AND jksyj.F_IsEffective = 1
AND px.F_IsEffective = 1
AND xh.Hksj >= '{startDate:yyyy-MM-dd HH:mm:ss}'
AND xh.Hksj <= '{endDateTime:yyyy-MM-dd HH:mm:ss}'";
var projectCountResult = await _db.Ado.SqlQueryAsync<dynamic>(projectCountSql);
var projectCount = projectCountResult?.FirstOrDefault() != null
? Convert.ToDecimal(projectCountResult.FirstOrDefault().ProjectCount ?? 0)
: 0m;
detailList.Add(new BusinessUnitDashboardHealthCoachDetailListOutput
{
HealthCoachId = coach.Id,
HealthCoachName = coach.RealName ?? "",
StoreId = storeId,
StoreName = storeDict.ContainsKey(storeId) ? storeDict[storeId] : "",
BillingPerformance = billingPerformance,
ConsumePerformance = consumePerformance,
RefundPerformance = refundPerformance,
TotalPerformance = totalPerformance,
ProjectCount = projectCount
});
}
// 分页处理
var currentPage = input.currentPage > 0 ? input.currentPage : 1;
var pageSize = input.pageSize > 0 ? input.pageSize : 10;
var total = detailList.Count;
var pagedList = detailList.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
return new { total = total, list = pagedList };
}
catch (Exception ex)
{
_logger.LogError(ex, "查询事业部驾驶舱健康师明细列表失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
}
}
|