Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] [MicroCredit] add repayment rate #998

Merged
merged 3 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions packages/api/src/controllers/v2/microcredit/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,33 @@ class MicroCreditController {
return;
}

this.microCreditService
.updateApplication(
req.body.map(a => a.applicationId),
req.body.map(a => a.status)
)
.then(r => {
// we will do the cleaning cache here since this only needs to clean cache
// for applications, but if accepted it also needs to clean cache for borrowers list
// and the chain subscriber will do that
if (req.user?.userId) {
utils.cache.cleanMicroCreditApplicationsCache(req.user?.userId);
}
standardResponse(res, 201, true, r);
})
.catch(e => standardResponse(res, 400, false, '', { error: e }));
const repaymentsDefined = req.body.filter(a => a.repaymentRate !== undefined);

if (repaymentsDefined.length > 0) {
this.microCreditService
.updateRepaymentRate(
req.body.map(a => a.applicationId),
req.body.map(a => a.repaymentRate)
)
.then(r => standardResponse(res, 201, true, r))
.catch(e => standardResponse(res, 400, false, '', { error: e }));
} else {
this.microCreditService
.updateApplication(
req.body.map(a => a.applicationId),
req.body.map(a => a.status)
)
.then(r => {
// we will do the cleaning cache here since this only needs to clean cache
// for applications, but if accepted it also needs to clean cache for borrowers list
// and the chain subscriber will do that
if (req.user?.userId) {
utils.cache.cleanMicroCreditApplicationsCache(req.user?.userId);
}
standardResponse(res, 201, true, r);
})
.catch(e => standardResponse(res, 400, false, '', { error: e }));
}
};

