iou.js
16.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
/**
* Created by Tommy Huang on 18/04/02.
*/
const config = require('config-lite')({
config_basedir: __dirname,
config_dir: 'config'
})
const moment = require('moment')
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 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)
if (startDate.isAfter(endDate)) throw new Erro('还款日期最早为借款当日')
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)
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
},
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: ['未发起', '已驳回']}})
])
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 result = await list.update(update)
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 result = await list.update({
deleted: true
})
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: '待确认'}})
])
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, friends] = await Promise.all([
list.update(update),
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.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 result = await list.update({
deleted: true
})
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 result = await list.update({
status: '已驳回',
reason: `${list.borrowerId === user.id ? '借款' : '出借'}方主动驳回`
})
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
})
} 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', 'DESC']]
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}`
})
}
}