|
@@ -3,20 +3,49 @@ const { CrudService } = require('naf-framework-mongoose-free/lib/service');
|
|
|
const { BusinessError, ErrorCode } = require('naf-core').Error;
|
|
|
const _ = require('lodash');
|
|
|
const assert = require('assert');
|
|
|
+const Transaction = require('mongoose-transactions');
|
|
|
|
|
|
//
|
|
|
class RelationStudentSchoolService extends CrudService {
|
|
|
constructor(ctx) {
|
|
|
super(ctx, 'relationstudentschool');
|
|
|
this.model = this.ctx.model.Relation.RelationStudentSchool;
|
|
|
+ this.studentModel = this.ctx.model.User.Student;
|
|
|
+ this.tran = new Transaction();
|
|
|
}
|
|
|
// 创建关系前,先查下有没有,有就别创建了
|
|
|
async beforeCreate(data) {
|
|
|
const { student_id, school_id } = data;
|
|
|
const num = await this.model.count({ student_id, school_id });
|
|
|
- if (num <= 0) { return data; }
|
|
|
+ if (num <= 0) {
|
|
|
+ return data;
|
|
|
+ }
|
|
|
throw new BusinessError(ErrorCode.DATA_EXISTED, '学员已入学,无需重复添加');
|
|
|
}
|
|
|
+
|
|
|
+ // 删除关系,同时将用户变为不同用户
|
|
|
+ async delete(filter) {
|
|
|
+ assert(filter);
|
|
|
+ filter = await this.beforeDelete(filter);
|
|
|
+ const { _id, id } = filter;
|
|
|
+ try {
|
|
|
+ const data = await this.model.findById(_id || id);
|
|
|
+ if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要删除的数据');
|
|
|
+ const { student_id } = data;
|
|
|
+ const student = await this.studentModel.findById(student_id);
|
|
|
+ const { user_id } = student;
|
|
|
+ this.tran.remove('RelationStudentSchool', _id || id);
|
|
|
+ this.tran.remove('Student', student_id);
|
|
|
+ this.tran.update('User', user_id, { type: '0' });
|
|
|
+ await this.tran.run();
|
|
|
+ } catch (error) {
|
|
|
+ await this.tran.rollback();
|
|
|
+ throw new Error(error);
|
|
|
+ } finally {
|
|
|
+ this.tran.clean();
|
|
|
+ }
|
|
|
+ return 'deleted';
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
module.exports = RelationStudentSchoolService;
|