saveForm = async (req: RequestWithUser, res: Response): Promise<void> => {
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/routes/v2/microcredit/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export default (route: Router): void => {
* tags:
* - "microcredit"
* summary: "Update microcredit applications"
* description: "Status can be 0: draft, 1: pending, 2: in-review, 3: requested-changes, 4: interview, 5: approved, 6: rejected"
* description: "repaymentRate is in seconds. Status can be 0: draft, 1: pending, 2: in-review, 3: requested-changes, 4: interview, 5: approved, 6: rejected"
* requestBody:
* required: true
* content:
Expand All @@ -113,6 +113,9 @@ export default (route: Router): void => {
* status:
* type: number
* example: 1
* repaymentRate:
* type: number
* example: 604800
* responses:
* "200":
* description: "Success"
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/routes/v2/microcredit/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default (route: Router): void => {
* name: filter
* schema:
* type: string
* enum: [not-claimed, ontrack, need-help, repaid, urgent]
* enum: [not-claimed, ontrack, need-help, repaid, urgent, failed-repayment]
* required: false
* description: optional filter (leave it undefined to get all)
* - in: query
Expand Down
10 changes: 7 additions & 3 deletions packages/api/src/validators/microcredit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const validator = createValidator();
type ListBorrowersType = {
offset?: number;
limit?: number;
filter?: 'not-claimed' | 'ontrack' | 'need-help' | 'repaid' | 'urgent';
filter?: 'not-claimed' | 'ontrack' | 'need-help' | 'repaid' | 'urgent' | 'failed-repayment';
orderBy?:
| 'amount'
| 'amount:asc'
Expand Down Expand Up @@ -39,7 +39,9 @@ type ListApplicationsType = {
const queryListBorrowersSchema = defaultSchema.object<ListBorrowersType>({
offset: Joi.number().optional().default(0),
limit: Joi.number().optional().max(20).default(10),
filter: Joi.string().optional().valid('not-claimed', 'ontrack', 'need-help', 'repaid', 'urgent'),
filter: Joi.string()
.optional()
.valid('not-claimed', 'ontrack', 'need-help', 'repaid', 'urgent', 'failed-repayment'),
orderBy: Joi.string()
.optional()
.valid(
Expand Down Expand Up @@ -134,6 +136,7 @@ type PostDocsRequestType = {
type PutApplicationsRequestType = [
{
applicationId: number;
repaymentRate: number;
status: number;
}
];
Expand Down Expand Up @@ -164,7 +167,8 @@ const putApplicationsValidator = celebrate({
.items(
Joi.object({
applicationId: Joi.number().required(),
status: Joi.number().required()
repaymentRate: Joi.number().optional(),
status: Joi.number().optional()
}).required()
)
.required()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,25 @@ module.exports = {
allowNull: false,
type: Sequelize.INTEGER
},
applicationId: {
allowNull: true,
type: Sequelize.INTEGER
},
performance: {
allowNull: false,
type: Sequelize.INTEGER,
defaultValue: 100
},
repaymentRate: {
allowNull: true,
type: Sequelize.INTEGER
},
lastNotificationRepayment: {
allowNull: true,
type: Sequelize.DATE
},
manager: {
allowNull: false,
allowNull: true,
type: Sequelize.STRING(48)
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
if (process.env.NODE_ENV === 'test') {
return;
}

await queryInterface.addColumn('microcredit_borrowers', 'repaymentRate', {
allowNull: true,
type: Sequelize.INTEGER
});
await queryInterface.addColumn('microcredit_borrowers', 'applicationId', {
allowNull: true,
type: Sequelize.INTEGER
});
await queryInterface.changeColumn('microcredit_borrowers', 'manager', {
allowNull: true,
type: Sequelize.STRING(48)
});
await queryInterface.changeColumn('microcredit_borrowers', 'performance', {
allowNull: false,
type: Sequelize.INTEGER,
defaultValue: 100
});
},
async down(queryInterface, Sequelize) {
//
}
};
30 changes: 27 additions & 3 deletions packages/core/src/database/models/microCredit/borrowers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { SubgraphMicroCreditBorrowersModel } from './subgraphBorrowers';
export class MicroCreditBorrowersModel extends Model<MicroCreditBorrowers, MicroCreditBorrowersCreation> {
public id!: number;
public userId!: number;
public applicationId!: number;
public performance!: number;
public repaymentRate!: number;
public lastNotificationRepayment!: Date;
public manager!: string;

Expand All @@ -17,7 +19,7 @@ export class MicroCreditBorrowersModel extends Model<MicroCreditBorrowers, Micro
}

export function initializeMicroCreditBorrowers(sequelize: Sequelize): typeof MicroCreditBorrowersModel {
const { appUser } = sequelize.models as DbModels;
const { appUser, microCreditApplications } = sequelize.models as DbModels;
MicroCreditBorrowersModel.init(
{
id: {
Expand All @@ -34,24 +36,46 @@ export function initializeMicroCreditBorrowers(sequelize: Sequelize): typeof Mic
onDelete: 'CASCADE',
allowNull: false
},
applicationId: {
type: DataTypes.INTEGER,
references: {
model: microCreditApplications,
key: 'id'
},
onDelete: 'CASCADE',
// should be false, but old borrowers did not had applications
allowNull: true
},
performance: {
allowNull: false,
type: DataTypes.INTEGER,
defaultValue: 100
},
repaymentRate: {
allowNull: true,
type: DataTypes.INTEGER
},
lastNotificationRepayment: {
allowNull: true,
type: DataTypes.DATE
},
manager: {
allowNull: false,
allowNull: true,
type: DataTypes.STRING(48)
}
},
{
tableName: 'microcredit_borrowers',
modelName: 'microCreditBorrowers',
sequelize,
timestamps: false
timestamps: false,
// ensure that applicationId + userId is unique
indexes: [
{
unique: true,
fields: ['applicationId', 'userId']
}
]
}
);
return MicroCreditBorrowersModel;
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/interfaces/microCredit/borrowers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
export interface MicroCreditBorrowers {
id: number;
userId: number;
applicationId: number;
performance: number;
repaymentRate: number;
lastNotificationRepayment: Date | null;
manager: string;
}

export interface MicroCreditBorrowersCreation {
userId: number;
performance: number;
applicationId: number;
performance?: number;
repaymentRate?: number;
lastNotificationRepayment?: Date;
manager: string;
manager?: string;
}
30 changes: 29 additions & 1 deletion packages/core/src/services/microcredit/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,12 @@ export default class MicroCreditCreate {
},
include: [
{
// get last application only
model: models.microCreditApplications,
as: 'microCreditApplications',
attributes: ['id']
attributes: ['id'],
order: [['id', 'DESC']],
limit: 1
}
]
});
Expand Down Expand Up @@ -206,6 +209,31 @@ export default class MicroCreditCreate {
);
}

public async updateRepaymentRate(applicationId_: number[], repaymentRate_: number[]): Promise<void> {
for (let x = 0; x < applicationId_.length; x++) {
const applicationId = applicationId_[x];
const repaymentRate = repaymentRate_[x];

const application = await models.microCreditApplications.findOne({
where: {
id: applicationId
}
});
const borrowerUserId = application!.userId;

await models.microCreditBorrowers.upsert(
{
userId: borrowerUserId,
applicationId,
repaymentRate
},
{
conflictFields: ['userId', 'applicationId']
}
);
}
}

public saveForm = async (
userId: number,
form: object,
Expand Down
42 changes: 31 additions & 11 deletions packages/core/src/services/microcredit/list.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MicroCreditApplication, MicroCreditApplicationStatus } from '../../interfaces/microCredit/applications';
import { MicroCreditBorrowers } from '../../interfaces/microCredit/borrowers';
import { Op, Order, WhereOptions, col, fn, literal } from 'sequelize';
import { SubgraphMicroCreditBorrowers } from '../../interfaces/microCredit/subgraphBorrowers';
import { config } from '../../..';
import { getAddress } from '@ethersproject/address';
import {
Expand Down Expand Up @@ -70,7 +71,7 @@ export type GetBorrowersQuery = {
offset?: number;
limit?: number;
addedBy?: string;
filter?: 'all' | 'not-claimed' | 'ontrack' | 'need-help' | 'repaid' | 'urgent';
filter?: 'all' | 'not-claimed' | 'ontrack' | 'need-help' | 'repaid' | 'urgent' | 'failed-repayment';
orderBy?:
| 'amount'
| 'amount:asc'
Expand Down Expand Up @@ -104,12 +105,15 @@ export default class MicroCreditList {
maturity: number;
amount: number;
period: number;
dailyInterest: number;
claimed: number;
repaid: number;
lastRepayment: number;
lastRepaymentAmount: number;
lastDebt: number;
dailyInterest?: number;
claimed?: number;
repaid?: number;
lastRepayment?: number;
lastRepaymentAmount?: number;
lastDebt?: number;
//
performance: number;
repaymentRate: number | null;
};
}[];
}> => {
Expand Down Expand Up @@ -179,13 +183,26 @@ export default class MicroCreditList {
literal(`(claimed + period) <= ${Math.trunc(limitDate.getTime() / 1000)}`)
]
};
case 'failed-repayment':
where = {
...where,
repaymentRate: { [Op.ne]: null } as any
};
return {
[Op.and]: [
{ status: 1 },
{ lastDebt: { [Op.gt]: 0 } },
{ lastRepayment: { [Op.ne]: null } },
literal(`(loan."lastRepayment" + "repaymentRate") < ${Math.trunc(now.getTime() / 1000)}`)
]
};
default:
return {};
}
};

const rBorrowers = await models.microCreditBorrowers.findAndCountAll({
attributes: ['performance'],
attributes: ['performance', 'repaymentRate'],
where: {
...where,
manager: query.addedBy
Expand All @@ -196,7 +213,7 @@ export default class MicroCreditList {
include: [
{
model: models.appUser,
attributes: ['address', 'firstName', 'lastName', 'avatarMediaPath'],
attributes: ['id', 'address', 'firstName', 'lastName', 'avatarMediaPath'],
as: 'user',
required: true
},
Expand Down Expand Up @@ -226,8 +243,11 @@ export default class MicroCreditList {
count: rBorrowers.count,
rows: rBorrowers.rows.map(r => ({
...r.user!.toJSON(),
loan: r.loan!,
performance: r.performance
loan: {
...(r.loan!.toJSON() as SubgraphMicroCreditBorrowers & { maturity: number }),
performance: r.performance,
repaymentRate: r.repaymentRate
}
}))
};
};
Expand Down
Loading
Loading