LqContractService.cs
61.1 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqContract;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_contract;
using NCC.Extend.Entitys.lq_contract_rent_detail;
using NCC.Extend.Entitys.lq_contract_monthly_cost;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
namespace NCC.Extend
{
/// <summary>
/// 合同管理服务
/// </summary>
[ApiDescriptionSettings(Tag = "绿纤合同管理", Name = "LqContract", Order = 250)]
[Route("api/Extend/LqContract")]
public class LqContractService : IDynamicApiController, ITransient
{
private readonly IUserManager _userManager;
private readonly ILogger<LqContractService> _logger;
private readonly ISqlSugarClient _db;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="userManager">用户管理器</param>
/// <param name="logger">日志记录器</param>
/// <param name="db">数据库客户端</param>
public LqContractService(IUserManager userManager, ILogger<LqContractService> logger, ISqlSugarClient db)
{
_userManager = userManager;
_logger = logger;
_db = db;
}
#region 创建合同
/// <summary>
/// 创建合同
/// </summary>
/// <remarks>
/// 创建新合同,系统会自动根据合同信息生成月租明细
///
/// 示例请求:
/// ```json
/// {
/// "storeId": "门店ID",
/// "title": "门店租赁合同",
/// "category": "租赁合同",
/// "tenantName": "张三",
/// "contractStartDate": "2025-01-01T00:00:00",
/// "contractEndDate": "2025-12-31T23:59:59",
/// "reminderDays": 7,
/// "deposit": 5000.00,
/// "monthlyRent": 1000.00,
/// "paymentAmount": 3000.00,
/// "paymentCycle": 3,
/// "remarks": "季度交租",
/// "attachment": ""
/// }
/// ```
///
/// 业务流程:
/// 1. 验证合同信息
/// 2. 查询门店信息(获取店名)
/// 3. 创建合同记录
/// 4. 自动生成月租明细(根据合同起始日期、结束日期、交租周期、缴租金额)
/// 5. 计算下次应交时间
/// </remarks>
/// <param name="input">创建输入</param>
/// <returns>创建结果</returns>
/// <response code="200">创建成功</response>
/// <response code="400">请求参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("Create")]
public async Task CreateAsync([FromBody] LqContractCrInput input)
{
try
{
// 验证合同日期
if (input.ContractStartDate >= input.ContractEndDate)
{
throw NCCException.Oh("合同起始日期必须小于合同结束日期");
}
// 验证交租周期
if (input.PaymentCycle <= 0 || input.PaymentCycle > 12)
{
throw NCCException.Oh("交租周期必须在1-12个月之间");
}
// 查询门店信息
var store = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Id == input.StoreId)
.Select(x => new { x.Dm })
.FirstAsync();
if (store == null)
{
throw NCCException.Oh("门店不存在");
}
_db.Ado.BeginTran();
try
{
// 创建合同
var contractEntity = new LqContractEntity
{
Id = YitIdHelper.NextId().ToString(),
StoreId = input.StoreId,
StoreName = store.Dm ?? "",
Title = input.Title,
Category = input.Category,
TenantName = input.TenantName,
ContractStartDate = input.ContractStartDate,
ContractEndDate = input.ContractEndDate,
ReminderDays = input.ReminderDays,
Deposit = input.Deposit,
MonthlyRent = input.MonthlyRent,
PaymentAmount = input.PaymentAmount,
PaymentCycle = input.PaymentCycle,
Remarks = input.Remarks,
Attachment = input.Attachment,
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now,
IsEffective = StatusEnum.有效.GetHashCode()
};
var insertCount = await _db.Insertable(contractEntity).ExecuteCommandAsync();
if (insertCount <= 0)
{
throw NCCException.Oh("创建合同失败");
}
// 自动生成月租明细
await GenerateRentDetailsAsync(contractEntity.Id, contractEntity.ContractStartDate, contractEntity.ContractEndDate, contractEntity.PaymentCycle, contractEntity.PaymentAmount);
// 自动生成按月成本记录
await GenerateMonthlyCostAsync(contractEntity.Id, contractEntity.StoreId, contractEntity.StoreName, contractEntity.Category, contractEntity.ContractStartDate, contractEntity.ContractEndDate, contractEntity.PaymentCycle, contractEntity.PaymentAmount);
// 计算下次应交时间
await CalculateNextPaymentDate(contractEntity.Id);
_db.Ado.CommitTran();
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
_logger.LogError(ex, "创建合同失败");
throw NCCException.Oh($"创建失败:{ex.Message}");
}
}
#endregion
#region 更新合同
/// <summary>
/// 更新合同
/// </summary>
/// <remarks>
/// 更新合同信息。如果修改了合同起始日期、结束日期、交租周期或缴租金额,系统会重新生成月租明细。
///
/// 示例请求:
/// ```json
/// {
/// "id": "合同ID",
/// "storeId": "门店ID",
/// "title": "门店租赁合同",
/// "category": "租赁合同",
/// "tenantName": "张三",
/// "contractStartDate": "2025-01-01T00:00:00",
/// "contractEndDate": "2025-12-31T23:59:59",
/// "reminderDays": 7,
/// "deposit": 5000.00,
/// "monthlyRent": 1000.00,
/// "paymentAmount": 3000.00,
/// "paymentCycle": 3,
/// "remarks": "季度交租",
/// "attachment": ""
/// }
/// ```
/// </remarks>
/// <param name="input">更新输入</param>
/// <returns>更新结果</returns>
/// <response code="200">更新成功</response>
/// <response code="400">请求参数错误或合同不存在</response>
/// <response code="500">服务器错误</response>
[HttpPut("Update")]
public async Task UpdateAsync([FromBody] LqContractUpInput input)
{
try
{
// 查询合同
var contract = await _db.Queryable<LqContractEntity>()
.Where(x => x.Id == input.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (contract == null)
{
throw NCCException.Oh("合同不存在或已失效");
}
// 验证合同日期
if (input.ContractStartDate >= input.ContractEndDate)
{
throw NCCException.Oh("合同起始日期必须小于合同结束日期");
}
// 验证交租周期
if (input.PaymentCycle <= 0 || input.PaymentCycle > 12)
{
throw NCCException.Oh("交租周期必须在1-12个月之间");
}
// 查询门店信息
var store = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Id == input.StoreId)
.Select(x => new { x.Dm })
.FirstAsync();
if (store == null)
{
throw NCCException.Oh("门店不存在");
}
_db.Ado.BeginTran();
try
{
// 判断是否需要重新生成明细
bool needRegenerateDetails = contract.ContractStartDate != input.ContractStartDate ||
contract.ContractEndDate != input.ContractEndDate ||
contract.PaymentCycle != input.PaymentCycle ||
contract.PaymentAmount != input.PaymentAmount;
// 判断是否需要更新成本记录的分类(如果只修改了分类,不需要重新生成,只需更新分类字段)
bool needUpdateCategory = contract.Category != input.Category;
// 更新合同信息
contract.StoreId = input.StoreId;
contract.StoreName = store.Dm ?? "";
contract.Title = input.Title;
contract.Category = input.Category;
contract.TenantName = input.TenantName;
contract.ContractStartDate = input.ContractStartDate;
contract.ContractEndDate = input.ContractEndDate;
contract.ReminderDays = input.ReminderDays;
contract.Deposit = input.Deposit;
contract.MonthlyRent = input.MonthlyRent;
contract.PaymentAmount = input.PaymentAmount;
contract.PaymentCycle = input.PaymentCycle;
contract.Remarks = input.Remarks;
contract.Attachment = input.Attachment;
contract.UpdateUser = _userManager.UserId;
contract.UpdateTime = DateTime.Now;
var updateCount = await _db.Updateable(contract).ExecuteCommandAsync();
if (updateCount <= 0)
{
throw NCCException.Oh("更新合同失败");
}
// 如果需要重新生成明细,先删除旧明细,再生成新明细
if (needRegenerateDetails)
{
// 删除旧的明细(逻辑删除)
await _db.Updateable<LqContractRentDetailEntity>()
.SetColumns(x => new LqContractRentDetailEntity
{
IsEffective = StatusEnum.无效.GetHashCode(),
UpdateUser = _userManager.UserId,
UpdateTime = DateTime.Now
})
.Where(x => x.ContractId == contract.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.ExecuteCommandAsync();
// 删除旧的成本记录(逻辑删除)
await _db.Updateable<LqContractMonthlyCostEntity>()
.SetColumns(x => new LqContractMonthlyCostEntity
{
IsEffective = StatusEnum.无效.GetHashCode(),
UpdateTime = DateTime.Now
})
.Where(x => x.ContractId == contract.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.ExecuteCommandAsync();
// 生成新的明细
await GenerateRentDetailsAsync(contract.Id, contract.ContractStartDate, contract.ContractEndDate, contract.PaymentCycle, contract.PaymentAmount);
// 生成新的成本记录
await GenerateMonthlyCostAsync(contract.Id, contract.StoreId, contract.StoreName, contract.Category, contract.ContractStartDate, contract.ContractEndDate, contract.PaymentCycle, contract.PaymentAmount);
}
else if (needUpdateCategory)
{
// 如果只修改了分类,只需更新成本记录的分类字段
await _db.Updateable<LqContractMonthlyCostEntity>()
.SetColumns(x => new LqContractMonthlyCostEntity
{
Category = contract.Category,
UpdateTime = DateTime.Now
})
.Where(x => x.ContractId == contract.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.ExecuteCommandAsync();
}
// 重新计算下次应交时间
await CalculateNextPaymentDate(contract.Id);
_db.Ado.CommitTran();
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
_logger.LogError(ex, "更新合同失败");
throw NCCException.Oh($"更新失败:{ex.Message}");
}
}
#endregion
#region 删除合同
/// <summary>
/// 删除合同
/// </summary>
/// <remarks>
/// 删除合同,同时会级联删除该合同的所有月租明细(逻辑删除)
///
/// 示例请求:
/// ```
/// DELETE /api/Extend/LqContract/{id}
/// ```
/// </remarks>
/// <param name="id">合同ID</param>
/// <returns>删除结果</returns>
/// <response code="200">删除成功</response>
/// <response code="400">合同不存在</response>
/// <response code="500">服务器错误</response>
[HttpDelete("{id}")]
public async Task DeleteAsync([FromRoute] string id)
{
try
{
if (string.IsNullOrWhiteSpace(id))
{
throw NCCException.Oh("合同ID不能为空");
}
// 查询合同
var contract = await _db.Queryable<LqContractEntity>()
.Where(x => x.Id == id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (contract == null)
{
throw NCCException.Oh("合同不存在或已失效");
}
_db.Ado.BeginTran();
try
{
// 删除该合同的所有月租明细(逻辑删除)
await _db.Updateable<LqContractRentDetailEntity>()
.SetColumns(x => new LqContractRentDetailEntity
{
IsEffective = StatusEnum.无效.GetHashCode(),
UpdateUser = _userManager.UserId,
UpdateTime = DateTime.Now
})
.Where(x => x.ContractId == id && x.IsEffective == StatusEnum.有效.GetHashCode())
.ExecuteCommandAsync();
// 删除该合同的所有成本记录(逻辑删除)
await _db.Updateable<LqContractMonthlyCostEntity>()
.SetColumns(x => new LqContractMonthlyCostEntity
{
IsEffective = StatusEnum.无效.GetHashCode(),
UpdateTime = DateTime.Now
})
.Where(x => x.ContractId == id && x.IsEffective == StatusEnum.有效.GetHashCode())
.ExecuteCommandAsync();
// 删除合同(逻辑删除)
contract.IsEffective = StatusEnum.无效.GetHashCode();
contract.UpdateUser = _userManager.UserId;
contract.UpdateTime = DateTime.Now;
var updateCount = await _db.Updateable(contract).ExecuteCommandAsync();
if (updateCount <= 0)
{
throw NCCException.Oh("删除合同失败");
}
_db.Ado.CommitTran();
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
_logger.LogError(ex, "删除合同失败");
throw NCCException.Oh($"删除失败:{ex.Message}");
}
}
#endregion
#region 获取合同列表
/// <summary>
/// 获取合同列表
/// </summary>
/// <remarks>
/// 分页查询合同列表,支持多条件筛选
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqContract/GetList?currentPage=1&pageSize=10&storeId=门店ID&title=合同标题
/// ```
/// </remarks>
/// <param name="input">查询输入</param>
/// <returns>合同列表</returns>
/// <response code="200">查询成功</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetList")]
public async Task<dynamic> GetListAsync([FromQuery] LqContractListQueryInput input)
{
try
{
var sidx = string.IsNullOrEmpty(input.sidx) ? "createTime" : input.sidx;
var sort = string.IsNullOrEmpty(input.sort) ? "desc" : input.sort;
var data = await _db.Queryable<LqContractEntity>()
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), x => x.StoreId == input.StoreId)
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreName), x => x.StoreName != null && x.StoreName.Contains(input.StoreName))
.WhereIF(!string.IsNullOrWhiteSpace(input.Category), x => x.Category == input.Category)
.WhereIF(!string.IsNullOrWhiteSpace(input.Title), x => x.Title != null && x.Title.Contains(input.Title))
.WhereIF(input.ContractStartDateBegin.HasValue, x => x.ContractStartDate >= input.ContractStartDateBegin.Value)
.WhereIF(input.ContractStartDateEnd.HasValue, x => x.ContractStartDate <= input.ContractStartDateEnd.Value)
.WhereIF(input.ContractEndDateBegin.HasValue, x => x.ContractEndDate >= input.ContractEndDateBegin.Value)
.WhereIF(input.ContractEndDateEnd.HasValue, x => x.ContractEndDate <= input.ContractEndDateEnd.Value)
.WhereIF(input.IsEffective.HasValue, x => x.IsEffective == input.IsEffective.Value)
.Where(x => x.IsEffective == StatusEnum.有效.GetHashCode())
.Select(x => new LqContractListOutput
{
id = x.Id,
storeId = x.StoreId,
storeName = x.StoreName,
title = x.Title,
category = x.Category,
tenantName = x.TenantName,
contractStartDate = x.ContractStartDate,
contractEndDate = x.ContractEndDate,
reminderDays = x.ReminderDays,
deposit = x.Deposit,
nextPaymentDate = x.NextPaymentDate,
monthlyRent = x.MonthlyRent,
paymentAmount = x.PaymentAmount,
paymentCycle = x.PaymentCycle,
remarks = x.Remarks,
attachment = x.Attachment,
createUser = x.CreateUser,
createUserName = "",
createTime = x.CreateTime,
updateUser = x.UpdateUser,
updateUserName = "",
updateTime = x.UpdateTime,
isEffective = x.IsEffective
})
.MergeTable()
.OrderBy(sidx + " " + sort)
.ToPagedListAsync(input.currentPage, input.pageSize);
// 补充用户信息
var userIds = data.list.SelectMany(x => new[] { x.createUser, x.updateUser })
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
if (userIds.Any())
{
var userList = await _db.Queryable<UserEntity>()
.Where(x => userIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = userList.ToDictionary(k => k.Id, v => v.RealName);
foreach (var item in data.list)
{
if (!string.IsNullOrEmpty(item.createUser) && userDict.ContainsKey(item.createUser))
item.createUserName = userDict[item.createUser];
if (!string.IsNullOrEmpty(item.updateUser) && userDict.ContainsKey(item.updateUser))
item.updateUserName = userDict[item.updateUser];
}
}
return PageResult<LqContractListOutput>.SqlSugarPageResult(data);
}
catch (Exception ex)
{
_logger.LogError(ex, "获取合同列表失败");
throw NCCException.Oh($"获取合同列表失败:{ex.Message}");
}
}
#endregion
#region 获取合同详情
/// <summary>
/// 获取合同详情
/// </summary>
/// <remarks>
/// 根据合同ID获取合同详细信息,包括月租明细列表
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqContract/GetInfo?id=合同ID
/// ```
/// </remarks>
/// <param name="id">合同ID</param>
/// <returns>合同详情</returns>
/// <response code="200">查询成功</response>
/// <response code="400">合同ID不能为空</response>
/// <response code="404">合同不存在</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetInfo")]
public async Task<LqContractInfoOutput> GetInfoAsync([FromQuery] string id)
{
try
{
if (string.IsNullOrWhiteSpace(id))
{
throw NCCException.Oh("合同ID不能为空");
}
// 查询合同
var contract = await _db.Queryable<LqContractEntity>()
.Where(x => x.Id == id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (contract == null)
{
throw NCCException.Oh("合同不存在或已失效");
}
// 查询月租明细
var rentDetails = await _db.Queryable<LqContractRentDetailEntity>()
.Where(x => x.ContractId == id && x.IsEffective == StatusEnum.有效.GetHashCode())
.OrderBy(x => x.PaymentMonth)
.Select(x => new LqContractRentDetailListOutput
{
id = x.Id,
contractId = x.ContractId,
paymentMonth = x.PaymentMonth,
dueDate = x.DueDate,
dueAmount = x.DueAmount,
isPaid = x.IsPaid,
actualPaymentDate = x.ActualPaymentDate,
actualPaymentAmount = x.ActualPaymentAmount,
remarks = x.Remarks,
createUser = x.CreateUser,
createUserName = "",
createTime = x.CreateTime,
updateUser = x.UpdateUser,
updateUserName = "",
updateTime = x.UpdateTime,
isEffective = x.IsEffective
})
.ToListAsync();
// 补充用户信息
var userIds = new List<string> { contract.CreateUser, contract.UpdateUser };
userIds.AddRange(rentDetails.SelectMany(x => new[] { x.createUser, x.updateUser }).Where(x => !string.IsNullOrEmpty(x)));
string createUserName = "";
string updateUserName = "";
if (userIds.Any())
{
var userList = await _db.Queryable<UserEntity>()
.Where(x => userIds.Distinct().Contains(x.Id))
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = userList.ToDictionary(k => k.Id, v => v.RealName);
if (!string.IsNullOrEmpty(contract.CreateUser) && userDict.ContainsKey(contract.CreateUser))
createUserName = userDict[contract.CreateUser];
if (!string.IsNullOrEmpty(contract.UpdateUser) && userDict.ContainsKey(contract.UpdateUser))
updateUserName = userDict[contract.UpdateUser];
foreach (var detail in rentDetails)
{
if (!string.IsNullOrEmpty(detail.createUser) && userDict.ContainsKey(detail.createUser))
detail.createUserName = userDict[detail.createUser];
if (!string.IsNullOrEmpty(detail.updateUser) && userDict.ContainsKey(detail.updateUser))
detail.updateUserName = userDict[detail.updateUser];
}
}
return new LqContractInfoOutput
{
id = contract.Id,
storeId = contract.StoreId,
storeName = contract.StoreName,
title = contract.Title,
category = contract.Category,
tenantName = contract.TenantName,
contractStartDate = contract.ContractStartDate,
contractEndDate = contract.ContractEndDate,
reminderDays = contract.ReminderDays,
deposit = contract.Deposit,
nextPaymentDate = contract.NextPaymentDate,
monthlyRent = contract.MonthlyRent,
paymentAmount = contract.PaymentAmount,
paymentCycle = contract.PaymentCycle,
remarks = contract.Remarks,
attachment = contract.Attachment,
createUser = contract.CreateUser,
createUserName = createUserName,
createTime = contract.CreateTime,
updateUser = contract.UpdateUser,
updateUserName = updateUserName,
updateTime = contract.UpdateTime,
isEffective = contract.IsEffective,
rentDetails = rentDetails
};
}
catch (Exception ex)
{
_logger.LogError(ex, "获取合同详情失败");
throw NCCException.Oh($"获取合同详情失败:{ex.Message}");
}
}
#endregion
#region 获取月租明细列表
/// <summary>
/// 获取月租明细列表
/// </summary>
/// <remarks>
/// 根据合同ID获取该合同的所有月租明细
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqContract/GetRentDetails?contractId=合同ID
/// ```
/// </remarks>
/// <param name="contractId">合同ID</param>
/// <returns>月租明细列表</returns>
/// <response code="200">查询成功</response>
/// <response code="400">合同ID不能为空</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetRentDetails")]
public async Task<dynamic> GetRentDetailsAsync([FromQuery] string contractId)
{
try
{
if (string.IsNullOrWhiteSpace(contractId))
{
throw NCCException.Oh("合同ID不能为空");
}
var rentDetails = await _db.Queryable<LqContractRentDetailEntity>()
.Where(x => x.ContractId == contractId && x.IsEffective == StatusEnum.有效.GetHashCode())
.OrderBy(x => x.PaymentMonth)
.Select(x => new LqContractRentDetailListOutput
{
id = x.Id,
contractId = x.ContractId,
paymentMonth = x.PaymentMonth,
dueDate = x.DueDate,
dueAmount = x.DueAmount,
isPaid = x.IsPaid,
actualPaymentDate = x.ActualPaymentDate,
actualPaymentAmount = x.ActualPaymentAmount,
remarks = x.Remarks,
createUser = x.CreateUser,
createUserName = "",
createTime = x.CreateTime,
updateUser = x.UpdateUser,
updateUserName = "",
updateTime = x.UpdateTime,
isEffective = x.IsEffective
})
.ToListAsync();
// 补充用户信息
var userIds = rentDetails.SelectMany(x => new[] { x.createUser, x.updateUser })
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList();
if (userIds.Any())
{
var userList = await _db.Queryable<UserEntity>()
.Where(x => userIds.Contains(x.Id))
.Select(x => new { x.Id, x.RealName })
.ToListAsync();
var userDict = userList.ToDictionary(k => k.Id, v => v.RealName);
foreach (var detail in rentDetails)
{
if (!string.IsNullOrEmpty(detail.createUser) && userDict.ContainsKey(detail.createUser))
detail.createUserName = userDict[detail.createUser];
if (!string.IsNullOrEmpty(detail.updateUser) && userDict.ContainsKey(detail.updateUser))
detail.updateUserName = userDict[detail.updateUser];
}
}
return rentDetails;
}
catch (Exception ex)
{
_logger.LogError(ex, "获取月租明细列表失败");
throw NCCException.Oh($"获取月租明细列表失败:{ex.Message}");
}
}
#endregion
#region 标记明细已缴费
/// <summary>
/// 标记月租明细已缴费
/// </summary>
/// <remarks>
/// 标记某条月租明细已缴费,记录实际缴费时间和金额
///
/// 示例请求:
/// ```json
/// {
/// "id": "明细ID",
/// "actualPaymentDate": "2025-01-15T00:00:00",
/// "actualPaymentAmount": 3000.00,
/// "remarks": "已缴费"
/// }
/// ```
/// </remarks>
/// <param name="input">标记已缴费输入</param>
/// <returns>标记结果</returns>
/// <response code="200">标记成功</response>
/// <response code="400">明细不存在或已缴费</response>
/// <response code="500">服务器错误</response>
[HttpPut("MarkRentDetailPaid")]
public async Task MarkRentDetailPaidAsync([FromBody] LqContractRentDetailMarkPaidInput input)
{
try
{
// 查询明细
var detail = await _db.Queryable<LqContractRentDetailEntity>()
.Where(x => x.Id == input.Id && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (detail == null)
{
throw NCCException.Oh("月租明细不存在或已失效");
}
if (detail.IsPaid == 1)
{
throw NCCException.Oh("该明细已标记为已缴费");
}
_db.Ado.BeginTran();
try
{
// 更新明细
detail.IsPaid = 1;
detail.ActualPaymentDate = input.ActualPaymentDate;
detail.ActualPaymentAmount = input.ActualPaymentAmount;
detail.Remarks = input.Remarks;
detail.UpdateUser = _userManager.UserId;
detail.UpdateTime = DateTime.Now;
var updateCount = await _db.Updateable(detail).ExecuteCommandAsync();
if (updateCount <= 0)
{
throw NCCException.Oh("标记已缴费失败");
}
// 重新计算下次应交时间
await CalculateNextPaymentDate(detail.ContractId);
_db.Ado.CommitTran();
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
_logger.LogError(ex, "标记明细已缴费失败");
throw NCCException.Oh($"标记失败:{ex.Message}");
}
}
#endregion
#region 根据合同id获取合同成本列表
/// <summary>
/// 根据合同id获取合同成本列表
/// </summary>
/// <param name="contractId"></param>
/// <returns></returns>
[HttpGet("GetContractCostList")]
public async Task<dynamic> GetContractCostListAsync([FromQuery] string contractId)
{
try
{
if (string.IsNullOrWhiteSpace(contractId))
{
throw NCCException.Oh("合同ID不能为空");
}
var costList = await _db.Queryable<LqContractMonthlyCostEntity>()
.Where(x => x.ContractId == contractId && x.IsEffective == StatusEnum.有效.GetHashCode())
.ToListAsync();
return costList;
}
catch (Exception ex)
{
_logger.LogError(ex, "获取合同成本列表失败");
throw NCCException.Oh($"获取合同成本列表失败:{ex.Message}");
}
}
#endregion
#region 私有方法
/// <summary>
/// 自动生成月租明细
/// </summary>
/// <param name="contractId">合同ID</param>
/// <param name="contractStartDate">合同起始日期</param>
/// <param name="contractEndDate">合同结束日期</param>
/// <param name="paymentCycle">交租周期(月)</param>
/// <param name="paymentAmount">缴租金额</param>
private async Task GenerateRentDetailsAsync(string contractId, DateTime contractStartDate, DateTime contractEndDate, int paymentCycle, decimal paymentAmount)
{
var details = new List<LqContractRentDetailEntity>();
var currentDate = contractStartDate.Date;
// 从合同起始日期开始,每隔交租周期生成一条明细
while (currentDate <= contractEndDate)
{
// 应缴月份:当前日期的月份第一天(格式:YYYY-MM-01)
var paymentMonth = new DateTime(currentDate.Year, currentDate.Month, 1);
// 应缴日期:应缴月份的第一天(根据业务规则,应缴日期为应缴月份的第一天)
var dueDate = paymentMonth;
var detail = new LqContractRentDetailEntity
{
Id = YitIdHelper.NextId().ToString(),
ContractId = contractId,
PaymentMonth = paymentMonth,
DueDate = dueDate,
DueAmount = paymentAmount,
IsPaid = 0,
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now,
IsEffective = StatusEnum.有效.GetHashCode()
};
details.Add(detail);
// 计算下一个交租日期(加上交租周期)
currentDate = currentDate.AddMonths(paymentCycle);
}
// 批量插入
if (details.Any())
{
await _db.Insertable(details).ExecuteCommandAsync();
}
}
/// <summary>
/// 生成按月成本记录
/// </summary>
/// <param name="contractId">合同ID</param>
/// <param name="storeId">门店ID</param>
/// <param name="storeName">店名</param>
/// <param name="category">分类</param>
/// <param name="contractStartDate">合同起始日期</param>
/// <param name="contractEndDate">合同结束日期</param>
/// <param name="paymentCycle">交租周期(月)</param>
/// <param name="paymentAmount">缴租金额</param>
private async Task GenerateMonthlyCostAsync(string contractId, string storeId, string storeName, string category, DateTime contractStartDate, DateTime contractEndDate, int paymentCycle, decimal paymentAmount)
{
// 计算每个月成本 = 缴租金额 / 交租周期
var monthlyCost = paymentAmount / paymentCycle;
var costRecords = new List<LqContractMonthlyCostEntity>();
var currentMonth = new DateTime(contractStartDate.Year, contractStartDate.Month, 1);
// 从合同起始月份开始,逐月生成成本记录,直到合同结束月份
while (currentMonth <= contractEndDate)
{
var costRecord = new LqContractMonthlyCostEntity
{
Id = YitIdHelper.NextId().ToString(),
ContractId = contractId,
StoreId = storeId,
StoreName = storeName,
Category = category,
Month = currentMonth,
MonthlyCost = monthlyCost,
PaymentCycle = paymentCycle,
PaymentAmount = paymentAmount,
IsEffective = StatusEnum.有效.GetHashCode(),
CreateUser = _userManager.UserId,
CreateTime = DateTime.Now
};
costRecords.Add(costRecord);
// 计算下一个月
currentMonth = currentMonth.AddMonths(1);
}
// 批量插入
if (costRecords.Any())
{
await _db.Insertable(costRecords).ExecuteCommandAsync();
}
}
/// <summary>
/// 计算下次应交时间(匿名方法)
/// </summary>
/// <param name="contractId">合同ID</param>
private async Task CalculateNextPaymentDate(string contractId)
{
// 查询合同信息
var contract = await _db.Queryable<LqContractEntity>()
.Where(x => x.Id == contractId && x.IsEffective == StatusEnum.有效.GetHashCode())
.FirstAsync();
if (contract == null)
{
return;
}
// 查询该合同未缴费的明细,按应缴日期升序排列
var unpaidDetail = await _db.Queryable<LqContractRentDetailEntity>()
.Where(x => x.ContractId == contractId && x.IsEffective == StatusEnum.有效.GetHashCode() && x.IsPaid == 0)
.OrderBy(x => x.DueDate)
.FirstAsync();
if (unpaidDetail != null)
{
// 计算:下次应交时间 = 最早应缴日期 - 提前提醒天数
var nextPaymentDate = unpaidDetail.DueDate.AddDays(-contract.ReminderDays);
// 更新合同的下次应交时间
contract.NextPaymentDate = nextPaymentDate;
contract.UpdateUser = _userManager.UserId;
contract.UpdateTime = DateTime.Now;
await _db.Updateable(contract).ExecuteCommandAsync();
}
else
{
// 如果没有未缴费的明细,清空下次应交时间
contract.NextPaymentDate = null;
contract.UpdateUser = _userManager.UserId;
contract.UpdateTime = DateTime.Now;
await _db.Updateable(contract).ExecuteCommandAsync();
}
}
#endregion
#region 获取合同成本按月统计
/// <summary>
/// 获取合同成本按月统计
/// </summary>
/// <remarks>
/// 根据合同ID、门店ID、月份等条件查询合同成本按月统计数据
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqContract/GetMonthlyCost?contractId=合同ID&storeId=门店ID&startMonth=2025-01&endMonth=2025-12
/// ```
///
/// 参数说明:
/// - contractId: 合同ID(可选)
/// - storeId: 门店ID(可选)
/// - startMonth: 开始月份(格式:YYYY-MM,可选)
/// - endMonth: 结束月份(格式:YYYY-MM,可选)
/// </remarks>
/// <param name="contractId">合同ID(可选)</param>
/// <param name="storeId">门店ID(可选)</param>
/// <param name="category">分类(可选)</param>
/// <param name="startMonth">开始月份(格式:YYYY-MM,可选)</param>
/// <param name="endMonth">结束月份(格式:YYYY-MM,可选)</param>
/// <returns>合同成本按月统计列表</returns>
/// <response code="200">查询成功</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetMonthlyCost")]
public async Task<dynamic> GetMonthlyCostAsync(
[FromQuery] string contractId = null,
[FromQuery] string storeId = null,
[FromQuery] string category = null,
[FromQuery] string startMonth = null,
[FromQuery] string endMonth = null)
{
try
{
var query = _db.Queryable<LqContractMonthlyCostEntity>()
.Where(x => x.IsEffective == StatusEnum.有效.GetHashCode())
.WhereIF(!string.IsNullOrWhiteSpace(contractId), x => x.ContractId == contractId)
.WhereIF(!string.IsNullOrWhiteSpace(storeId), x => x.StoreId == storeId)
.WhereIF(!string.IsNullOrWhiteSpace(category), x => x.Category == category);
// 处理月份范围筛选
if (!string.IsNullOrWhiteSpace(startMonth))
{
if (DateTime.TryParseExact(startMonth, "yyyy-MM", null, DateTimeStyles.None, out DateTime startDate))
{
var startMonthDate = new DateTime(startDate.Year, startDate.Month, 1);
query = query.Where(x => x.Month >= startMonthDate);
}
}
if (!string.IsNullOrWhiteSpace(endMonth))
{
if (DateTime.TryParseExact(endMonth, "yyyy-MM", null, DateTimeStyles.None, out DateTime endDate))
{
var endMonthDate = new DateTime(endDate.Year, endDate.Month, DateTime.DaysInMonth(endDate.Year, endDate.Month));
query = query.Where(x => x.Month <= endMonthDate);
}
}
var data = await query
.OrderBy(x => x.Month)
.Select(x => new
{
id = x.Id,
contractId = x.ContractId,
storeId = x.StoreId,
storeName = x.StoreName,
category = x.Category,
month = x.Month.ToString("yyyy-MM"),
monthlyCost = x.MonthlyCost,
paymentCycle = x.PaymentCycle,
paymentAmount = x.PaymentAmount,
createTime = x.CreateTime
})
.ToListAsync();
return new { code = 200, msg = "查询成功", data = data };
}
catch (Exception ex)
{
_logger.LogError(ex, "获取合同成本按月统计失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
/// <summary>
/// 按门店和月份统计合同成本
/// </summary>
/// <remarks>
/// 根据门店ID和月份统计该门店的合同成本总和
///
/// 示例请求:
/// ```
/// GET /api/Extend/LqContract/GetStoreMonthlyCost?storeId=门店ID&month=2025-11
/// ```
/// </remarks>
/// <param name="storeId">门店ID</param>
/// <param name="month">月份(格式:YYYY-MM)</param>
/// <returns>该门店该月的合同成本总和</returns>
/// <response code="200">查询成功</response>
/// <response code="400">参数错误</response>
/// <response code="500">服务器错误</response>
[HttpGet("GetStoreMonthlyCost")]
public async Task<dynamic> GetStoreMonthlyCostAsync(
[FromQuery] string storeId,
[FromQuery] string month)
{
try
{
if (string.IsNullOrWhiteSpace(storeId))
{
throw NCCException.Oh("门店ID不能为空");
}
if (string.IsNullOrWhiteSpace(month))
{
throw NCCException.Oh("月份不能为空");
}
if (!DateTime.TryParseExact(month, "yyyy-MM", null, DateTimeStyles.None, out DateTime monthDate))
{
throw NCCException.Oh("月份格式错误,应为 YYYY-MM");
}
var monthStart = new DateTime(monthDate.Year, monthDate.Month, 1);
var totalCost = await _db.Queryable<LqContractMonthlyCostEntity>()
.Where(x => x.StoreId == storeId
&& x.Month == monthStart
&& x.IsEffective == StatusEnum.有效.GetHashCode())
.SumAsync(x => x.MonthlyCost);
return new { code = 200, msg = "查询成功", data = new { storeId = storeId, month = month, totalCost = totalCost } };
}
catch (Exception ex)
{
_logger.LogError(ex, "按门店和月份统计合同成本失败");
throw NCCException.Oh($"查询失败:{ex.Message}");
}
}
#endregion
#region 统计门店合同费用
/// <summary>
/// 统计门店合同费用
/// </summary>
/// <remarks>
/// 根据门店ID和月份统计该门店的合同费用,支持按分类统计(租门店、员工宿舍、车辆、场所等)
///
/// 示例请求:
/// ```json
/// {
/// "storeId": "1649328471923847168",
/// "year": 2025,
/// "month": 1,
/// "categories": ["租门店", "员工宿舍", "车辆", "场所"]
/// }
/// ```
///
/// 参数说明:
/// - storeId: 门店ID(必填)
/// - year: 统计年份(可选,不传则统计所有年份)
/// - month: 统计月份(可选,1-12,不传则统计所有月份;如果只传月份不传年份,则使用当前年份)
/// - categories: 分类列表(可选,不传则统计所有分类)
///
/// 时间范围说明:
/// - 如果同时提供年份和月份:统计指定月份的数据
/// - 如果只提供年份:统计整年的数据
/// - 如果都不提供:统计所有时间的数据
///
/// 返回数据说明:
/// - storeId: 门店ID
/// - storeName: 门店名称
/// - year: 统计年份
/// - month: 统计月份
/// - totalAmount: 总费用(所有分类的费用总和)
/// - categoryDetails: 按分类统计的费用明细
/// - category: 分类名称
/// - amount: 该分类的费用总额
/// - detailCount: 该分类的明细数量
/// - details: 明细列表
/// </remarks>
/// <param name="input">统计输入</param>
/// <returns>费用统计结果</returns>
/// <response code="200">统计成功</response>
/// <response code="400">请求参数错误</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetExpenseStatistics")]
public async Task<ContractExpenseStatisticsOutput> GetExpenseStatisticsAsync([FromBody] ContractExpenseStatisticsInput input)
{
try
{
// 验证年份(如果提供了年份)
if (input.Year.HasValue && (input.Year < 2020 || input.Year > 2100))
{
throw NCCException.Oh("年份必须在2020-2100之间");
}
// 验证月份(如果提供了月份)
if (input.Month.HasValue && (input.Month < 1 || input.Month > 12))
{
throw NCCException.Oh("月份必须在1-12之间");
}
// 如果提供了月份但没有提供年份,使用当前年份
if (input.Month.HasValue && !input.Year.HasValue)
{
input.Year = DateTime.Now.Year;
}
// 构建时间范围
DateTime? monthStart = null;
DateTime? monthEnd = null;
if (input.Year.HasValue && input.Month.HasValue)
{
// 统计指定月份
var statisticsMonth = new DateTime(input.Year.Value, input.Month.Value, 1);
monthStart = statisticsMonth;
monthEnd = statisticsMonth.AddMonths(1).AddDays(-1);
}
else if (input.Year.HasValue)
{
// 只提供了年份,统计整年
monthStart = new DateTime(input.Year.Value, 1, 1);
monthEnd = new DateTime(input.Year.Value, 12, 31, 23, 59, 59);
}
// 如果年份和月份都没提供,monthStart 和 monthEnd 保持为 null,表示不按时间过滤
// 查询门店信息
var store = await _db.Queryable<LqMdxxEntity>()
.Where(x => x.Id == input.StoreId)
.Select(x => new { x.Dm })
.FirstAsync();
if (store == null)
{
throw NCCException.Oh("门店不存在");
}
// 查询该门店在指定时间范围的月租明细
var detailsQuery = _db.Queryable<LqContractRentDetailEntity, LqContractEntity>(
(detail, contract) => new JoinQueryInfos(
JoinType.Inner, detail.ContractId == contract.Id))
.Where((detail, contract) =>
contract.StoreId == input.StoreId &&
contract.IsEffective == StatusEnum.有效.GetHashCode() &&
detail.IsEffective == StatusEnum.有效.GetHashCode());
// 如果提供了时间范围,则添加时间过滤条件
if (monthStart.HasValue && monthEnd.HasValue)
{
detailsQuery = detailsQuery.Where((detail, contract) =>
detail.PaymentMonth >= monthStart.Value &&
detail.PaymentMonth <= monthEnd.Value);
}
// 如果指定了分类,则添加分类过滤条件
var details = await detailsQuery
.WhereIF(input.Categories != null && input.Categories.Length > 0,
(detail, contract) => contract.Category != null && input.Categories.Contains(contract.Category))
.Select((detail, contract) => new
{
DetailId = detail.Id,
ContractId = contract.Id,
ContractTitle = contract.Title,
Category = contract.Category ?? "未分类",
DueAmount = detail.DueAmount,
IsPaid = detail.IsPaid,
ActualPaymentAmount = detail.ActualPaymentAmount
})
.ToListAsync();
// 按分类分组统计
var categoryGroups = details.GroupBy(x => x.Category).ToList();
var categoryDetails = new List<CategoryExpenseDetail>();
decimal totalAmount = 0;
foreach (var group in categoryGroups)
{
var categoryName = group.Key;
var categoryItems = group.ToList();
var categoryAmount = categoryItems.Sum(x => x.DueAmount);
totalAmount += categoryAmount;
var expenseDetails = categoryItems.Select(x => new ExpenseDetailItem
{
detailId = x.DetailId,
contractId = x.ContractId,
contractTitle = x.ContractTitle,
category = x.Category,
dueAmount = x.DueAmount,
isPaid = x.IsPaid,
actualPaymentAmount = x.ActualPaymentAmount
}).ToList();
categoryDetails.Add(new CategoryExpenseDetail
{
category = categoryName,
amount = categoryAmount,
detailCount = categoryItems.Count,
details = expenseDetails
});
}
// 按分类名称排序
categoryDetails = categoryDetails.OrderBy(x => x.category).ToList();
return new ContractExpenseStatisticsOutput
{
storeId = input.StoreId,
storeName = store.Dm ?? "",
year = input.Year ?? 0,
month = input.Month ?? 0,
totalAmount = totalAmount,
categoryDetails = categoryDetails
};
}
catch (Exception ex)
{
_logger.LogError(ex, "统计门店合同费用失败");
throw NCCException.Oh($"统计失败:{ex.Message}");
}
}
#endregion
#region 付款提醒列表
/// <summary>
/// 获取付款前提醒列表
/// </summary>
/// <remarks>
/// 查询需要提醒付款的合同列表
///
/// 查询逻辑:
/// 1. 查询所有有效的合同,且 F_NextPaymentDate 不为空
/// 2. 如果 OnlyOverdue 为 true,只返回 F_NextPaymentDate 小于等于当前日期的合同
/// 3. 如果 OnlyOverdue 为 false,返回所有有提醒时间的合同
/// 4. 关联查询未缴费的明细,获取应缴日期和应缴金额
/// 5. 计算距离应缴日期的天数
///
/// 示例请求:
/// ```json
/// {
/// "storeId": "门店ID(可选)",
/// "onlyOverdue": true
/// }
/// ```
///
/// 参数说明:
/// - storeId: 门店ID,可选,用于筛选特定门店
/// - onlyOverdue: 是否只查询已到期的提醒,默认true
/// </remarks>
/// <param name="input">查询输入</param>
/// <returns>付款提醒列表</returns>
/// <response code="200">查询成功</response>
/// <response code="500">服务器错误</response>
[HttpPost("GetPaymentReminderList")]
public async Task<List<PaymentReminderListOutput>> GetPaymentReminderListAsync([FromBody] PaymentReminderListInput input = null)
{
try
{
if (input == null)
{
input = new PaymentReminderListInput();
}
var now = DateTime.Now.Date;
// 查询需要提醒的合同
var contracts = await _db.Queryable<LqContractEntity>()
.Where(x => x.IsEffective == StatusEnum.有效.GetHashCode())
.Where(x => x.NextPaymentDate != null)
.WhereIF(input.OnlyOverdue, x => x.NextPaymentDate.Value.Date <= now)
.WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), x => x.StoreId == input.StoreId)
.OrderBy(x => x.NextPaymentDate)
.ToListAsync();
if (!contracts.Any())
{
return new List<PaymentReminderListOutput>();
}
var contractIds = contracts.Select(x => x.Id).ToList();
// 查询所有未缴费的明细
var unpaidDetails = await _db.Queryable<LqContractRentDetailEntity>()
.Where(x => contractIds.Contains(x.ContractId))
.Where(x => x.IsEffective == StatusEnum.有效.GetHashCode())
.Where(x => x.IsPaid == 0)
.OrderBy(x => x.DueDate)
.ToListAsync();
// 按合同ID分组,获取每个合同最早未缴费的明细
var contractDetailDict = unpaidDetails
.GroupBy(x => x.ContractId)
.ToDictionary(
g => g.Key,
g => g.OrderBy(x => x.DueDate).First()
);
// 构建返回结果
var result = new List<PaymentReminderListOutput>();
foreach (var contract in contracts)
{
if (contractDetailDict.ContainsKey(contract.Id))
{
var detail = contractDetailDict[contract.Id];
var daysUntilDue = (detail.DueDate.Date - now).Days;
var isOverdue = detail.DueDate.Date < now;
result.Add(new PaymentReminderListOutput
{
ContractId = contract.Id,
DetailId = detail.Id,
StoreId = contract.StoreId,
StoreName = contract.StoreName,
Title = contract.Title,
Category = contract.Category,
TenantName = contract.TenantName,
PaymentDate = detail.DueDate,
PaymentAmount = detail.DueAmount,
PaymentMonth = detail.PaymentMonth.ToString("yyyy-MM"),
ReminderDate = contract.NextPaymentDate,
ReminderDays = contract.ReminderDays,
DaysUntilPayment = daysUntilDue,
IsOverdue = isOverdue,
PaymentCycle = contract.PaymentCycle,
Remarks = detail.Remarks
});
}
}
return result.OrderBy(x => x.PaymentDate).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "获取付款提醒列表失败");
throw NCCException.Oh($"获取付款提醒列表失败:{ex.Message}");
}
}
#endregion
}
}