LqReimbursementApplicationService.cs
94.5 KB
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
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.LqReimbursementApplication;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys;
using NCC.Extend.Entitys.Dto.LqReimbursementApplication;
using NCC.Extend.Entitys.lq_reimbursement_application_node;
using NCC.Extend.Entitys.lq_reimbursement_application_node_user;
using NCC.Extend.Entitys.lq_reimbursement_approval_record;
using NCC.Extend.Entitys.lq_mdxx;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
namespace NCC.Extend.LqReimbursementApplication
{
/// <summary>
/// 报销申请表服务
/// </summary>
[ApiDescriptionSettings(Tag = "Extend", Name = "LqReimbursementApplication", Order = 200)]
[Route("api/Extend/[controller]")]
public class LqReimbursementApplicationService : ILqReimbursementApplicationService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository<LqReimbursementApplicationEntity> _lqReimbursementApplicationRepository;
private readonly SqlSugarScope _db;
private readonly IUserManager _userManager;
/// <summary>
/// 初始化一个<see cref="LqReimbursementApplicationService"/>类型的新实例
/// </summary>
public LqReimbursementApplicationService(
ISqlSugarRepository<LqReimbursementApplicationEntity> lqReimbursementApplicationRepository,
IUserManager userManager)
{
_lqReimbursementApplicationRepository = lqReimbursementApplicationRepository;
_db = _lqReimbursementApplicationRepository.Context;
_userManager = userManager;
}
/// <summary>
/// 获取报销申请表详情(包含表单和流程信息)
/// </summary>
/// <remarks>
/// 根据申请编号获取报销申请的详细信息,包括表单数据、节点配置、审批历史、购买记录等。
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqReimbursementApplication/{id}
/// ```
///
/// 参数说明:
/// - id: 申请编号(必填)
///
/// 返回说明:
/// - form: 表单基本信息,包含申请编号、申请人信息、门店信息、审批状态、完成时间等
/// - nodes: 节点配置列表,包含每个节点的审批人、审批记录等
/// - currentApprovers: 当前节点审批人列表
/// - currentNodeOrder: 当前节点顺序
/// - approvalStatus: 审批状态
/// - returnedReason: 退回原因(如果有)
/// - purchaseRecords: 关联的购买记录列表
/// - form.completionTime: 完成时间(最后一个审批人通过的时间),如果申请未完成则为null
/// </remarks>
/// <param name="id">申请编号</param>
/// <returns>报销申请详情</returns>
/// <response code="200">查询成功</response>
/// <response code="404">申请不存在</response>
/// <response code="500">服务器错误</response>
[HttpGet("{id}")]
public async Task<dynamic> GetInfo(string id)
{
var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var output = entity.Adapt<LqReimbursementApplicationInfoOutput>();
// 获取完成时间(优先使用实体类中的 CompletionTime,如果没有则查询审批记录)
if (entity.CompletionTime.HasValue)
{
output.completionTime = entity.CompletionTime;
}
else
{
// 查询最后一次审批通过的记录
var completionRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id && x.ApprovalResult == "通过")
.OrderBy(x => x.ApprovalTime, OrderByType.Desc)
.FirstAsync();
output.completionTime = completionRecord?.ApprovalTime;
}
// 获取节点配置
var nodes = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => x.ApplicationId == id)
.OrderBy(x => x.NodeOrder)
.ToListAsync();
// 获取每个节点的审批人
var nodeUsers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == id)
.OrderBy(x => x.NodeOrder)
.OrderBy(x => x.SortOrder)
.ToListAsync();
// 获取审批历史
var approvalRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id)
.OrderBy(x => x.NodeOrder)
.OrderBy(x => x.ApprovalTime)
.ToListAsync();
// 获取关联的购买记录
var purchaseRecords = await _db.Queryable<LqPurchaseRecordsEntity>()
.Where(x => x.ApplicationId == id)
.OrderBy(x => x.CreateTime)
.ToListAsync();
// 获取门店名称
string storeName = null;
if (!string.IsNullOrEmpty(entity.ApplicationStoreId))
{
var store = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Id == entity.ApplicationStoreId)
.Select(x => x.Dm)
.FirstAsync();
storeName = store ?? null;
}
output.applicationStoreName = storeName;
// 组装节点信息
var nodeList = nodes.Select(n => new
{
nodeId = n.Id,
nodeOrder = n.NodeOrder,
nodeName = n.NodeName,
approvalType = n.ApprovalType,
isRequired = n.IsRequired,
approvers = nodeUsers.Where(u => u.NodeId == n.Id).Select(u => new
{
userId = u.UserId,
userName = u.UserName,
sortOrder = u.SortOrder
}).ToList(),
approvalRecords = approvalRecords.Where(r => r.NodeId == n.Id).Select(r => new
{
approverName = r.ApproverName,
approvalResult = r.ApprovalResult,
approvalOpinion = r.ApprovalOpinion,
approvalTime = r.ApprovalTime
}).ToList()
}).ToList();
// 获取当前节点审批人
var currentApprovers = new List<object>();
if (entity.CurrentNodeOrder.HasValue && entity.CurrentNodeOrder > 0)
{
currentApprovers = nodeUsers
.Where(u => u.NodeOrder == entity.CurrentNodeOrder.Value)
.Select(u => new
{
userId = u.UserId,
userName = u.UserName
})
.Cast<object>()
.ToList();
}
// 组装购买记录数据
var purchaseRecordsList = purchaseRecords.Select(pr => new
{
id = pr.Id,
reimbursementCategoryId = pr.ReimbursementCategoryId,
reimbursementCategoryName = pr.ReimbursementCategoryName,
unitPrice = pr.UnitPrice,
quantity = pr.Quantity,
amount = pr.Amount,
memo = pr.Memo,
attachment = pr.Attachment,
purchaseTime = pr.PurchaseTime,
createTime = pr.CreateTime,
createUser = pr.CreateUser,
createUserStoreId = pr.CreateUserStoreId,
approveStatus = pr.ApproveStatus,
approveUser = pr.ApproveUser,
approveTime = pr.ApproveTime,
applicationId = pr.ApplicationId
}).ToList();
return new
{
form = output,
nodes = nodeList,
currentApprovers = currentApprovers,
currentNodeOrder = entity.CurrentNodeOrder,
approvalStatus = entity.ApprovalStatus ?? entity.ApproveStatus,
returnedReason = entity.ReturnedReason,
purchaseRecords = purchaseRecordsList
};
}
/// <summary>
/// 获取报销申请表列表
/// </summary>
/// <remarks>
/// 获取报销申请表分页列表,支持多种查询条件组合查询。
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqReimbursementApplication?currentPage=1&pageSize=20&approveStatus=已通过&completionTime=2025-01-01,2025-12-31
/// ```
///
/// 参数说明:
/// - currentPage: 当前页码(默认1)
/// - pageSize: 每页数量(默认20)
/// - id: 申请编号(可选,模糊查询)
/// - applicationUserId: 申请人编号(可选,模糊查询)
/// - applicationUserName: 申请人姓名(可选,模糊查询)
/// - applicationStoreId: 申请门店ID(可选,模糊查询)
/// - applicationTime: 申请时间范围(可选,格式:开始时间,结束时间)
/// - amount: 总金额(可选,模糊查询)
/// - approveUser: 审批人(可选,精确匹配)
/// - approveStatus: 审批结果(可选,模糊查询)
/// - approveTime: 审批时间范围(可选,格式:开始时间,结束时间)
/// - purchaseRecordsId: 关联购买编号(可选,模糊查询)
/// - completionTime: 完成时间范围(可选,格式:开始时间,结束时间)。完成时间指最后一个审批人通过的时间
///
/// 返回说明:
/// - 返回分页列表,包含报销申请详细信息
/// - 每条记录包含:申请编号、申请人信息、门店信息、审批状态、完成时间等
/// - completionTime: 完成时间(最后一个审批人通过的时间),如果申请未完成则为null
/// </remarks>
/// <param name="input">请求参数</param>
/// <returns>分页列表</returns>
/// <response code="200">查询成功</response>
/// <response code="400">输入参数错误</response>
/// <response code="500">服务器错误</response>
[HttpGet("")]
public async Task<dynamic> GetList([FromQuery] LqReimbursementApplicationListQueryInput input)
{
List<string> queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null;
DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null;
List<string> queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null;
DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null;
List<string> queryCompletionTime = input.completionTime != null ? input.completionTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startCompletionTime = queryCompletionTime != null ? Ext.GetDateTime(queryCompletionTime.First()) : null;
DateTime? endCompletionTime = queryCompletionTime != null ? Ext.GetDateTime(queryCompletionTime.Last()) : null;
var query = _db.Queryable<LqReimbursementApplicationEntity>()
.WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
.WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId))
.WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName))
.WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
.WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0))
.WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount))
.WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser))
.WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => (p.ApprovalStatus ?? p.ApproveStatus).Contains(input.approveStatus))
// .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0))
//.WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId));
// 处理排序(兼容前端传入的字段名)
if (string.IsNullOrEmpty(input.sidx))
{
query = query.OrderBy(x => x.ApplicationTime, OrderByType.Desc);
}
else
{
var sortType = input.sort?.ToLower() == "desc" ? OrderByType.Desc : OrderByType.Asc;
// 根据字段名映射到实体属性(兼容前端传入的字段名)
switch (input.sidx.ToLower())
{
case "id":
query = query.OrderBy(x => x.Id, sortType);
break;
case "applicationtime":
case "application_time":
query = query.OrderBy(x => x.ApplicationTime, sortType);
break;
case "amount":
query = query.OrderBy(x => x.Amount, sortType);
break;
case "applicationuserid":
case "application_user_id":
query = query.OrderBy(x => x.ApplicationUserId, sortType);
break;
case "applicationusername":
case "application_user_name":
query = query.OrderBy(x => x.ApplicationUserName, sortType);
break;
case "approvestatus":
case "approve_status":
query = query.OrderBy(x => x.ApprovalStatus ?? x.ApproveStatus, sortType);
break;
case "approvetime":
case "approve_time":
query = query.OrderBy(x => x.ApproveTime, sortType);
break;
default:
query = query.OrderBy(x => x.ApplicationTime, OrderByType.Desc);
break;
}
}
var total = await query.CountAsync();
var entities = await query.ToPageListAsync(input.currentPage, input.pageSize);
// 获取当前审批人信息
var applicationIds = entities.Select(x => x.Id).ToList();
var currentApprovers = new List<dynamic>();
if (applicationIds.Any())
{
var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => applicationIds.Contains(x.ApplicationId))
.InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
.Select((u, a) => new
{
applicationId = a.Id,
approverName = u.UserName
})
.ToListAsync();
currentApprovers = approverList.Cast<dynamic>().ToList();
}
var approverDict = currentApprovers
.GroupBy(x => (string)x.applicationId)
.ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));
// 如果提供了完成时间筛选,需要先查询完成时间,然后过滤
if (queryCompletionTime != null && applicationIds.Any())
{
var completionTimeRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => applicationIds.Contains(x.ApplicationId) && x.ApprovalResult == "通过")
.GroupBy(x => x.ApplicationId)
.Select(x => new
{
ApplicationId = x.ApplicationId,
MaxApprovalTime = SqlFunc.AggregateMax(x.ApprovalTime)
})
.ToListAsync();
var filteredApplicationIds = completionTimeRecords
.Where(x => x.MaxApprovalTime.HasValue &&
x.MaxApprovalTime.Value >= new DateTime(startCompletionTime.ToDate().Year, startCompletionTime.ToDate().Month, startCompletionTime.ToDate().Day, 0, 0, 0) &&
x.MaxApprovalTime.Value <= new DateTime(endCompletionTime.ToDate().Year, endCompletionTime.ToDate().Month, endCompletionTime.ToDate().Day, 23, 59, 59))
.Select(x => x.ApplicationId)
.ToList();
entities = entities.Where(x => filteredApplicationIds.Contains(x.Id)).ToList();
total = entities.Count;
applicationIds = entities.Select(x => x.Id).ToList();
}
// 获取门店名称
var storeIds = entities.Where(x => !string.IsNullOrEmpty(x.ApplicationStoreId)).Select(x => x.ApplicationStoreId).Distinct().ToList();
var storeDict = new Dictionary<string, string>();
if (storeIds.Any())
{
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
}
// 获取完成时间(优先使用实体类中的 CompletionTime,如果没有则查询审批记录)
var completionTimeDict = new Dictionary<string, DateTime?>();
if (applicationIds.Any())
{
// 先检查实体类中是否有 CompletionTime
var entitiesWithCompletionTime = entities.Where(x => x.CompletionTime.HasValue).ToList();
foreach (var entity in entitiesWithCompletionTime)
{
completionTimeDict[entity.Id] = entity.CompletionTime;
}
// 对于没有 CompletionTime 的实体,查询审批记录
var entitiesWithoutCompletionTime = entities.Where(x => !x.CompletionTime.HasValue).Select(x => x.Id).ToList();
if (entitiesWithoutCompletionTime.Any())
{
var completionRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => entitiesWithoutCompletionTime.Contains(x.ApplicationId) && x.ApprovalResult == "通过")
.GroupBy(x => x.ApplicationId)
.Select(x => new
{
ApplicationId = x.ApplicationId,
MaxApprovalTime = SqlFunc.AggregateMax(x.ApprovalTime)
})
.ToListAsync();
foreach (var record in completionRecords)
{
if (!completionTimeDict.ContainsKey(record.ApplicationId))
{
completionTimeDict[record.ApplicationId] = record.MaxApprovalTime;
}
}
}
}
// 组装返回数据
var result = entities.Select(item => new LqReimbursementApplicationListOutput
{
id = item.Id,
applicationUserId = item.ApplicationUserId,
applicationUserName = item.ApplicationUserName,
applicationStoreId = item.ApplicationStoreId,
applicationStoreName = !string.IsNullOrEmpty(item.ApplicationStoreId) && storeDict.ContainsKey(item.ApplicationStoreId)
? storeDict[item.ApplicationStoreId]
: null,
applicationTime = item.ApplicationTime,
amount = item.Amount,
approveUser = item.ApproveUser,
approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
approveTime = item.ApproveTime,
purchaseRecordsId = item.PurchaseRecordsId,
currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
currentNodeOrder = item.CurrentNodeOrder,
nodeCount = item.NodeCount,
completionTime = completionTimeDict.ContainsKey(item.Id) ? completionTimeDict[item.Id] : (item.CompletionTime ?? null)
}).ToList();
return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
new SqlSugarPagedList<LqReimbursementApplicationListOutput>
{
list = result,
pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
});
}
/// <summary>
/// 新建报销申请表
/// </summary>
/// <param name="input">参数</param>
/// <returns>返回创建的申请ID</returns>
[HttpPost("")]
public async Task<dynamic> Create([FromBody] LqReimbursementApplicationCrInput input)
{
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt<LqReimbursementApplicationEntity>();
entity.Id = YitIdHelper.NextId().ToString();
try
{
//开启事务
_db.BeginTran();
// 1. 验证节点配置
if (input.nodes == null || input.nodes.Count == 0)
{
throw new Exception("至少需要配置1个审批节点");
}
// 设置合理的上限,避免节点过多
if (input.nodes.Count > 20)
{
throw new Exception("节点数量不能超过20个");
}
// 验证节点顺序是否连续(1, 2, 3, ...)
var nodeOrders = input.nodes.Select(n => n.nodeOrder).OrderBy(x => x).ToList();
for (int i = 0; i < nodeOrders.Count; i++)
{
if (nodeOrders[i] != i + 1)
{
throw new Exception($"节点顺序必须连续,从1开始");
}
}
// 验证每个节点至少有一个审批人
foreach (var node in input.nodes)
{
if (node.approverIds == null || node.approverIds.Count == 0)
{
throw new Exception($"节点{node.nodeOrder}({node.nodeName})必须至少指定一个审批人");
}
}
// 2. 设置报销申请初始状态
entity.NodeCount = input.nodes.Count;
entity.CurrentNodeOrder = 0;
entity.ApprovalStatus = "待审批";
entity.ApplicationTime = DateTime.Now;
if (string.IsNullOrEmpty(entity.ApplicationUserId))
{
entity.ApplicationUserId = userInfo.userId;
}
if (string.IsNullOrEmpty(entity.ApplicationUserName))
{
entity.ApplicationUserName = userInfo.userName;
}
// 3. 保存报销申请表(不使用IgnoreColumns,确保新字段被保存)
var isOk = await _db.Insertable(entity).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
// 4. 创建节点配置
if (input.nodes != null && input.nodes.Count > 0)
{
foreach (var nodeConfig in input.nodes)
{
var node = new LqReimbursementApplicationNodeEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = entity.Id,
NodeOrder = nodeConfig.nodeOrder,
NodeName = nodeConfig.nodeName,
ApprovalType = nodeConfig.approvalType ?? "会签",
IsRequired = 1,
CreateTime = DateTime.Now
};
var nodeResult = await _db.Insertable(node).ExecuteCommandAsync();
if (nodeResult <= 0)
{
throw new Exception($"创建节点{nodeConfig.nodeOrder}失败");
}
// 5. 创建节点审批人
if (nodeConfig.approverIds != null && nodeConfig.approverIds.Count > 0)
{
for (int i = 0; i < nodeConfig.approverIds.Count; i++)
{
var nodeUser = new LqReimbursementApplicationNodeUserEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = entity.Id,
NodeId = node.Id,
NodeOrder = nodeConfig.nodeOrder,
UserId = nodeConfig.approverIds[i],
UserName = nodeConfig.approverNames != null && i < nodeConfig.approverNames.Count
? nodeConfig.approverNames[i]
: null,
SortOrder = i + 1,
CreateTime = DateTime.Now
};
var userResult = await _db.Insertable(nodeUser).ExecuteCommandAsync();
if (userResult <= 0)
{
throw new Exception($"创建节点{nodeConfig.nodeOrder}的审批人{nodeConfig.approverIds[i]}失败");
}
}
}
}
}
// 6. 更新购买记录的审批单编号和审批状态为"待审批"
if (input.selectedPurchaseRecordIds != null && input.selectedPurchaseRecordIds.Count > 0)
{
// 先更新ApplicationId
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => it.ApplicationId == entity.Id)
.Where(it => input.selectedPurchaseRecordIds.Contains(it.Id))
.ExecuteCommandAsync();
// 再更新ApproveStatus(分开更新确保都能执行)
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => it.ApproveStatus == "待审批")
.Where(it => input.selectedPurchaseRecordIds.Contains(it.Id))
.ExecuteCommandAsync();
}
//关闭事务
_db.CommitTran();
// 返回创建的申请ID
return new { id = entity.Id };
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw;
}
}
/// <summary>
/// 获取报销申请表无分页列表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[NonAction]
public async Task<dynamic> GetNoPagingList([FromQuery] LqReimbursementApplicationListQueryInput input)
{
var sidx = input.sidx == null ? "id" : input.sidx;
List<string> queryApplicationTime = input.applicationTime != null ? input.applicationTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.First()) : null;
DateTime? endApplicationTime = queryApplicationTime != null ? Ext.GetDateTime(queryApplicationTime.Last()) : null;
List<string> queryApproveTime = input.approveTime != null ? input.approveTime.Split(',').ToObeject<List<string>>() : null;
DateTime? startApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.First()) : null;
DateTime? endApproveTime = queryApproveTime != null ? Ext.GetDateTime(queryApproveTime.Last()) : null;
var data = await _db.Queryable<LqReimbursementApplicationEntity>()
.WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
.WhereIF(!string.IsNullOrEmpty(input.applicationUserId), p => p.ApplicationUserId.Contains(input.applicationUserId))
.WhereIF(!string.IsNullOrEmpty(input.applicationUserName), p => p.ApplicationUserName.Contains(input.applicationUserName))
.WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
.WhereIF(queryApplicationTime != null, p => p.ApplicationTime >= new DateTime(startApplicationTime.ToDate().Year, startApplicationTime.ToDate().Month, startApplicationTime.ToDate().Day, 0, 0, 0))
.WhereIF(queryApplicationTime != null, p => p.ApplicationTime <= new DateTime(endApplicationTime.ToDate().Year, endApplicationTime.ToDate().Month, endApplicationTime.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.amount), p => p.Amount.Contains(input.amount))
.WhereIF(!string.IsNullOrEmpty(input.approveUser), p => p.ApproveUser.Equals(input.approveUser))
.WhereIF(!string.IsNullOrEmpty(input.approveStatus), p => p.ApproveStatus.Contains(input.approveStatus))
// .WhereIF(queryApproveTime != null, p => p.ApproveTime >= new DateTime(startApproveTime.ToDate().Year, startApproveTime.ToDate().Month, startApproveTime.ToDate().Day, 0, 0, 0))
// .WhereIF(queryApproveTime != null, p => p.ApproveTime <= new DateTime(endApproveTime.ToDate().Year, endApproveTime.ToDate().Month, endApproveTime.ToDate().Day, 23, 59, 59))
.WhereIF(!string.IsNullOrEmpty(input.purchaseRecordsId), p => p.PurchaseRecordsId.Contains(input.purchaseRecordsId))
.Select(it => new LqReimbursementApplicationListOutput
{
id = it.Id,
applicationUserId = it.ApplicationUserId,
applicationUserName = it.ApplicationUserName,
applicationStoreId = it.ApplicationStoreId,
applicationTime = it.ApplicationTime,
amount = it.Amount,
approveUser = it.ApproveUser,
approveStatus = it.ApproveStatus,
approveTime = it.ApproveTime,
purchaseRecordsId = it.PurchaseRecordsId,
}).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync();
return data;
}
/// <summary>
/// 导出报销申请表
/// </summary>
/// <param name="input">请求参数</param>
/// <returns></returns>
[HttpGet("Actions/Export")]
public async Task<dynamic> Export([FromQuery] LqReimbursementApplicationListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = new List<LqReimbursementApplicationListOutput>();
if (input.dataType == 0)
{
var data = Clay.Object(await this.GetList(input));
exportData = data.Solidify<PageResult<LqReimbursementApplicationListOutput>>().list;
}
else
{
exportData = await this.GetNoPagingList(input);
}
List<ParamsModel> paramList = "[{\"value\":\"申请编号\",\"field\":\"id\"},{\"value\":\"申请人编号\",\"field\":\"applicationUserId\"},{\"value\":\"申请人姓名\",\"field\":\"applicationUserName\"},{\"value\":\"申请门店\",\"field\":\"applicationStoreId\"},{\"value\":\"申请时间\",\"field\":\"applicationTime\"},{\"value\":\"总金额\",\"field\":\"amount\"},{\"value\":\"审批人\",\"field\":\"approveUser\"},{\"value\":\"审批结果\",\"field\":\"approveStatus\"},{\"value\":\"审批时间\",\"field\":\"approveTime\"},{\"value\":\"关联购买编号\",\"field\":\"purchaseRecordsId\"},]".ToList<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "报销申请表.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
List<string> selectKeyList = input.selectKey.Split(',').ToList();
foreach (var item in selectKeyList)
{
var isExist = paramList.Find(p => p.field == item);
if (isExist != null)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
}
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<LqReimbursementApplicationListOutput>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
/// <summary>
/// 批量删除报销申请表
/// </summary>
/// <param name="ids">主键数组</param>
/// <returns></returns>
[HttpPost("batchRemove")]
public async Task BatchRemove([FromBody] List<string> ids)
{
var entitys = await _db.Queryable<LqReimbursementApplicationEntity>().In(it => it.Id, ids).ToListAsync();
if (entitys.Count > 0)
{
try
{
//开启事务
_db.BeginTran();
//批量删除报销申请表
await _db.Deleteable<LqReimbursementApplicationEntity>().In(d => d.Id, ids).ExecuteCommandAsync();
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw NCCException.Oh(ErrorCode.COM1002);
}
}
}
/// <summary>
/// 更新报销申请表
/// </summary>
/// <param name="id">主键</param>
/// <param name="input">参数</param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] LqReimbursementApplicationUpInput input)
{
try
{
//开启事务
_db.BeginTran();
// 获取原有的关联购买记录ID
var oldEntity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
_ = oldEntity ?? throw NCCException.Oh(ErrorCode.COM1005);
// 检查是否可以修改:只有"待审批"(CurrentNodeOrder=0)或"已退回"状态的申请才能修改
if (oldEntity.CurrentNodeOrder != null && oldEntity.CurrentNodeOrder != 0 && oldEntity.ApprovalStatus != "已退回")
{
throw new Exception($"该申请当前状态为{oldEntity.ApprovalStatus},无法修改。只有待审批或已退回状态的申请才能修改。");
}
var oldIds = new List<string>();
if (oldEntity != null && !string.IsNullOrEmpty(oldEntity.PurchaseRecordsId))
{
// 获取原有购买记录ID列表
oldIds = oldEntity.PurchaseRecordsId.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToList();
}
// 获取新的购买记录ID列表
var newIds = input.selectedPurchaseRecordIds ?? new List<string>();
// 确保 purchaseRecordsId 字段包含所有选中的记录ID(逗号分隔)
if (newIds.Count > 0)
{
input.purchaseRecordsId = string.Join(",", newIds);
}
else
{
input.purchaseRecordsId = null;
}
// 找出需要移除关联的记录(在旧列表中但不在新列表中)
var idsToRemove = oldIds.Where(x => !newIds.Contains(x)).ToList();
if (idsToRemove.Count > 0)
{
// 清除这些购买记录的审批单编号和审批状态
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => new LqPurchaseRecordsEntity
{
ApplicationId = null,
ApproveStatus = "未审批"
})
.Where(it => idsToRemove.Contains(it.Id))
.ExecuteCommandAsync();
}
// 更新报销申请表(确保 purchaseRecordsId 字段被正确更新)
var entity = input.Adapt<LqReimbursementApplicationEntity>();
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
// 更新所有选中的购买记录的审批单编号和审批状态为"待审批"
// 包括新追加的记录和已存在的记录(确保状态正确)
if (newIds.Count > 0)
{
// 先更新ApplicationId
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => it.ApplicationId == id)
.Where(it => newIds.Contains(it.Id))
.ExecuteCommandAsync();
// 再更新ApproveStatus(分开更新确保都能执行)
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => it.ApproveStatus == "待审批")
.Where(it => newIds.Contains(it.Id))
.ExecuteCommandAsync();
}
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw;
}
}
/// <summary>
/// 删除报销申请表
/// </summary>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable<LqReimbursementApplicationEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
}
/// <summary>
/// 提交审批(进入第一个节点)
/// </summary>
/// <param name="id">申请编号</param>
/// <returns></returns>
[HttpPost("{id}/Actions/SubmitApproval")]
public async Task SubmitApproval(string id)
{
var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
// 允许"待审批"和"已退回"状态的申请提交审批
if (entity.CurrentNodeOrder != 0 && entity.ApprovalStatus != "已退回")
{
throw new Exception("该申请已经提交审批,不能重复提交");
}
if (entity.NodeCount == null || entity.NodeCount == 0)
{
throw new Exception("节点配置异常,无法提交审批");
}
try
{
_db.BeginTran();
// 获取第一个节点
var firstNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == 1)
.FirstAsync();
if (firstNode == null)
{
throw new Exception("未找到第一个审批节点配置");
}
// 更新报销申请状态
entity.CurrentNodeOrder = 1;
entity.CurrentNodeId = firstNode.Id;
entity.ApprovalStatus = "审批中";
// 清除退回原因(重新提交审批)
entity.ReturnedReason = null;
entity.ReturnedNodeOrder = null;
await _db.Updateable(entity).ExecuteCommandAsync();
// 获取第一个节点的所有审批人
var firstNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == 1)
.ToListAsync();
// 获取第一个节点已有的审批记录
var existingRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == 1)
.ToListAsync();
// 为第一个节点的每个审批人创建待审批记录(如果不存在)
foreach (var approver in firstNodeApprovers)
{
// 检查是否已存在该审批人的"待审批"记录
var existingPendingRecord = existingRecords.FirstOrDefault(x =>
x.ApproverId == approver.UserId && x.ApprovalResult == "待审批");
if (existingPendingRecord == null)
{
// 如果不存在"待审批"记录,创建新的待审批记录
// 注意:即使之前有"退回"记录,也创建新的"待审批"记录,保留历史记录
var record = new LqReimbursementApprovalRecordEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = id,
NodeId = firstNode.Id,
NodeOrder = 1,
ApproverId = approver.UserId,
ApproverName = approver.UserName,
ApprovalResult = "待审批",
IsCurrentNode = 1,
ApprovalTime = null
};
await _db.Insertable(record).ExecuteCommandAsync();
}
else
{
// 如果已存在"待审批"记录,只更新IsCurrentNode状态
existingPendingRecord.IsCurrentNode = 1;
await _db.Updateable(existingPendingRecord).ExecuteCommandAsync();
}
}
// 更新所有审批记录的IsCurrentNode状态(将第一个节点的"待审批"记录设为1,其他设为0)
// 注意:保留所有历史记录(包括"退回"记录),只更新IsCurrentNode状态
await _db.Updateable<LqReimbursementApprovalRecordEntity>()
.SetColumns(it => it.IsCurrentNode == 0)
.Where(it => it.ApplicationId == id && (it.NodeOrder != 1 || it.ApprovalResult != "待审批"))
.ExecuteCommandAsync();
_db.CommitTran();
}
catch (Exception)
{
_db.RollbackTran();
throw;
}
}
/// <summary>
/// 审批操作(通过/不通过/退回)
/// </summary>
/// <param name="id">申请编号</param>
/// <param name="result">审批结果:通过/不通过/退回</param>
/// <param name="opinion">审批意见</param>
/// <returns></returns>
[HttpPost("{id}/Actions/Approve")]
public async Task Approve(string id, [FromQuery] string result, [FromQuery] string opinion = "")
{
var userInfo = await _userManager.GetUserInfo();
var entity = await _db.Queryable<LqReimbursementApplicationEntity>().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
if (entity.CurrentNodeOrder == null || entity.CurrentNodeOrder == 0)
{
throw new Exception("该申请尚未提交审批");
}
if (entity.ApprovalStatus != "审批中")
{
throw new Exception($"该申请当前状态为{entity.ApprovalStatus},无法进行审批操作");
}
// 验证当前用户是否有审批权限(管理员可以审批所有节点)
var isAdmin = userInfo.isAdministrator;
if (!isAdmin)
{
var hasPermission = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.UserId == userInfo.userId)
.AnyAsync();
if (!hasPermission)
{
throw new Exception("您没有当前节点的审批权限");
}
}
// 检查是否已经审批过(排除待审批状态)
// 注意:如果存在"待审批"记录,说明可以审批
// 如果不存在"待审批"记录,但存在其他状态的记录(通过、不通过),说明已经审批过
// 但是,如果之前有"退回"记录,重新提交审批后会创建新的"待审批"记录,所以这里优先检查"待审批"状态
var existingPendingApprovalRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.ApproverId == userInfo.userId
&& x.ApprovalResult == "待审批")
.FirstAsync();
// 如果存在"待审批"记录,说明可以审批,不需要抛出异常
// 如果不存在"待审批"记录,需要检查是否有"通过"或"不通过"的记录(不包括"退回",因为退回后可以重新审批)
// 注意:如果状态已经是"已通过",说明整个流程已完成,不允许再次审批
if (existingPendingApprovalRecord == null)
{
// 如果申请状态已经是"已通过",不允许再次审批
if (entity.ApprovalStatus == "已通过")
{
throw new Exception("该申请已经审批通过,无法再次审批");
}
// 检查是否有"通过"或"不通过"的记录(不包括"退回")
var completedRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.ApproverId == userInfo.userId
&& (x.ApprovalResult == "通过" || x.ApprovalResult == "不通过"))
.FirstAsync();
if (completedRecord != null)
{
// 如果申请状态还是"审批中",说明还有其他审批人未审批,当前用户已经审批过,不允许重复审批
throw new Exception("您已经审批过该节点");
}
}
try
{
_db.BeginTran();
// 获取当前节点信息
var currentNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
.FirstAsync();
if (currentNode == null)
{
throw new Exception("未找到当前节点配置");
}
// 查找现有的审批记录(优先查找"待审批"记录)
var existingRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.ApproverId == userInfo.userId
&& x.ApprovalResult == "待审批")
.FirstAsync();
// 如果不存在"待审批"记录,再查找其他记录
if (existingRecord == null)
{
existingRecord = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.ApproverId == userInfo.userId)
.FirstAsync();
}
if (existingRecord != null)
{
// 如果审批结果是"待审批",允许更新
// 如果已经有明确的审批结果(通过/不通过),则不允许重复审批
// 注意:不包括"退回",因为退回后可以重新审批
if (!string.IsNullOrEmpty(existingRecord.ApprovalResult)
&& existingRecord.ApprovalResult != "待审批"
&& existingRecord.ApprovalResult != ""
&& existingRecord.ApprovalResult != "退回")
{
// 已经有明确的审批结果(通过/不通过),不允许重复审批
throw new Exception("您已经审批过该节点");
}
// 更新现有记录(包括空字符串、"待审批"、"退回"的情况)
// 注意:只更新审批结果和意见,不更新审批人信息(ApproverId和ApproverName在创建时已确定)
existingRecord.ApprovalResult = result;
existingRecord.ApprovalOpinion = opinion;
existingRecord.ApprovalTime = DateTime.Now;
existingRecord.IsCurrentNode = 1;
await _db.Updateable(existingRecord).ExecuteCommandAsync();
}
else
{
// 创建新记录(如果不存在)
var approvalRecord = new LqReimbursementApprovalRecordEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = id,
NodeId = currentNode.Id,
NodeOrder = entity.CurrentNodeOrder.Value,
ApproverId = userInfo.userId,
ApproverName = userInfo.userName,
ApprovalResult = result,
ApprovalOpinion = opinion,
ApprovalTime = DateTime.Now,
IsCurrentNode = 1
};
await _db.Insertable(approvalRecord).ExecuteCommandAsync();
}
// 根据审批结果处理
if (result == "不通过")
{
// 不通过:审批结束
entity.ApprovalStatus = "未通过";
await _db.Updateable(entity).ExecuteCommandAsync();
// 更新所有购买记录状态为"未通过"(通过ApplicationId关联更新)
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => new LqPurchaseRecordsEntity
{
ApproveStatus = "未通过",
ApproveTime = DateTime.Now,
ApproveUser = userInfo.userId
})
.Where(it => it.ApplicationId == id)
.ExecuteCommandAsync();
}
else if (result == "退回")
{
// 退回:退回到上一节点
// 先更新当前节点的退回记录的IsCurrentNode状态(设为0,因为不再是当前节点)
var currentNodeOrder = entity.CurrentNodeOrder.Value;
await _db.Updateable<LqReimbursementApprovalRecordEntity>()
.SetColumns(it => it.IsCurrentNode == 0)
.Where(x => x.ApplicationId == id && x.NodeOrder == currentNodeOrder)
.ExecuteCommandAsync();
if (entity.CurrentNodeOrder == 1)
{
// 退回到申请人
entity.CurrentNodeOrder = 0;
entity.ApprovalStatus = "已退回";
entity.ReturnedNodeOrder = 0;
entity.ReturnedReason = opinion;
entity.CurrentNodeId = null;
// 注意:不退回到发起人时,不删除审批记录,保留所有历史记录(包括退回记录)
}
else
{
// 退回到上一节点
entity.CurrentNodeOrder -= 1;
entity.ReturnedNodeOrder = entity.CurrentNodeOrder;
entity.ReturnedReason = opinion;
// 获取上一节点信息
var prevNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
.FirstAsync();
if (prevNode != null)
{
entity.CurrentNodeId = prevNode.Id;
}
// 获取上一节点已有的审批记录
var prevNodeExistingRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
.ToListAsync();
// 获取上一节点的所有审批人
var prevNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
.ToListAsync();
// 为上一节点的每个审批人创建待审批记录(如果不存在)
foreach (var approver in prevNodeApprovers)
{
// 检查是否已存在该审批人的"待审批"记录
var prevNodeExistingPendingRecord = prevNodeExistingRecords.FirstOrDefault(x =>
x.ApproverId == approver.UserId && x.ApprovalResult == "待审批");
if (prevNodeExistingPendingRecord == null)
{
// 如果不存在"待审批"记录,创建新的待审批记录
// 注意:即使之前有"退回"或其他记录,也创建新的"待审批"记录,保留历史记录
var record = new LqReimbursementApprovalRecordEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = id,
NodeId = prevNode.Id,
NodeOrder = entity.CurrentNodeOrder.Value,
ApproverId = approver.UserId,
ApproverName = approver.UserName,
ApprovalResult = "待审批",
IsCurrentNode = 1,
ApprovalTime = null
};
await _db.Insertable(record).ExecuteCommandAsync();
}
else
{
// 如果已存在"待审批"记录,只更新IsCurrentNode状态
prevNodeExistingPendingRecord.IsCurrentNode = 1;
await _db.Updateable(prevNodeExistingPendingRecord).ExecuteCommandAsync();
}
}
}
await _db.Updateable(entity).ExecuteCommandAsync();
}
else if (result == "通过")
{
// 通过:判断是否需要进入下一个节点
bool shouldMoveToNext = false;
if (currentNode.ApprovalType == "或签")
{
// 或签:任意一个审批人通过,立即进入下一个节点
shouldMoveToNext = true;
}
else // 会签
{
// 会签:检查是否所有审批人都已通过
var approvers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == id && x.NodeOrder == entity.CurrentNodeOrder)
.Select(x => x.UserId)
.ToListAsync();
// 查询所有"通过"的审批记录,包括当前用户刚审批的记录
// 注意:由于在事务中,需要确保查询包含当前刚更新的记录
var approvedUsers = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id
&& x.NodeOrder == entity.CurrentNodeOrder
&& x.ApprovalResult == "通过")
.Select(x => x.ApproverId)
.Distinct()
.ToListAsync();
// 如果当前用户刚审批通过,但查询结果中还没有包含,手动添加
if (result == "通过" && !approvedUsers.Contains(userInfo.userId))
{
approvedUsers.Add(userInfo.userId);
}
if (approvers.Count == approvedUsers.Count && approvers.Count > 0)
{
// 所有人都已通过
shouldMoveToNext = true;
}
// 特殊情况:如果只有一个审批人,且当前审批人就是该审批人,且审批结果是"通过",则直接进入下一节点
else if (approvers.Count == 1 && approvers.Contains(userInfo.userId) && result == "通过")
{
shouldMoveToNext = true;
}
}
if (shouldMoveToNext)
{
// 进入下一个节点或完成审批
await MoveToNextNode(id, userInfo.userId);
}
}
_db.CommitTran();
}
catch (Exception)
{
_db.RollbackTran();
throw;
}
}
/// <summary>
/// 进入下一个节点
/// </summary>
private async Task MoveToNextNode(string applicationId, string approveUserId)
{
var entity = await _db.Queryable<LqReimbursementApplicationEntity>()
.FirstAsync(x => x.Id == applicationId);
// 判断是否是最后一个节点
if (entity.CurrentNodeOrder >= entity.NodeCount)
{
// 审批完成
entity.CurrentNodeOrder = entity.NodeCount + 1;
entity.ApprovalStatus = "已通过";
entity.CurrentNodeId = null;
entity.CompletionTime = DateTime.Now; // 设置完成时间
await _db.Updateable(entity).ExecuteCommandAsync();
// 更新所有购买记录状态为"已审批"
// 通过ApplicationId关联更新,因为PurchaseRecordsId可能为空
await _db.Updateable<LqPurchaseRecordsEntity>()
.SetColumns(it => new LqPurchaseRecordsEntity
{
ApproveStatus = "已审批",
ApproveTime = DateTime.Now,
ApproveUser = approveUserId
})
.Where(it => it.ApplicationId == applicationId)
.ExecuteCommandAsync();
}
else
{
// 进入下一个节点
entity.CurrentNodeOrder += 1;
// 获取下一个节点信息
var nextNode = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder)
.FirstAsync();
if (nextNode == null)
{
throw new Exception($"未找到节点{entity.CurrentNodeOrder}的配置");
}
entity.CurrentNodeId = nextNode.Id;
entity.ApprovalStatus = "审批中";
await _db.Updateable(entity).ExecuteCommandAsync();
// 清除之前的当前节点标记
await _db.Updateable<LqReimbursementApprovalRecordEntity>()
.SetColumns(it => new LqReimbursementApprovalRecordEntity { IsCurrentNode = 0 })
.Where(it => it.ApplicationId == applicationId)
.ExecuteCommandAsync();
// 为下一个节点的每个审批人创建待审批记录
var nextNodeApprovers = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.ApplicationId == applicationId && x.NodeOrder == entity.CurrentNodeOrder)
.ToListAsync();
foreach (var approver in nextNodeApprovers)
{
var record = new LqReimbursementApprovalRecordEntity
{
Id = YitIdHelper.NextId().ToString(),
ApplicationId = applicationId,
NodeId = nextNode.Id,
NodeOrder = entity.CurrentNodeOrder.Value,
ApproverId = approver.UserId,
ApproverName = approver.UserName,
ApprovalResult = "待审批",
IsCurrentNode = 1,
ApprovalTime = null
};
await _db.Insertable(record).ExecuteCommandAsync();
}
}
}
/// <summary>
/// 获取所有待办列表(管理员用,所有待审批的申请)
/// </summary>
/// <remarks>
/// 管理员可以查看所有状态为"审批中"的报销申请列表。
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqReimbursementApplication/Actions/AllPendingApproval?currentPage=1&pageSize=20
/// ```
///
/// 参数说明:
/// - currentPage: 当前页码(默认1)
/// - pageSize: 每页数量(默认20)
/// - applicationStoreId: 申请门店ID(可选)
/// - 其他查询参数与 GetList 接口相同
///
/// 返回说明:
/// - 返回分页列表,只包含状态为"审批中"的申请
/// - 每条记录包含:申请编号、申请人信息、门店信息、审批状态、完成时间等
/// - completionTime: 完成时间(最后一个审批人通过的时间),待审批的申请该字段为null
/// </remarks>
/// <param name="input">查询参数</param>
/// <returns>分页列表</returns>
/// <response code="200">查询成功</response>
/// <response code="400">输入参数错误</response>
/// <response code="500">服务器错误</response>
[HttpGet("Actions/AllPendingApproval")]
public async Task<dynamic> GetAllPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input)
{
// 管理员可以查看所有待审批的申请
var query = _db.Queryable<LqReimbursementApplicationEntity>()
.Where(x => x.ApprovalStatus == "审批中")
.WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId));
// 处理排序
if (string.IsNullOrEmpty(input.sidx))
{
query = query.OrderBy(x => x.ApplicationTime, OrderByType.Desc);
}
else
{
var sortType = input.sort?.ToLower() == "desc" ? OrderByType.Desc : OrderByType.Asc;
// 根据字段名映射到实体属性
switch (input.sidx.ToLower())
{
case "id":
query = query.OrderBy(x => x.Id, sortType);
break;
case "applicationtime":
query = query.OrderBy(x => x.ApplicationTime, sortType);
break;
case "amount":
query = query.OrderBy(x => x.Amount, sortType);
break;
default:
query = query.OrderBy(x => x.ApplicationTime, OrderByType.Desc);
break;
}
}
var total = await query.CountAsync();
var entities = await query.ToPageListAsync(input.currentPage, input.pageSize);
// 获取当前审批人信息
var applicationIds = entities.Select(x => x.Id).ToList();
var currentApprovers = new List<dynamic>();
if (applicationIds.Any())
{
var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => applicationIds.Contains(x.ApplicationId))
.InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
.Select((u, a) => new
{
applicationId = a.Id,
approverName = u.UserName
})
.ToListAsync();
currentApprovers = approverList.Cast<dynamic>().ToList();
}
var approverDict = currentApprovers
.GroupBy(x => (string)x.applicationId)
.ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));
// 获取门店名称
var storeIds = entities.Where(x => !string.IsNullOrEmpty(x.ApplicationStoreId)).Select(x => x.ApplicationStoreId).Distinct().ToList();
var storeDict = new Dictionary<string, string>();
if (storeIds.Any())
{
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
}
// 获取完成时间(优先使用实体类中的 CompletionTime,如果没有则查询审批记录)
var completionTimeDict = new Dictionary<string, DateTime?>();
if (applicationIds.Any())
{
// 先检查实体类中是否有 CompletionTime
var entitiesWithCompletionTime = entities.Where(x => x.CompletionTime.HasValue).ToList();
foreach (var entity in entitiesWithCompletionTime)
{
completionTimeDict[entity.Id] = entity.CompletionTime;
}
// 对于没有 CompletionTime 的实体,查询审批记录
var entitiesWithoutCompletionTime = entities.Where(x => !x.CompletionTime.HasValue).Select(x => x.Id).ToList();
if (entitiesWithoutCompletionTime.Any())
{
var completionRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => entitiesWithoutCompletionTime.Contains(x.ApplicationId) && x.ApprovalResult == "通过")
.GroupBy(x => x.ApplicationId)
.Select(x => new
{
ApplicationId = x.ApplicationId,
MaxApprovalTime = SqlFunc.AggregateMax(x.ApprovalTime)
})
.ToListAsync();
foreach (var record in completionRecords)
{
if (!completionTimeDict.ContainsKey(record.ApplicationId))
{
completionTimeDict[record.ApplicationId] = record.MaxApprovalTime;
}
}
}
}
// 组装返回数据
var result = entities.Select(item => new LqReimbursementApplicationListOutput
{
id = item.Id,
applicationUserId = item.ApplicationUserId,
applicationUserName = item.ApplicationUserName,
applicationStoreId = item.ApplicationStoreId,
applicationStoreName = !string.IsNullOrEmpty(item.ApplicationStoreId) && storeDict.ContainsKey(item.ApplicationStoreId)
? storeDict[item.ApplicationStoreId]
: null,
applicationTime = item.ApplicationTime,
amount = item.Amount,
approveUser = item.ApproveUser,
approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
approveTime = item.ApproveTime,
purchaseRecordsId = item.PurchaseRecordsId,
currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
currentNodeOrder = item.CurrentNodeOrder,
nodeCount = item.NodeCount,
completionTime = completionTimeDict.ContainsKey(item.Id) ? completionTimeDict[item.Id] : (item.CompletionTime ?? null)
}).ToList();
return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
new SqlSugarPagedList<LqReimbursementApplicationListOutput>
{
list = result,
pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
});
}
/// <summary>
/// 获取待审批列表(当前用户作为审批人的申请)
/// </summary>
/// <param name="input">查询参数</param>
/// <returns></returns>
[HttpGet("Actions/PendingApproval")]
public async Task<dynamic> GetPendingApprovalList([FromQuery] LqReimbursementApplicationListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
// 查询当前用户作为审批人的节点
var userNodeOrders = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => x.UserId == userInfo.userId)
.Select(x => new { x.ApplicationId, x.NodeOrder })
.ToListAsync();
if (!userNodeOrders.Any())
{
return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
new SqlSugarPagedList<LqReimbursementApplicationListOutput>
{
list = new List<LqReimbursementApplicationListOutput>(),
pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = 0 }
});
}
// 获取用户有权限的申请ID和节点顺序
var userApplications = userNodeOrders
.GroupBy(x => x.ApplicationId)
.ToDictionary(g => g.Key, g => g.Select(x => x.NodeOrder).ToList());
var applicationIds = userApplications.Keys.ToList();
// 先查询所有符合条件的申请(状态为"审批中"且在用户有权限的申请列表中)
var allApplications = await _db.Queryable<LqReimbursementApplicationEntity>()
.Where(x => applicationIds.Contains(x.Id) && x.ApprovalStatus == "审批中")
.WhereIF(!string.IsNullOrEmpty(input.applicationStoreId), p => p.ApplicationStoreId.Contains(input.applicationStoreId))
.ToListAsync();
// 在内存中过滤:当前节点必须是用户有权限的节点
var filteredApplications = allApplications
.Where(x => userApplications.ContainsKey(x.Id)
&& userApplications[x.Id].Contains(x.CurrentNodeOrder ?? 0))
.ToList();
// 获取过滤后的申请ID列表
var filteredApplicationIds = filteredApplications.Select(x => x.Id).ToList();
// 如果没有符合条件的申请,直接返回空列表
if (!filteredApplicationIds.Any())
{
return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
new SqlSugarPagedList<LqReimbursementApplicationListOutput>
{
list = new List<LqReimbursementApplicationListOutput>(),
pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = 0 }
});
}
// 对过滤后的申请进行排序
var sortType = input.sort?.ToLower() == "desc" ? OrderByType.Desc : OrderByType.Asc;
IOrderedEnumerable<LqReimbursementApplicationEntity> orderedApplications;
if (string.IsNullOrEmpty(input.sidx))
{
orderedApplications = filteredApplications.OrderByDescending(x => x.ApplicationTime);
}
else
{
switch (input.sidx.ToLower())
{
case "id":
orderedApplications = sortType == OrderByType.Desc
? filteredApplications.OrderByDescending(x => x.Id)
: filteredApplications.OrderBy(x => x.Id);
break;
case "applicationtime":
orderedApplications = sortType == OrderByType.Desc
? filteredApplications.OrderByDescending(x => x.ApplicationTime)
: filteredApplications.OrderBy(x => x.ApplicationTime);
break;
case "amount":
orderedApplications = sortType == OrderByType.Desc
? filteredApplications.OrderByDescending(x => x.Amount)
: filteredApplications.OrderBy(x => x.Amount);
break;
default:
orderedApplications = filteredApplications.OrderByDescending(x => x.ApplicationTime);
break;
}
}
// 手动分页
var total = filteredApplications.Count;
var entities = orderedApplications
.Skip((input.currentPage - 1) * input.pageSize)
.Take(input.pageSize)
.ToList();
// 获取当前审批人信息
var resultApplicationIds = entities.Select(x => x.Id).ToList();
var currentApprovers = new List<dynamic>();
if (resultApplicationIds.Any())
{
var approverList = await _db.Queryable<LqReimbursementApplicationNodeUserEntity>()
.Where(x => resultApplicationIds.Contains(x.ApplicationId))
.InnerJoin<LqReimbursementApplicationEntity>((u, a) => u.ApplicationId == a.Id && u.NodeOrder == a.CurrentNodeOrder)
.Select((u, a) => new
{
applicationId = a.Id,
approverName = u.UserName
})
.ToListAsync();
currentApprovers = approverList.Cast<dynamic>().ToList();
}
var approverDict = currentApprovers
.GroupBy(x => (string)x.applicationId)
.ToDictionary(g => g.Key, g => string.Join(", ", g.Select(x => (string)x.approverName)));
// 获取门店名称
var storeIds = entities.Where(x => !string.IsNullOrEmpty(x.ApplicationStoreId)).Select(x => x.ApplicationStoreId).Distinct().ToList();
var storeDict = new Dictionary<string, string>();
if (storeIds.Any())
{
var stores = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
storeDict = stores.ToDictionary(x => x.Id, x => x.Dm ?? "");
}
// 获取完成时间(优先使用实体类中的 CompletionTime,如果没有则查询审批记录)
var completionTimeDict3 = new Dictionary<string, DateTime?>();
if (resultApplicationIds.Any())
{
// 先检查实体类中是否有 CompletionTime
var entitiesWithCompletionTime3 = entities.Where(x => x.CompletionTime.HasValue).ToList();
foreach (var entity in entitiesWithCompletionTime3)
{
completionTimeDict3[entity.Id] = entity.CompletionTime;
}
// 对于没有 CompletionTime 的实体,查询审批记录
var entitiesWithoutCompletionTime3 = entities.Where(x => !x.CompletionTime.HasValue).Select(x => x.Id).ToList();
if (entitiesWithoutCompletionTime3.Any())
{
var completionRecords3 = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => entitiesWithoutCompletionTime3.Contains(x.ApplicationId) && x.ApprovalResult == "通过")
.GroupBy(x => x.ApplicationId)
.Select(x => new
{
ApplicationId = x.ApplicationId,
MaxApprovalTime = SqlFunc.AggregateMax(x.ApprovalTime)
})
.ToListAsync();
foreach (var record in completionRecords3)
{
if (!completionTimeDict3.ContainsKey(record.ApplicationId))
{
completionTimeDict3[record.ApplicationId] = record.MaxApprovalTime;
}
}
}
}
// 组装返回数据
var result = entities.Select(item => new LqReimbursementApplicationListOutput
{
id = item.Id,
applicationUserId = item.ApplicationUserId,
applicationUserName = item.ApplicationUserName,
applicationStoreId = item.ApplicationStoreId,
applicationStoreName = !string.IsNullOrEmpty(item.ApplicationStoreId) && storeDict.ContainsKey(item.ApplicationStoreId)
? storeDict[item.ApplicationStoreId]
: null,
applicationTime = item.ApplicationTime,
amount = item.Amount,
approveUser = item.ApproveUser,
approveStatus = item.ApprovalStatus ?? item.ApproveStatus,
approveTime = item.ApproveTime,
purchaseRecordsId = item.PurchaseRecordsId,
currentApprovers = approverDict.ContainsKey(item.Id) ? approverDict[item.Id] : null,
currentNodeOrder = item.CurrentNodeOrder,
nodeCount = item.NodeCount,
completionTime = completionTimeDict3.ContainsKey(item.Id) ? completionTimeDict3[item.Id] : (item.CompletionTime ?? null)
}).ToList();
return PageResult<LqReimbursementApplicationListOutput>.SqlSugarPageResult(
new SqlSugarPagedList<LqReimbursementApplicationListOutput>
{
list = result,
pagination = new PagedModel { PageIndex = input.currentPage, PageSize = input.pageSize, Total = total }
});
}
/// <summary>
/// 获取审批历史
/// </summary>
/// <param name="id">申请编号</param>
/// <returns></returns>
[HttpGet("{id}/Actions/ApprovalHistory")]
public async Task<dynamic> GetApprovalHistory(string id)
{
// 先查询审批记录
var approvalRecords = await _db.Queryable<LqReimbursementApprovalRecordEntity>()
.Where(x => x.ApplicationId == id)
.OrderBy(x => x.NodeOrder)
.OrderBy(x => x.ApprovalTime)
.ToListAsync();
// 获取节点信息
if (approvalRecords.Any())
{
var nodeIds = approvalRecords.Select(x => x.NodeId).Distinct().ToList();
var nodes = await _db.Queryable<LqReimbursementApplicationNodeEntity>()
.Where(x => nodeIds.Contains(x.Id))
.ToListAsync();
var nodeDict = nodes.ToDictionary(x => x.Id, x => x.NodeName);
// 组装结果
var records = approvalRecords.Select(r => new
{
nodeOrder = r.NodeOrder,
nodeName = nodeDict.ContainsKey(r.NodeId) ? nodeDict[r.NodeId] : null,
approverName = r.ApproverName,
approvalResult = r.ApprovalResult,
approvalOpinion = r.ApprovalOpinion,
approvalTime = r.ApprovalTime
}).ToList();
return records;
}
return new List<object>();
}
/// <summary>
/// 导出本月已审核通过的报销表明细
/// </summary>
/// <remarks>
/// 导出本月已审核通过的报销申请及其关联的购买记录明细
/// 用于线下整理后导入到店内支出表
///
/// 示例请求:
/// GET /api/Extend/LqReimbursementApplication/Actions/ExportApprovedDetails?year=2025&month=01
/// </remarks>
/// <param name="year">年份(可选,默认当前年份)</param>
/// <param name="month">月份(可选,默认当前月份,格式:01-12)</param>
/// <returns>导出文件信息</returns>
/// <response code="200">导出成功</response>
/// <response code="500">服务器错误</response>
[HttpGet("Actions/ExportApprovedDetails")]
public async Task<dynamic> ExportApprovedDetails([FromQuery] int? year = null, [FromQuery] string month = null)
{
try
{
var userInfo = await _userManager.GetUserInfo();
var now = DateTime.Now;
var queryYear = year ?? now.Year;
var queryMonth = !string.IsNullOrEmpty(month) ? month : now.ToString("MM");
// 构建月份字符串(YYYYMM格式)
var monthStr = $"{queryYear}{queryMonth}";
// 计算月份的开始和结束日期
var startDate = new DateTime(queryYear, int.Parse(queryMonth), 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
// 查询本月已审核通过的报销申请
var applications = await _db.Queryable<LqReimbursementApplicationEntity>()
.Where(x => (x.ApprovalStatus ?? x.ApproveStatus) == "已通过")
.Where(x => x.ApplicationTime.HasValue &&
x.ApplicationTime.Value.Year == queryYear &&
x.ApplicationTime.Value.Month == int.Parse(queryMonth))
.ToListAsync();
// 获取所有关联的购买记录
var applicationIds = applications.Select(x => x.Id).ToList();
var purchaseRecords = new List<LqPurchaseRecordsEntity>();
if (applicationIds.Any())
{
purchaseRecords = await _db.Queryable<LqPurchaseRecordsEntity>()
.Where(x => applicationIds.Contains(x.ApplicationId))
.OrderBy(x => x.ApplicationId)
.OrderBy(x => x.CreateTime)
.ToListAsync();
}
// 获取门店信息
var storeIds = applications.Where(x => !string.IsNullOrEmpty(x.ApplicationStoreId))
.Select(x => x.ApplicationStoreId)
.Distinct()
.ToList();
var stores = new Dictionary<string, string>();
if (storeIds.Any())
{
var storeList = await _db.Queryable<LqMdxxEntity>()
.Where(x => storeIds.Contains(x.Id))
.Select(x => new { x.Id, x.Dm })
.ToListAsync();
stores = storeList.ToDictionary(x => x.Id, x => x.Dm ?? "");
}
// 组装导出数据(包含报销申请和购买记录明细)
var exportData = new List<ReimbursementDetailExportOutput>();
foreach (var app in applications)
{
var appPurchaseRecords = purchaseRecords.Where(x => x.ApplicationId == app.Id).ToList();
if (appPurchaseRecords.Any())
{
// 每个购买记录作为一行
foreach (var pr in appPurchaseRecords)
{
exportData.Add(new ReimbursementDetailExportOutput
{
applicationId = app.Id,
applicationUserName = app.ApplicationUserName,
applicationStoreId = app.ApplicationStoreId,
applicationStoreName = !string.IsNullOrEmpty(app.ApplicationStoreId) && stores.ContainsKey(app.ApplicationStoreId)
? stores[app.ApplicationStoreId]
: "",
applicationTime = app.ApplicationTime,
applicationAmount = !string.IsNullOrEmpty(app.Amount) ? decimal.Parse(app.Amount) : 0m,
purchaseRecordId = pr.Id,
reimbursementCategoryId = pr.ReimbursementCategoryId,
reimbursementCategoryName = pr.ReimbursementCategoryName,
unitPrice = pr.UnitPrice,
quantity = pr.Quantity ?? 0,
amount = pr.Amount,
memo = pr.Memo,
purchaseTime = pr.PurchaseTime
});
}
}
else
{
// 如果没有购买记录,至少导出报销申请基本信息
exportData.Add(new ReimbursementDetailExportOutput
{
applicationId = app.Id,
applicationUserName = app.ApplicationUserName,
applicationStoreId = app.ApplicationStoreId,
applicationStoreName = !string.IsNullOrEmpty(app.ApplicationStoreId) && stores.ContainsKey(app.ApplicationStoreId)
? stores[app.ApplicationStoreId]
: "",
applicationTime = app.ApplicationTime,
applicationAmount = !string.IsNullOrEmpty(app.Amount) ? decimal.Parse(app.Amount) : 0m,
purchaseRecordId = "",
reimbursementCategoryId = "",
reimbursementCategoryName = "",
unitPrice = 0m,
quantity = 0,
amount = 0m,
memo = "",
purchaseTime = null
});
}
}
// 导出Excel
List<ParamsModel> paramList = "[{\"value\":\"报销申请ID\",\"field\":\"applicationId\"},{\"value\":\"申请人姓名\",\"field\":\"applicationUserName\"},{\"value\":\"门店ID\",\"field\":\"applicationStoreId\"},{\"value\":\"门店名称\",\"field\":\"applicationStoreName\"},{\"value\":\"申请时间\",\"field\":\"applicationTime\"},{\"value\":\"申请金额\",\"field\":\"applicationAmount\"},{\"value\":\"购买记录ID\",\"field\":\"purchaseRecordId\"},{\"value\":\"支出分类ID\",\"field\":\"reimbursementCategoryId\"},{\"value\":\"支出分类名称\",\"field\":\"reimbursementCategoryName\"},{\"value\":\"单价\",\"field\":\"unitPrice\"},{\"value\":\"数量\",\"field\":\"quantity\"},{\"value\":\"金额\",\"field\":\"amount\"},{\"value\":\"备注说明\",\"field\":\"memo\"},{\"value\":\"购买时间\",\"field\":\"purchaseTime\"},]".ToList<ParamsModel>();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = $"报销表明细_{queryYear}年{queryMonth}月.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List<ExcelColumnModel>();
foreach (var param in paramList)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = param.field, ExcelColumn = param.value });
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper<ReimbursementDetailExportOutput>.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
catch (Exception ex)
{
throw NCCException.Oh($"导出失败:{ex.Message}");
}
}
}
/// <summary>
/// 报销表明细导出输出
/// </summary>
public class ReimbursementDetailExportOutput
{
/// <summary>
/// 报销申请ID
/// </summary>
public string applicationId { get; set; }
/// <summary>
/// 申请人姓名
/// </summary>
public string applicationUserName { get; set; }
/// <summary>
/// 门店ID
/// </summary>
public string applicationStoreId { get; set; }
/// <summary>
/// 门店名称
/// </summary>
public string applicationStoreName { get; set; }
/// <summary>
/// 申请时间
/// </summary>
public DateTime? applicationTime { get; set; }
/// <summary>
/// 申请金额
/// </summary>
public decimal applicationAmount { get; set; }
/// <summary>
/// 购买记录ID
/// </summary>
public string purchaseRecordId { get; set; }
/// <summary>
/// 支出分类ID
/// </summary>
public string reimbursementCategoryId { get; set; }
/// <summary>
/// 支出分类名称
/// </summary>
public string reimbursementCategoryName { get; set; }
/// <summary>
/// 单价
/// </summary>
public decimal unitPrice { get; set; }
/// <summary>
/// 数量
/// </summary>
public int quantity { get; set; }
/// <summary>
/// 金额
/// </summary>
public decimal amount { get; set; }
/// <summary>
/// 备注说明
/// </summary>
public string memo { get; set; }
/// <summary>
/// 购买时间
/// </summary>
public DateTime? purchaseTime { get; set; }
}
}