iou.js
31.9 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
/**
* Created by Tommy Huang on 18/04/02.
*/
const config = require('config-lite')({
config_basedir: __dirname,
config_dir: 'config'
})
const moment = require('moment')
const _ = require('lodash')
const uuid = require('uuid/v4')
const qr = require('qr-image')
const Helper = require('./helper')
const Op = require('sequelize').Op
const User = require('../models').User
const BorrowList = require('../models').BorrowList
const Friendship = require('../models').Friendship
const Period = require('../models').Period
const Repayment = require('../models').Repayment
const OverdueRecord = require('../models').OverdueRecord
const Redis = require('../models/redis')
exports.create = async function(req, res) {
try {
const idFromToken = req.user.userId
const id = req.body.userId
const amount = parseInt(req.body.amount) || 0
const role = req.body.role
const target = req.body.target
const start = req.body.start
const end = req.body.end
const rate = req.body.rate
const rateValue = parseFloat(req.body.rateValue) || 0
const usage = req.body.usage
const explanation = req.body.explanation || ''
const imgs = req.files || []
if (!id || !role || !target || !start || !end || !usage ||!amount) throw new Error('参数错误')
if (idFromToken !== id) throw new Error('token check fail')
if (amount <= 0) throw new Error('非法的借款金额')
if (parseInt(rate.slice(0, rate.length - 1)) !== rateValue * 100 || rateValue < 0.00 || rateValue > 0.24) throw new Error('非法利率参数')
const startDate = moment(start)
const endDate = moment(end)
const now = moment()
if (startDate.isAfter(now)) throw new Error('借款日期不能晚于今天')
if (endDate.isBefore(now.startOf('day'))) throw new Error('还款日期不能早于今天')
if (startDate.isAfter(endDate)) throw new Error('还款日期最早为借款当日')
const user = await User.findOne({where: {id: id}})
if (!user) throw new Erro('用户不存在')
let imgSrc = []
if (imgs.length) {
imgSrc = await Promise.all(imgs.map(async (item) => {
let fileName = `${uuid()}.${item.mimetype.split('/')[1]}`
let buffer = item.buffer
if (buffer.size >= 2000000) {
buffer = await Helper.imageCompression(item.buffer, 1200)
}
await Helper.writeFile(`${config.img.iouImg}/${fileName}`, buffer)
return fileName
}))
}
imgSrc = imgSrc.join(',')
let newBorrowList = {
id: uuid(),
amount: amount,
startDate: startDate.format(),
endDate: endDate.format(),
rate: rateValue,
usage: usage,
explanation: explanation,
imgs: imgSrc,
targetName: target,
sponsorId: user.id
}
if (role === 'borrower') {
newBorrowList.borrowerId = user.id
} else {
newBorrowList.creditorId = user.id
}
let result = await BorrowList.create(newBorrowList)
let firstPeriod = await Period.create({
id: uuid(),
borrowListId: result.id,
amount: result.amount,
startDate: result.startDate,
endDate: result.endDate,
rate: result.rate,
})
res.json({
success: 1,
id: result.id
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `创建失败:${e.message}`
})
}
}
exports.get = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
const id = req.query.id
if (!id || !userId) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let info = await BorrowList.findOne({
where: {
id: id,
deleted: false
},
attributes: { exclude: ['deleted', 'qr', 'updated_at'] },
include: [{
model: User,
required: false,
as: 'Borrower',
attributes: ['id', 'name', 'username', 'headimgurl']
}, {
model: User,
required: false,
as: 'Creditor',
attributes: ['id', 'name', 'username', 'headimgurl']
}]
})
if (!info) throw new Error('未找到对应的借条')
if (info.sponsorId !== userId) {
if (info.status === '未发起') {
throw new Error('未找到对应的借条')
} else if (info.status === '待确认') {
if (!info.borrowerId || !info.creditorId) {
const target = await User.findOne({where: {id: userId}})
if (target.name) {
if (target.name === info.targetName) {
let update = {}
!!info.borrowerId ? update.creditorId = userId : update.borrowerId = userId
await info.update(update)
} else {
let update = {status: '已驳回'}
update.reason = !!info.borrowerId ? '填写的出借人姓名与邀请对象的姓名不符,系统自动驳回' : '填写的借款人姓名与邀请对象的姓名不符,系统自动驳回'
await info.update(update)
throw new Error('未找到对应的借条')
}
}
} else {
if (info.creditorId !== userId && info.borrowerId !== userId) throw new Error('未找到对应的借条')
}
} else {
if (info.creditorId !== userId && info.borrowerId !== userId) throw new Error('未找到对应的借条')
}
}
res.json({
success: 1,
info: info
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `获取失败:${e.message}`
})
}
}
exports.getIndexList = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
if (!userId) throw new Error('参数错误')
// if (idFromToken !== userId) throw new Error('token check fail')
let [borrowList, creditList, borrowedAmount, creditedAmout] = await Promise.all([
BorrowList.findAll({
where: {
deleted: false,
borrowerId: userId,
status: ['未发起', '待确认', '已驳回']
},
attributes: ['id', 'amount', 'start_date', 'end_date', 'rate', 'status', 'targetName'],
include: [{
model: User,
required: false,
as: 'Creditor',
attributes: ['id', 'name', 'username', 'headimgurl']
}],
order: [['created_at', 'DESC']],
limit: 10
}),
BorrowList.findAll({
where: {
deleted: false,
creditorId: userId,
status: ['未发起', '待确认', '已驳回']
},
attributes: ['id', 'amount', 'start_date', 'end_date', 'rate', 'status', 'targetName'],
include: [{
model: User,
required: false,
as: 'Borrower',
attributes: ['id', 'name', 'username', 'headimgurl']
}],
order: [['created_at', 'DESC']],
limit: 10
}),
BorrowList.sum('amount', {where: {
deleted: false,
borrowerId: userId,
status: ['已生效']
}}),
BorrowList.sum('amount', {where: {
deleted: false,
creditorId: userId,
status: ['已生效']
}}),
])
borrowList = borrowList.map((item) => {
return buildIndexListInfo(item.dataValues, 'borrow')
})
creditList = creditList.map((item) => {
return buildIndexListInfo(item.dataValues, 'credit')
})
res.json({
success: 1,
borrowedAmount: borrowedAmount || 0,
creditedAmout: creditedAmout || 0,
list: {
borrow: borrowList,
credit: creditList
}
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `获取失败:${e.message}`
})
}
}
/**
* 生成首页需要的借条列表格式
* @param {Object} item 借条数据对象
* @param {String} type 正在借款:'borrow', 正在出借: ’credit‘
*/
function buildIndexListInfo(item, type) {
console.log(item)
const duration = moment(item.end_date).diff(moment(item.start_date), 'days')
const timeRemain = moment(item.end_date).diff(moment(), 'days')
const target = type === 'borrow' ? item.Creditor : item.Borrower
const avatar = target ? target.headimgurl : null
item = Object.assign(item, {
duration: duration,
timeRemain: timeRemain,
target: target,
avatar: avatar,
})
return item
}
exports.submitIOU = async function(req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password ) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, sponsorId: userId, status: ['未发起', '已驳回']},
include: [{model: Period}]
})
])
if (!user) throw new Error('用户不存在')
if (!list) throw new Error('未找到对应的借条')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
const shareUrl = Helper.buildShareUrl(list.id)
const qrImg = qr.imageSync(shareUrl, { type: 'svg' })
let update = {
qr: qrImg
}
if (user.id === list.creditorId) {
update.creditorAgree = true
update.status = '待确认'
update.borrowerId = null
}
if (user.id === list.borrowerId) {
update.borrowerAgree = true
update.status = '待确认'
update.creditorId = null
}
let [updateList, updatePeriod] = await Promise.all([
list.update(update),
Period.update({status: '待确认'}, {
where: {borrowListId: list.id,}
})
])
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `借条提交失败:${e.message}`
})
}
}
exports.deleteIOU = async function(req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password ) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({where: {id: id, sponsorId: userId, status: ['未发起', '已驳回']}})
])
if (!user) throw new Error('用户不存在')
if (!list) throw new Error('未找到对应的借条')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
let [listDelete, preiodDelete] = await Promise.all([
list.update({deleted: true}),
Period.update({deleted: true}, {
where: {borrowListId: list.id,}
})
])
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `借条删除失败:${e.message}`
})
}
}
exports.comfirmIOU = async function(req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password ) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: '待确认', deleted: false},
include: [{model: Period, where: {status: '待确认', deleted: false, isExtension: false}}]
})
])
if (!user) throw new Error('用户不存在')
if (!list) throw new Error('未找到对应的借条')
if (list.creditorId !== userId && list.borrowerId !== userId) throw new Error('未找到对应的借条')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (user.name !== list.targetName) throw new Error('借条信息与您的身份信息不符,无法确认该借条')
let update = {}
if (list.borrowerId === user.id && list.sponsorId !== user.id) {
update.borrowerAgree = true
update.status = '已生效'
} else if (list.creditorId === user.id && list.sponsorId !== user.id) {
update.creditorAgree = true
update.status = '已生效'
}
let [result, preiod, friends] = await Promise.all([
list.update(update),
Period.update({status: '已生效'}, {where: {borrowListId: list.id, status: '待确认', deleted: false, isExtension: false}}),
Friendship.findOne({
where: {userId: user.id, friendId: list.sponsorId},
})
])
if (!friends) {
friends = await Friendship.bulkCreate([
{userId: user.id, friendId: list.sponsorId},
{friendId: user.id, userId: list.sponsorId},
])
}
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `借条确认失败:${e.message}`
})
}
}
exports.rejectIOU = async function(req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password ) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({where: {id: id, status: '待确认'}})
])
if (!user) throw new Error('用户不存在')
if (!list) throw new Error('未找到对应的借条')
if (list.creditorId !== userId && list.borrowerId !== userId) throw new Error('未找到对应的借条')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (user.name !== list.targetName) throw new Error('借条信息与您的身份信息不符,无法驳回该借条')
let [listResult, preiodResult] = await Promise.all([
list.update({
status: '已驳回',
reason: `${list.borrowerId === user.id ? '借款' : '出借'}方主动驳回`
}),
Period.update({
status: '已驳回',
}, {where: {borrowListId: list.id, status: '待确认', deleted: false, isExtension: false}})
])
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `借条驳回失败:${e.message}`
})
}
}
exports.shareInfo = async function(req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
const id = req.query.id
if (!id || !userId) throw new Error('未找到对应的借条')
if (idFromToken !== userId) throw new Error('token check fail')
let list = await BorrowList.findOne({
where: {
id: id,
sponsorId: userId,
status: '待确认'
}
})
if (!list) throw new Error('未找到对应的借条')
const shareUrl = Helper.buildShareUrl(list.id)
let qrImg = list.qr
if (!qrImg) {
qrImg = qr.imageSync(shareUrl, { type: 'svg' })
await list.update({qr: qrImg})
}
res.json({
success: 1,
img: qrImg,
url: shareUrl,
amount: list.amount,
startDate: list.startDate,
endDate: list.endDate
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.getHistory = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
const type = req.query.type
const search = req.query.search || ''
const status = req.query.status || ''
let sort = req.query.sort || ''
if (!userId || !type || (type !== 'borrow' && type !== 'credit')) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let where = {
deleted: false,
status: ['已生效', '已逾期']
}
let order = [['endDate', 'ASC']]
if (type === 'borrow') {
where.borrowerId = userId
target = 'Creditor'
} else {
where.creditorId = userId
target = 'Borrower'
}
if (status !== '') where.status = status
sort = sort.split(',')
if (sort.length === 2 && (sort[1] === 'DESC' || sort[1] === 'ASC')) order = [sort]
let list = await BorrowList.findAll({
where: where,
attributes: ['id', 'amount', 'start_date', 'end_date', 'rate', 'status', 'targetName'],
include: [{
model: User,
where: {
name: {
[Op.like]: `%${search}%`
}
},
as: target,
attributes: ['id', 'name', 'username', 'headimgurl']
}],
order: order,
})
const times = list.length
let total = 0
let interest = 0
let result = []
list = list.map((item) => {
let result = buildIndexListInfo(item.dataValues, type)
total += result.amount
interest += (result.amount * result.rate / 365 * result.duration)
return result
})
interest = Math.floor(interest * 100) / 100
res.json({
success: 1,
list: list,
overview: {
total: total,
interest: interest,
times: times
}
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `获取失败:${e.message}`
})
}
}
exports.getListExtendPreiod = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
const id = req.query.id || ''
if (!userId || !id) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let [list, newCount] = await Promise.all([
Period.findAll({where: {borrowListId: id, isExtension: true}}),
Period.count({where: {borrowListId: id, isExtension: true, status: '待确认'}})
])
res.json({
success: 1,
list: list,
newCount: newCount
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `获取失败:${e.message}`
})
}
}
exports.getConfirmedInfo = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.query.userId
const id = req.query.id
const kind = req.query.kind || 'borrow'
if (!id || !userId) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
let where = {
id: id,
deleted: false,
status: ['已生效', '已还清', '已逾期']
}
kind === 'borrow' ? where.borrowerId = userId : where.creditorId = userId
let info = await BorrowList.findOne({
where: where,
attributes: { exclude: ['deleted', 'qr', 'updated_at', 'sponsorId', 'creditorAgree', 'borrowerAgree', 'targetName', 'created_at', 'imgs'] },
include: [{
model: User,
as: 'Borrower',
attributes: ['id', 'name', 'username', 'headimgurl']
}, {
model: User,
as: 'Creditor',
attributes: ['id', 'name', 'username', 'headimgurl']
}, {
model: Period,
required: false,
where: {borrowListId: id, isExtension: true, deleted: false},
attributes: ['id', 'start_date', 'end_date', 'rate', 'status', 'amount', 'created_at']
}, {
model: Repayment,
required: false,
where: {borrowListId: id, deleted: false},
attributes: ['id', 'repayment_date', 'status', 'amount']
}]
})
if (!info) throw new Error('未找到对应的借条')
let timeRemain = 0
let duration = moment(info.endDate).diff(moment(info.startDate), 'days')
if (info.status === '已生效') {
timeRemain = moment(info.endDate).diff(moment(), 'days')
}
if (info.status === '已逾期') {
timeRemain = moment().diff(moment(info.endDate), 'days')
}
info.dataValues.timeRemain = timeRemain
info.dataValues.duration = duration
res.json({
success: 1,
info: info
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `获取失败:${e.message}`
})
}
}
exports.createRepayment = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list, repayment] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({where: {id: id, status: ['已生效', '已逾期'], borrowerId: userId}}),
Repayment.findAll({
where: {
borrowListId: id,
status: '待确认'
}
})
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的借条')
if (!!repayment.length) throw new Error('您有还款请求正待确认中,请勿重复提交')
let duration = moment(list.endDate).diff(moment(list.startDate), 'days')
let amount = Math.floor(list.amount * list.rate / 365 * duration * 100) / 100 + list.amount
let newRepayment = await Repayment.create({
id: uuid(),
borrowListId: list.id,
amount: amount,
repaymentDate: moment().format(),
})
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.writeOffs = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], creditorId: userId},
include: [{
model: OverdueRecord,
required: false
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的借条')
const repaymentDate = moment().startOf('day').format()
if (list.status !== '已逾期' && !list.overdue_records.length) {
let [listUpdate, repaymentUpdate] = await Promise.all([
list.update({
status: '已还清'
}),
Repayment.update({status: '交易关闭'}, {where: {borrowListId: list.id, status: '待确认'}})
])
} else {
let [listUpdate, repaymentUpdate, updateOverdueRecords] = await Promise.all([
list.update({
status: '已还清',
repaymentDate: repaymentDate
}),
Repayment.update({status: '交易关闭'}, {where: {borrowListId: list.id, status: '待确认'}}),
list.overdue_records[0].update({
status: '已还清',
endDate: repaymentDate
})
])
}
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.repaymentConfirm = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], creditorId: userId},
attributes: ['id', 'creditorId', 'status'],
include: [{
model: Repayment,
where: {
status: '待确认'
}
}, {
model: OverdueRecord,
required: false
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的还款记录')
const repaymentDate = moment().startOf('day').format()
if (list.status !== '已逾期' && !list.overdue_records.length) {
let [listUpdate, repaymentUpdate] = await Promise.all([
list.update({
status: '已还清'
}),
Repayment.update({status: '已确认'}, {where: {id: list.repayment_records[0].id}})
])
} else {
let [listUpdate, repaymentUpdate, updateOverdueRecords] = await Promise.all([
list.update({
status: '已还清',
repaymentDate: repaymentDate
}),
Repayment.update({status: '已确认'}, {where: {id: list.repayment_records[0].id}}),
list.overdue_records[0].update({
status: '已还清',
endDate: repaymentDate
})
])
}
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.repaymentReject = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], creditorId: userId},
attributes: ['id', 'creditorId', 'status'],
include: [{
model: Repayment,
where: {
status: '待确认'
}
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的还款记录')
let repaymentUpdate = await Repayment.update({status: '已驳回'}, {where: {id: list.repayment_records[0].id}})
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.createExtendPreiod = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
let endDate = req.body.endDate
if (!id || !userId || !password || !endDate) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], creditorId: userId},
attributes: ['id', 'creditorId', 'borrowerId', 'endDate', 'status', 'rate', 'amount'],
include: [{
model: Period,
required: false,
where: {
status: '待确认',
deleted: false
}
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的借条')
if (!!list.periods.length) throw new Error('您有还款请求正待确认中,请勿重复提交')
const startDate = moment(list.endDate)
endDate = moment(endDate)
const now = moment()
if (endDate.isBefore(now.startOf('day'))) throw new Error('展期结束日期不能早于今天')
if (startDate.isAfter(endDate)) throw new Erro('展期结束日期最早为展期开始当日')
let period = await Period.create({
id: uuid(),
borrowListId: list.id,
startDate: startDate.format(),
endDate: endDate.format(),
rate: list.rate,
amount: list.amount,
isExtension: true,
status: '待确认'
})
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.periodConfirm = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], borrowerId: userId},
attributes: ['id', 'creditorId', 'borrowerId', 'endDate', 'status', 'rate', 'amount'],
include: [{
model: Period,
where: {
status: '待确认',
deleted: false
}
}, {
model: OverdueRecord,
required: false
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的展期记录')
let newEnd = moment(list.periods[0].endDate)
let newStatus = newEnd.isAfter(moment()) ? '已生效' : '已逾期'
if (list.status !== '已逾期' && !list.overdue_records.length) {
let [listUpdate, periodUpdate] = await Promise.all([
list.update({
status: newStatus,
endDate: newEnd.format()
}),
Period.update({status: '已确认'}, {where: {id: list.periods[0].id}})
])
} else {
const repaymentDate = moment().startOf('day').format()
let [listUpdate, periodUpdate, updateOverdueRecords] = await Promise.all([
list.update({
status: newStatus,
endDate: newEnd.format()
}),
Period.update({status: '已确认'}, {where: {id: list.periods[0].id}}),
list.overdue_records[0].update({
status: '已展期',
endDate: repaymentDate
})
])
}
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.periodReject = async function (req, res) {
try {
const idFromToken = req.user.userId
const userId = req.body.userId
const id = req.body.id
const password = req.body.password
if (!id || !userId || !password) throw new Error('参数错误')
if (idFromToken !== userId) throw new Error('token check fail')
const [user, list] = await Promise.all([
User.findOne({where: {id: userId}}),
BorrowList.findOne({
where: {id: id, status: ['已生效', '已逾期'], borrowerId: userId},
attributes: ['id', 'creditorId', 'borrowerId', 'endDate', 'status', 'rate', 'amount'],
include: [{
model: Period,
where: {
status: '待确认',
deleted: false
}
}]
}),
])
if (!user) throw new Error('用户不存在')
if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
if (!list) throw new Error('未找到对应的展期记录')
let periodUpdate = await Period.update({status: '已拒绝'}, {where: {id: list.periods[0].id}})
res.json({
success: 1,
})
} catch (e) {
console.log(e)
res.json({
success: 0,
msg: `${e.message}`
})
}
}
exports.overdueCheck = async function() {
try {
let newOverdueList = await BorrowList.findAll({
where: {
status: '已生效',
endDate: {
[Op.lt]: moment().format()
}
}
})
const ids = []
let newOverdueRecordItems = newOverdueList.map((item) => {
ids.push(item.id)
return {
id: uuid(),
userId: item.borrowerId,
borrowListId: item.id,
startDate: moment().startOf('day').format()
}
})
let [statusUpdate, newOverdueRecords] = await Promise.all([
BorrowList.update({status: '已逾期'}, {
where: {
id: ids
}
}),
OverdueRecord.bulkCreate(newOverdueRecordItems)
])
} catch (e) {
console.log(e)
}
}